This is my html page for adding data
php script for inserting data into database placements and csv file into "eligilist" database. NOTE: the rownd1,rownd2.... are javascript event based on number of rounds are selected then javascript code shows number of selection boxes which is rownd1, rownd2,rownd3 so these are the values based on user selection.
<?php
require_once('dbconfig/config.php');
if(isset($_POST['submit']))
{
$name = $_POST['placename'];
$eligibility = $_POST['elig'];
$backlogs=$_POST['blogs'];
$rounds=$_POST['rownds'];
if( isset($_POST["rownd1"]) && isset($_POST["rownd2"] ) && isset($_POST["rownd3"] ) && isset($_POST["rownd4"] ))
{
$round1=$_POST['rownd1'];
$round2=$_POST['rownd2'];
$round3=$_POST['rownd3'];
$round4=$_POST['rownd4'];
}
elseif (isset($_POST["rownd1"]) && isset($_POST["rownd2"] ) && isset($_POST["rownd3"] )) {
$round1=$_POST['rownd1'];
$round2=$_POST['rownd2'];
$round3=$_POST['rownd3'];
$round4=NULL;
}
elseif (isset($_POST["rownd1"]) && isset($_POST["rownd2"] )) {
$round1=$_POST['rownd1'];
$round2=$_POST['rownd2'];
$round3=NULL;
$round4=NULL;
}
elseif (isset($_POST["rownd1"]))
{
$round1=$_POST['rownd1'];
$round2=NULL;
$round3=NULL;
$round4=NULL;
}
$venu=$_POST['location'];
$date=$_POST['InterviewTime'];
$fileName = $_FILES['myFile']['name'];
$fileTmpName = $_FILES['myFile']['tmp_name'];
$fileExtension = pathinfo($fileName,PATHINFO_EXTENSION);
$allowedType = array('csv');
if(!in_array($fileExtension, $allowedType))
{
echo '<script type="text/javascript"> alert("invalid file extension")</script>';
} else{
$handle = fopen($fileTmpName,'r');
while (($myData = fgetcsv($handle,1000,',')) !== FALSE){
$fname = $myData[0];
$regno = $myData[1];
$branch = $myData[2];
$percentage = $myData[3];
$back_logs = $myData[4];
$mobile = $myData[5];
$email = $myData[6];
$query = "INSERT INTO eliglist (sr, fname, regno, branch, percentage, back_logs, mobile, email) VALUES (NULL,".$fname.",".$regno.",".$branch.",".$percentage.",".$back_logs.",".$mobile.",".$email.")";
$query_run = mysqli_query($con,$query);
}
$query1 = "INSERT INTO `placements` (`id`,`name`,`eligibility`,`backlogs`,`rounds`,`round1`,`round2`,`round3`,`round4`,`venu`,`date`) VALUES (NULL,'$name','$eligibility','$backlogs','$rounds','$round1','$round2','$round3','$round4','$venu','$date')";
$query_run1 = mysqli_query($con,$query1);
if($query_run && $query_run1)
{
echo '<script type="text/javascript"> alert("Successfully added")</script>';
}
else
{
echo '<script type="text/javascript"> alert("Error!")</script>';
}
}
}
}
?>
my problem is when i was submit all data along with csv file it shows error...but the except csv file remaining data are inserted into placements database the only problem with csv file not storing in eligilist table in databse...please help me and resolve my code if any errors...thank you.
You need quotes round the field values in your insert (the same way you do it for the placements table)...
$query = "INSERT INTO eliglist (sr, fname, regno, branch, percentage, back_logs, mobile, email)
VALUES (NULL,'$fname','$regno','$branch','$percentage','$back_logs','$mobile','$email')";
BUT you should be using prepared statements and bind variables as this helps prevent several problems...
$query = "INSERT INTO eliglist (sr, fname, regno, branch, percentage, back_logs, mobile, email)
VALUES (NULL,?,?,?,?,?,?,?)";
$prep = mysqli_prepare ( $con,$query );
$handle = fopen($fileTmpName,'r');
while (($myData = fgetcsv($handle,1000,',')) !== FALSE){
$fname = $myData[0];
$regno = $myData[1];
$branch = $myData[2];
$percentage = $myData[3];
$back_logs = $myData[4];
$mobile = $myData[5];
$email = $myData[6];
mysqli_stmt_bind_param($prep, "sssssss", $fname,
$regno, $branch, $percentage, $back_logs,
$mobile, $email );
mysqli_stmt_execute($prep);
}
Related
I'm trying to set a condition wherein if the 'filefield' is empty, it will skip the insert in DB as it is only an option and just proceed in inserting of 'name' and 'description' in the DB, which will never be empty.
<?php
include("connection.php");
if (isset($_POST['submit']))
{
$name = mysqli_real_escape_string($conn, $_POST['name']);
$description = mysqli_real_escape_string($conn, $_POST['description']);
if ($name == '' || $description == '' )
{
$error = 'ERROR: Please fill required fields!';
renderForm($name, $description);
}
else
{
if(!empty($_FILES['filefield'])){
if(isset($_FILES['filefield'])){
$file=$_FILES['filefield'];
$upload_directory='uploads/';
$ext_str = "gif,jpg,jpeg,mp3,tiff,bmp,doc,docx,ppt,pptx,txt,pdf";
$allowed_extensions=explode(',',$ext_str);
$ext = substr($file['name'], strrpos($file['name'], '.') + 1);
if (!in_array($ext, $allowed_extensions) )
{
echo '<script language="javascript">';
echo 'alert("file type not allowed for upload")';
echo '</script>';
exit();
}
$path=md5(microtime()).'.'.$ext;
if(move_uploaded_file($file['tmp_name'],$upload_directory.$path)){
$filefield = $_FILES["filefield"]["name"];
$path = $path."/".$filefield;
}
}
}
}
if (!empty($_FILES['filefield']) || !isset($_FILES['filefield'])) {
$query = "INSERT INTO `item`(`name`, `description`, `path`) VALUES ('$name','$description','$path')";
}
else {
$query = "INSERT INTO `item`(`name`, `description`) VALUES ('$name','$description')";
}
$result = mysqli_query($conn, $query);
if($result)
{
echo '<script language="javascript">';
echo 'alert("Success!")';
echo '</script>';
exit();
}
}
?>
I'm not sure how to proceed with the condition. Any help is highly appreciated.
First, close off all of your logic, including if(move_uploaded_file), so that the $query is competely outside of any conditionals. Then it's just a matters of checking whether the filefield was filled out or not. If it's not empty, your $query insert all three fields. If it is, your $query only inserts $name and $description.
This can be seen in the following (heavily cut-down) code:
/* Existing logic */
else
{
if (!empty($_FILES['filefield'])) {
if (isset($_FILES['filefield'])) {
if (move_uploaded_file($file['tmp_name'], $upload_directory.$path)) {
...
$path = $path."/".$filefield;
}
}
}
}
/* Modified logic */
if (!empty($_FILES['filefield']) || !isset($_FILES['filefield'])) {
$query = "INSERT INTO `item`(`name`, `description`, `path`) VALUES ('$name','$description','$path')";
}
else {
$query = "INSERT INTO `item`(`name`, `description`) VALUES ('$name','$description')";
}
$result = mysqli_query($conn, $query);
I have the below code that should add user input into the db, I can't understand why its not adding to db, the email field in the table is a foreign key that references to another table, and I'm using session to store email in the $email and save it to db when user saves data, also I'm accepting date and time from user input which is exactly as per the db format but it still doesn't save, I have tried entering static data as well, not working either. Am I missing something ?
$server = "localhost";
$user = "root";
$pwd = "";
$sql_db = "cabcustomers";
$email = $_SESSION['sesName'];
$conn = #mysqli_connect($server,$user,$pwd,$sql_db);
if (isset ($_POST["name"]) && isset ($_POST["contact"]) && isset ($_POST["unitno"]) && isset ($_POST["streetno"]) && isset ($_POST["streetname"]) && isset ($_POST["suburb"]) && isset ($_POST["destsuburb"]) && isset ($_POST["pickdt"]) && isset ($_POST["picktime"]))
{
$name = $_POST["name"];
$contact = $_POST["contact"];
$unitno = $_POST["unitno"];
$streetno = $_POST["streetno"];
$streetname = $_POST["streetname"];
$suburb = $_POST["suburb"];
$destsuburb = $_POST["destsuburb"];
$pickdt = $_POST["pickdt"];
$picktime = $_POST["picktime"];
if(empty($name) || empty($contact) || empty($unitno) || empty($streetno) || empty($streetname) || empty($suburb) || empty($destsuburb) || empty($pickdt) || empty($picktime))
{
echo "<p>ONE OR MORE OF FIELDS HAVE MISSING INFORMATION, KINDLY CHECK AND TRY AGAIN!</p>";
}
elseif (!is_numeric($contact))
{
echo "<p>CONTACT NUMBER MUST BE NUMERIC!</p>";
}
else
{
$idlen = 7;
$bookingid = uniqid (rand(), true);
$bookingid = "BK" . substr($bookingid, 0, $idlen);
$status = "unassigned";
$pickdt = $pickdt . " " . $picktime;
$query = "insert into bookings (bookingid, pname, contact, unitno, streetno, streetname, suburb, destsuburb, pickupdt, bookingdt, status, email) values ('$bookingid', '$name', '$contact', '$unitno', '$streetno', '$streetname', '$suburb', '$destsuburb','$pickdt', 'NOW()','$status', '$email');";
echo $email;
$result = mysqli_query($conn, $query);
echo $result;
echo "<p>INFORMATION SAVED</p>";
}
mysqli_close($conn);
}
Based on the comments after your initial question, I don't think the connection is the problem, the problem is most likely happening during the INSERT query. Have you tried running the query from phpMyAdmin to troubleshoot the syntax of the query outside of PHP?
It's working, but when I add the data in to my database, the data will be twice. I don't know if my syntax is wrong or my code is wrong.
Here's the structure:
//if submit is clicked
$checkin = $_POST['text_checkin'];
while ($row = mysqli_fetch_array($reservation)) {
if (isset($_POST['submitBtn'])) {
if ($row['reservefrom'] == $checkin) {
echo "Same Date";
return;
}
else
{
$lastname = $_POST['text_lastname'];
$firstname = $_POST['text_firstname'];
$address = $_POST['text_address'];
$tnumber = $_POST['text_tnumber'];
$cnumber = $_POST['text_cnumber'];
$email = $_POST['text_email'];
$checkin = $_POST['text_checkin'];
$checkout = $_POST['text_checkout'];
$room = $_POST['text_room'];
$tour = $_POST['text_tour'];
$guest = $_POST['text_guest'];
$query = "INSERT INTO reservation
(lastname, firstname, homeaddress,
telephonenumber, cellphonenumber, email,
reservefrom, reserveto, room, tour,
guestnumber)
values ('$lastname', '$firstname', '$address',
'$tnumber', '$cnumber', '$email', '$checkin',
'$checkout', '$room', '$tour', '$guest')";
mysqli_query($db, $query);
echo "Data Submitted!";
}
}
}
You're getting multiple inserts because you are looping for each record in $reservations. You should first look into why you are getting multiple records if you expected just a single record reservation.
That aside, alter your code by replacing your while loop with:
if(isset($_POST['submitBtn']) && $row = mysqli_fetch_array($reservation)){
if($row['reservefrom'] == $checkin) die("Same Date");
$lastname = $_POST['text_lastname'];
$firstname = $_POST['text_firstname'];
// ... other values, then execute your query
}else{
// either submitBtn was not posted or no result were found in $reservation
}
I noticed also that you use return in your code, but the code doesn't seem to be within a function so that's confusing. If it is within a function, it's probably a bad idea to echo from within unless the function is specifically meant to send data directly to the browser.
PHP Form Posts to MySQL Database Successfully, But Adds Blank Rows sometimes when registering.
here is my code:
include("includes/db.php");
if (isset($_POST['submit']) && $hidden == "" ) {
$product = mysqli_real_escape_string($bd, $_POST['product']);
$name = mysqli_real_escape_string($bd, $_POST['name']);
$address = mysqli_real_escape_string($bd, $_POST['address']);
$coupon = mysqli_real_escape_string($bd, $_POST['coupon']);
date_default_timezone_set("Asia/Kolkata");
$dates = date('Y-m-d H:i:s');
if (isset($_FILES["invoice_copy"]["name"])) {
$imgpancard = $_FILES["invoice_copy"]["name"];
$tmp_name = $_FILES['invoice_copy']['tmp_name'];
$error = $_FILES['invoice_copy']['error'];
if (!empty($imgpancard)) {
$location = 'doc/';
if (move_uploaded_file($tmp_name, $location.$imgpancard)){
//echo 'Uploaded';
}
}
}
$query = mysqli_query($bd, "SELECT * FROM customer WHERE coupon='".$coupon."'");
if(mysqli_num_rows($query) > 0) {
echo'<script> alert("COUPON ALEARDY EXISTS!");
window.location="register.php";
</script> ';
}
else {
$sql = "INSERT INTO customer (product, customer_name, address, coupon, RegistrationDate, invoice_copy) VALUES ('$product', '$name', '$address', '$coupon', '$dates', '$imgpancard')";
if(mysqli_query($bd, $sql)){
echo'<script> alert("DATA SUBMITTED SUCCESFULLY!");
window.location="index.html"; </script> ';
}
else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($bd);
}
}
}
how to of 10 times one times blank data is inserted.how to avoid it can please tell me , whether code is wrong or not. In every input feild i have used required attribute
I am trying to set up an import/export to MySQL for a CSV file. I have most of it, however I am trying to validate the information. When I validate I want none of the records to be imported to MySQL. The code I currently have will only not import any records after an empty field. I wouldn't normally ask but I am stumped.
<?php
include 'connection.php';
$empty_value_found = false;
$file = $_FILES['file']['tmp_name'];
$handle = fopen ($file,"r");
while(($fileop = fgetcsv($handle,1000,",")) !==false){
$first = trim($fileop[0]);
$last = trim($fileop[1]);
$birthday = trim($fileop[2]);
$age = trim($fileop[3]);
$address = trim($fileop[4]);
if (
empty($first)
|| empty($last)
|| empty($birthday)
|| empty($age)
|| empty($address)
) {
$empty_value_found = true;
echo "empty field please check";
break; // stop our while-loop
}
}
// now we check - if there no empty values
if (!$empty_value_found) {
// we can go through our file again and insert values,
// code is similar to what you have
$sql = mysqli_query($conn,"INSERT INTO `mytable` (first, last, birthday, age, address) VALUES ('$first','$last','$birthday','$age','$address')");
$getdata = "SELECT * FROM mytable";
$results = mysqli_query($conn,$getdata);
if(mysqli_num_rows($results) >=1){
echo "<table><tr><th>First</th><th>Last</th><th>Birthday</th><th>Age</th> <th>Address</th></tr>";
}
while($row = mysqli_fetch_assoc($results)){
echo "<tr><td>" . $row["first"]. "</td><td>" . $row["last"]. "</td><td>" . $row["birthday"]. "</td><td>" . $row["age"]. "</td><td>" . $row["address"]. "</td></tr>";
}
}
echo "</table>";
mysqli_close($conn);
?>
Okay, let's see:
// here you get an array from csv-string
while(($fileop = fgetcsv($handle,1000,",")) !==false){
// first: use trim function to remove spaces from left and right of a value
$first = trim($fileop[0]);
$last = trim($fileop[1]);
$birthday = trim($fileop[2]);
$age = trim($fileop[3]);
$address = trim($fileop[4]);
// now you have five values.
// u want to insert them to database only if they are ALL not empty
// use function empty to check if value is empty
if (!empty($first)
&& !empty($last)
&& !empty($birthday)
&& !empty($age)
&& !empty($address)
) {
$sql = mysqli_query($conn,"INSERT INTO `mytable` (first, last, birthday, age, address) VALUES ('$first','$last','$birthday','$age','$address')");
// other code here
}
}
This script will insert values which are not empty. But still it will ignore rows with empty values.
If you want to check if all fields in all rows of your csv are not empty, then you should do this:
// set a special flag
$empty_value_found = false;
while(($fileop = fgetcsv($handle,1000,",")) !==false){
// first: use trim function to remove spaces from left and right of a value
$first = trim($fileop[0]);
$last = trim($fileop[1]);
$birthday = trim($fileop[2]);
$age = trim($fileop[3]);
$address = trim($fileop[4]);
// now you have five values.
// if any of them is empty - we should NOT go further and stop our cycle
if (empty($first)
|| empty($last)
|| empty($birthday)
|| empty($age)
|| empty($address)
) {
$empty_value_found = true;
break; // stop our while-loop
}
}
// now we check - if there no empty values
if (!$empty_value_found) {
// we can go through our file again and insert values,
// code is similar to what you have
}
So if you want to check