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
Related
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);
}
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?
As you can see in the below PHP code, I am going to get the value for a combobox from a database table. It shows all the columns of the table without any problem, but when I want to pass the value of combobox back to a table, it always passes the value 1. Why?
<?php
$leccom = mysql_query("select Lec_ID, Lec_Name from lecturer") or die(mysql_error());
while ($result = mysql_fetch_array($leccom)) {
$name = $result[Lec_Name];
$id_leccom = $result[Lec_ID];
echo "<option value='$id_leccom'> $name</option>";
}
?>
Next file:
<?php
mysql_select_db('lms', mysql_connect('localhost', 'root', '')) or die(mysql_error());
// Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = #trim($str);
if (get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
// Sanitize the POST values
$filedesc = clean($_POST['pdesc']);
$fname = clean($_POST['Pre_Name']);
$com = clean($_post[$id_Leccom]);
echo $_post['comselection'];
// $subject= clean($_POST['upname']);
// upload random name/number
$rd2 = mt_rand(1000, 9999) . "_File";
// Check that we have a file
if ((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0))
{
// Check if the file is JPEG image and it's size is less than 350Kb
$filename = basename($_FILES['uploaded_file']['name']);
$ext = substr($filename, strrpos($filename, '.') + 1);
if (($ext != "exe") && ($_FILES["uploaded_file"]["type"] != "application/x-msdownload"))
{
// Determine the path to which we want to save this file
// $newname = dirname(__FILE__).'/upload/'.$filename;
$newname = "uploads/" . $rd2 . "-" . $filename;
// Check if the file with the same name is already exists on the server
// Attempt to move the uploaded file to it's new place
if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $newname)))
{
// successful upload
// echo "It's done! The file has been saved as: ".$newname;
// echo "$filedesc,$newname,$fname,$comlec";
mysql_query("INSERT INTO `lms`.`presentation` (`Pre_Name` ,`Path` ,`PLec_ID` ,`pdatein` ,`pdesc`) values ('$fname','$newname','1',NOW(),'$filedesc')") or die("failed");
// mysql_query("INSERT INTO presentation (pdesc,path,pdatein,Pre_Name,plec_id) VALUES ('$filedesc','$newname',NOW(),'$fname','$comlec')") or die("query failed");
// mysql_query("INSERT INTO presentation ('pdesc','path','Pre_Name','PLec_ID') values ('$filedesc','$newname','$fname','$comlec')") ;
header("location: fileupload.php");
}
}
}
?>
$name = $result['Lec_Name'];
$id_leccom = $result['Lec_ID'];
and
echo "<option value='".$id_leccom."'>$name</option>";
I have this script that checks a submitted form. It checks if all fields are all filled out, and checks if the user has submitted the form before. It also checks if the entered data is already in the database or not. When I try to check if the entered data is in the database, it always returns false. My question is: How can I efficiently check if the POST values are the same?
Code:
<?php
error_reporting(E_NOTICE ^ E_ALL);
$Name = $_POST['name'];
$ID = $_POST['id'];
$Topic_1 = $_POST['1'];
$Topic_2 = $_POST['2'];
$Topic_3 = $_POST['3'];
$Topic_4 = $_POST['4'];
$Topic_5 = $_POST['5'];
$Topic_6 = $_POST['6'];
$Topic_7 = $_POST['7'];
$Topic_8 = $_POST['8'];
$Topic_9 = $_POST['9'];
$Topic_10 = $_POST['10'];
$Topic_11 = $_POST['11'];
$Topic_12 = $_POST['12'];
$Topic_13 = $_POST['13'];
$Topic_14 = $_POST['14'];
$Topic_15 = $_POST['15'];
$IP = $_SERVER['REMOTE_ADDR'];
$Connect = new mysqli("127.0.0.1", "root", "", "Data");
$Check = 'SELECT * FROM Submissions WHERE School_ID = "'.$ID.'" AND IP = "'.$IP.'"';
$Insert = 'INSERT INTO Submissions (Name, School_ID, Topic_1, Topic_2, Topic_3, Topic_4, Topic_5, Topic_6, Topic_7, Topic_8, Topic_9, Topic_10, Topic_11, Topic_12, Topic_13, Topic_14, Topic_15, IP) VALUES ("'.$Name.'", "'.$ID.'", "'.$Topic_1.'", "'.$Topic_2.'", "'.$Topic_3.'", "'.$Topic_4.'", "'.$Topic_5.'", "'.$Topic_6.'", "'.$Topic_7.'", "'.$Topic_8.'", "'.$Topic_9.'", "'.$Topic_10.'", "'.$Topic_11.'", "'.$Topic_12.'", "'.$Topic_13.'", "'.$Topic_14.'", "'.$Topic_15.'", "'.$IP.'")';
if($Name && $ID != "")
{
if($Result = $Connect->query($Check))
{
$Rows = $Result->num_rows;
if($Rows == 0)
{
if($_POST != $_POST)
{
if($Go = $Connect->prepare($Insert))
{
if($Go->execute())
{
echo 'Thanks';
}
else
{
echo 'There Was An Error';
}
}
else
{
echo 'There Was An Error';
}
}
else
{
echo 'No Two Values Can Match.';
}
}
else
{
echo 'You Cant Vote Twice.';
}
$Result->close();
}
else
{
echo 'There Was An Error.';
}
}
else
{
echo 'Please Fill Out All Fields';
}
$Connect->close();
Your if statement should look like
if($name != "" && $check != "")
Here's the error:
if($_POST != $_POST)
You do probably want to compare the result from the db with the $_POST instead.
$Row = $Result->fetch_assoc();
if($Row != $_POST)
Prior to doing a comparison use var_dump() on the variables to check what they actually contain.
var_dump($Name);
var_dump($ID);
exit();
Then check for a negative or positive match.
if( !empty($Name) && empty($ID) ){
exit('ah, name filled in but not id ...');
}
You can even spoof that in a separate file.
<?php
$Name = 'Bob';
$ID = ''; // or use 0 or any test you want
var_dump($Name);
var_dump($ID);
if( !empty($Name) && empty($ID) ){
exit('ah, name filled in but not id ...');
}
Isolating problems like this will help you develop incrementally, get something working, then add more lines till you arrive at your destination.
To check if not two POST values are the same:
array_diff($_POST, array_unique($_POST));
What you looking for is following
$_POST['1'] = 'a';
$_POST['2'] = 'b';
$_POST['3'] = 'c';
$_POST['4'] = 'a';
$_POST['5'] = 'd';
$results = array_unique($_POST);
var_dump($results);
returns:
array
1 => string 'a' (length=1)
2 => string 'b' (length=1)
3 => string 'c' (length=1)
5 => string 'd' (length=1)
You can't really so easily check if a person did submit a form before.
One way is to add one more hidden field to form if the request came with POST.
Something like that:
<form method="POST" action="">
<?php
if(isset($_POST['submit'])) {
echo '<input type="hidden" name="second_post" value="1">';
} ?>
<!-- Other form items -->
<input type="submit" name="submit" value="1">
</form>
Then you can check is it a second time with:
if(isset($_POST['second_post'])) {
// Second time of form post;
} else {
// First (or zero) time post.
}
require_once('mysqli_connect.php');
$errors = array();
if(empty($_POST['senFirstName']) && empty($_POST['senLastName'])
&& empty($_POST['recFirstName']) && empty($_POST['recLastName'])
&& empty($_POST['proName']) && empty($_POST['proWeight'])
&& empty($_POST['traNo']) && empty($_POST['shipDate'])
&& empty($_POST['deliDate'])) {
$errors[] = 'Please make sure you type in all the information.';
}
else {
$sfn = mysqli_real_escape_string($dbc, trim($_POST['senFirstName']));
$sln = mysqli_real_escape_string($dbc, trim($_POST['senLastName']));
$rfn = mysqli_real_escape_string($dbc, trim($_POST['recFirstName']));
$rln = mysqli_real_escape_string($dbc, trim($_POST['recLastName']));
$pn = mysqli_real_escape_string($dbc, trim($_POST['proName']));
$pw = mysqli_real_escape_string($dbc, trim($_POST['proWeight']));
$traNo = mysqli_real_escape_string($dbc, trim($_POST['traNo']));
$shipDate = mysqli_real_escape_string($dbc, trim($_POST['shipDate']));
$deliDate = mysqli_real_escape_string($dbc, trim($_POST['deliDate']));
$status = mysqli_real_escape_string($dbc, trim($_POST['status']));
$shiptype = mysqli_real_escape_string($dbc, trim($_POST['shiptype']));
}
if(empty($errors)) { // If everything's OK.
$query = "SELECT traNo, CONCAT(recFirstName, ' ', recLastName) AS recieverName, proName, CONCAT(senFirstName, ' ', senLastName) AS senderName, status, shiptype FROM tracking, rel_tracking_reciever, reciever, product, sender
WHERE traNo='$traNo' AND tracking.traId = rel_tracking_reciever.traId AND reciever.recId = rel_tracking_reciever.recId AND tracking.proId = product.proId AND tracking.senId = sender.senId";
$result = #mysqli_query($dbc, $query);
$num = mysqli_num_rows($result);
if ($num) { // tracking number was found
while ($row = mysqli_fetch_array($result,MYSQL_ASSOC)) {
echo '<div id="error">';
echo "<p>This tracking number <b>{$row['traNo']}</b> has already been assigned to <b>{$row['senderName']}</b></p>\n";
echo '</div>';
}
mysqli_free_result ($result); // Free up the resources.
}
1) I want to validate input box with the multiple IF conditions using && Logical expression but instead, it submits empty forms into the database.
Note: I purposely left out the shipment and status input box because the options cannot be empty by default.
2) Is there a way i can generate the tracking number automatically without typing it manually. I have tried GUID but am not getting it.
Thanks..
You have to set ids that you want to validate - there is no complain.
You can do this with:
$ids = array('senFirstName', 'senLastName', 'recFirstName', 'recLastName' /* ... and more */);
$valid = true;
foreach ( $ids as $id ) {
if ( empty($_POST[$id]) ) {
$valid = false;
}
}
if ( $valid === true ) {
// everything's ok
} else {
$errors[] = 'Please make sure you type in all the information.';
}
You need ||, not && if you want to test, if one is empty.
Otherwise you would proove, if all of them are empty.
(Sorry for bad english)
if(empty($_POST['senFirstName']) || empty($_POST['senLastName']) ...