I am importing employee data from .csv file as bulk operation. There is many fields like First name, Last Name, Email, Contact No, Address etc.
Email field in database is Index/Unique. So i have put validation over it.
But my question is when certain rows contains special characters like matinées#fauts.net or débutante#peured.info [focus é].
This will stops php script execution unexpectedly without error log. I have also go through Apache Error Log/PHP Error Log but there is no errors. Please help me to prevent this.
I have also tried to set character encoding scheme to UTF-8 or Westorn-ISO-800 etc, but this will not work.
Code snippet:
` $firstname = $sd[0];
if ($firstname != '' || !empty($firstname)) {
$lastname = $sd[1];
$email = $sd[2];
if ($sd[3] != '' && $sd[3] != NULL) {
$password = md5( $sd[3]);
}
$contactno = $sd[4];
$internalextension = $sd[5];
$companyid = $this->session->userdata('companyid');
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
return array("status" => FALSE, "message" => "Error while Importing Employee. Please Check Your .csv "
. "file; <br/> Your file contains Invalid Email Id at Line number" . ($count + 1) . ". Email: $email");
} else {
if ($count != 500) {
$query = $query . "(NULL, '" . $firstname . "', '" . $lastname . "', '" . $email . "', "
. "'" . $password . "', '" . $salt . "', 1, '" . $contactno . "',"
. "'" . $internalextension . "', 4, " . $companyid . ", '" . my_datenow() . "'),";
} else {
$query = $query . "(NULL, '" . $firstname . "', '" . $lastname . "', '" . $email . "', "
. "'" . $password . "', '" . $salt . "', 1, '" . $contactno . "',"
. "'" . $internalextension . "', 4, " . $companyid . ", '" . my_datenow() . "');";
echo $query;
}
}
} else {
return array("status" => FALSE, "message" => "Error while Importing Employee. Please Check Your .csv file; First Name should not be blank.");
}`
You can use htmlspecialchars() before assigning value to variable for example
$firstname = htmlspecialchars($sd[0]);
htmlspecialchars — Convert special characters to HTML entities
reference : http://php.net/manual/en/function.htmlspecialchars.php
Related
I have a PHP and I want to do 2 inserts and 1 delete, but I can only make an insert. If the array containt the last parameter == "historico" should delete from instant_table all register with same serial_num and inserte the array intro the instant_table and insert in historical_table("SensorData"). Ifnot (the array don't hace the parameter "historico"), should de delete from instant_table all register with same serial_num and only inserte the array intro the instant_table.
My code:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$serial_numb = test_input($_POST["serial_numb"]);
$DHTtempC = test_input($_POST["DHTtempC"]);
$DHThumid = test_input($_POST["DHThumid"]);
$CCS811_CO2 = test_input($_POST["CCS811_CO2"]);
$CCS811_tVOC = test_input($_POST["CCS811_tVOC"]);
$PM25 = test_input($_POST["PM25"]);
$PM10 = test_input($_POST["PM10"]);
$reading_date = date("Y-m-d");
$update_status = test_input($_POST["update_status"]);
$tipo_tabla = test_input($_POST["tipo_tabla"]);
// Create connection
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
if ($tipo_tabla == "historico"){
$sql = "INSERT INTO SensorData (serial_numb, DHTtempC, DHThumid, CCS811_CO2, CCS811_tVOC, PM25, PM10, reading_date, update_status)
VALUES ('" . $serial_numb . "', '" . $DHTtempC . "', '" . $DHThumid . "', '" . $CCS811_CO2 . "', '" . $CCS811_tVOC . "', '" . $PM25 . "', '" . $PM10 . "', '" . $reading_date . "', '" . $update_status . "')";
}
$sql = "DELETE FROM instant_data WHERE (serial_numb = '" . $serial_numb . "')";
$sql = "INSERT INTO instant_data (serial_numb, DHTtempC, DHThumid, CCS811_CO2, CCS811_tVOC, PM25, PM10, reading_date, update_status)
VALUES ('" . $serial_numb . "', '" . $DHTtempC . "', '" . $DHThumid . "', '" . $CCS811_CO2 . "', '" . $CCS811_tVOC . "', '" . $PM25 . "', '" . $PM10 . "', '" . $reading_date . "', '" . $update_status . "')";
if ($mysqli->query($sql) === TRUE) {
echo "New record created successfully";
}
else {
echo "Error: " . $sql . "<br>" . $mysqli->error;
}
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$mysqli->close();
}
else {
echo "No data posted with HTTP POST.";
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
Tu sum up, If the array contains the parameter, INSERTE(TABLE1) + DELETE with same serial_num(TABLE2) + INSERTE(TABLE2). If not DELETE with same serial_num(TABLE2) + INSERTE(TABLE2).
EDIT: Now this code only make the second INSERT
It seems like you are overwriting the content of $sql without executing the queries in between. You have to either:
execute each query before redefining $sql
use $sql .= (instead of $sql =) to concatenate the next query. If you do this, you have to terminate your sql query with an ; before concatenating the next query.
Are you using this code just for an small personal project or are you going to publish this in any way? In case of the later one:
please read into PHP SQL best practices. With your current approach you are vulnerable to SQL injections and your code is kinda difficult to read.
i have an html form , when user submits the data, the data goes into database, this was working fine until i added one more thing, i added mail function to send the mail after the data is submitted. my code is like below:
<?php
error_reporting(0);
session_start();
require('db_config.php');
if (isset($_POST['submit'])) {
$name = $_FILES['Photo']['name'];
list($txt, $ext) = explode(".", $name);
$image_name = time() . "." . $ext;
$tmp = $_FILES['Photo']['tmp_name'];
$shame = $_FILES['paymentphoto']['name'];
list($txts, $exts) = explode(".", $shame);
$receipt_name = time() . "." . $ext;
$tmps = $_FILES['paymentphoto']['tmp_name'];
if (move_uploaded_file($tmp, 'uploads/' . $image_name) && move_uploaded_file($tmps, 'receipt/' . $receipt_name)) {
$sql = "INSERT INTO members (firstname, lastname, image, company, designation, addressone, addresstwo, aadhar, city, state, pin, pan, rnameone, rnametwo, mobile, alternate, email, experience, businessdate, companyregistration, gstin, servicesoffered, fee, mode, receipt) VALUES ('" . $_POST['first_name'] . "','" . $_POST['last_name'] . "' , '" . $image_name . "','" . $_POST['company'] . "', '" . $_POST['designation'] . "','" . $_POST['address'] . "', '" . $_POST['address2'] . "', '" . $_POST['aadhaar'] . "', '" . $_POST['city'] . "', '" . $_POST['state'] . "', '" . $_POST['pin'] . "', '" . $_POST['pan'] . "', '" . $_POST['recommended'] . "', '" . $_POST['recommended2'] . "','" . $_POST['mobile'] . "', '" . $_POST['alternate'] . "', '" . $_POST['email'] . "', '" . $_POST['experience'] . "', '" . $_POST['date'] . "', '" . $_POST['registration'] . "', '" . $_POST['gst'] . "', '" . $_POST['services'] . "', '" . $_POST['fee'] . "', '" . $_POST['payment'] . "', '" . $receipt_name . "' )";
$mysqli->query($sql);
$to = "teiamembers#gmail.com"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$headers = "From:" . $from . "\nMIME-Version: 1.0\nContent-Type: text/html; charset=utf-8\n";
$headers2 = "From:" . $to;
$subject = "TEIA Membership Registration Request";
$subject2 = "TEIA Membership Request";
$message = $first_name . " has requested for TEIA Registration. Full Name:" . " " . $first_name . " " . $last_name . "<br>" . "Email:" . $from . "<br>" . "Mobile:" . " " . $_POST['mobile'] . "<br>" . "Company Name:" . " " . $_POST['company'] . "<br>" . "Designation" . " " . $_POST['designation'] . "<br>" . "Residence Address:" . " " . $_POST['address'] . "<br>" . "Office Address:" . " " . $_POST['address2'] . "<br>" . "Aadhaar:" . " " . $_POST['aadhaar'] . "<br>" . "City:" . " " . $_POST['city'] . "<br>" . "State:" . " " . $_POST['state'] . "<br>" . "Pin:" . " " . $_POST['pin'] . "<br>" . "Pan:" . " " . $_POST['pan'] . "<br>" . "Reference:" . " " . $_POST['recommended'] . "<br>" . "Alternate Number:" . " " . $_POST['alternate'] . "<br>" . "Experience:" . " " . $_POST['experience'] . "<br>" . "Aadhaar:" . " " . $_POST['aadhaar'] . "<br>" . "Date of Business Setup:" . " " . $_POST['date'] . "<br>" . "Company Registration Number:" . " " . $_POST['registration'] . "<br>" . "GSTIN:" . " " . $_POST['gst'] . "<br>" . "Services Offered:" . " " . $_POST['services'] . "<br>" . "Fee Paid:" . " " . $_POST['fee'] . "<br>" . "Payment Mode:" . " " . $_POST['payment'] . "<br>";
$message2 = "Your request for TEIA Membership Received. We will contact you Shortly. ";
mail($to, $subject, $message, $headers);
mail($from, $subject2, $message2, $headers2); // sends a copy of the message to the sender
if ($mysqli) {
$msg = "Your Request For Membership Registration Sent Successfully";
}
}
}
?>
now the problem is when the user submits the form, the mail is working properly, but the values are not going to database, can anyone please tell me what could be wrong here, thanks in advance
TAKE CARE OF SQL INJECTION first.
Some amount of checking is necessary all the time. At the very least...this one.
if($mysqli->query($sql)) { fine } else { error }
And in the "error" part of above, if you would have included error number and actual message, you yourself might have found the answer.
Main doubt I have is...you have some unique column and the insert did not happen as it did appear in database earlier.
Also, better to use an id int unique auto_increment for several purposes.
Secondly, you should have created $mailstatus and have checked the same and not mysqli for this message.
if ($mailstatus) {
$msg = "Your Request For Membership Registration Sent Successfully";
}
My script grabs a textfile full with tab delimited data from my inbox and is supposed to import it into my database. The problem is that the data can contain special characters such , or & or ;, which get picked up as delimiters and break my import.
I am unable to use LOAD DATA or LOAD DATA LOCAL due to my webhost's server configuration, hence the below method is the only way I have so far.
How can I hardcode the script below to delimited the data only by tabs and ignore everything else?
// read content of CSV file
while (($row = fgetcsv($getdata)) !== FALSE) {
// skip the top 3 rows (header information) - Line 0, Line 1 and Line 2
if ($line <= 2) {
$line++;
continue;
} else {
$sql = "INSERT INTO `$dbtable`
(`OPERA_CONF`, `CRS`, `HOLIDEX`, `ARRIVAL`, `DEPARTURE`, `NIGHTS`, `ADULTS`, `KIDS`, `TITLE`, `FIRST`, `LAST`, `NATIONALITY`, `ROOM`, `ROOM_TYPE`, `MBR`, `MBR_NO`, `MBR_LVL`, `RATE`, `CURR`, `RATECODE`, `MARKET`, `COMPANY`, `AGENT`, `EMAIL`, `PHONE`, `TIMESTAMP`)
VALUES (
'" . mysqli_real_escape_string($mysqli, $row[0]) . "',
'" . mysqli_real_escape_string($mysqli, $row[1]) . "',
'" . mysqli_real_escape_string($mysqli, $row[2]) . "',
'" . mysqli_real_escape_string($mysqli, $row[3]) . "',
'" . mysqli_real_escape_string($mysqli, $row[4]) . "',
'" . mysqli_real_escape_string($mysqli, $row[5]) . "',
'" . mysqli_real_escape_string($mysqli, $row[6]) . "',
'" . mysqli_real_escape_string($mysqli, $row[7]) . "',
'" . mysqli_real_escape_string($mysqli, $row[8]) . "',
'" . mysqli_real_escape_string($mysqli, $row[9]) . "',
'" . mysqli_real_escape_string($mysqli, $row[10]) . "',
'" . mysqli_real_escape_string($mysqli, $row[11]) . "',
'" . mysqli_real_escape_string($mysqli, $row[12]) . "',
'" . mysqli_real_escape_string($mysqli, $row[13]) . "',
'" . mysqli_real_escape_string($mysqli, $row[14]) . "',
'" . mysqli_real_escape_string($mysqli, $row[15]) . "',
'" . mysqli_real_escape_string($mysqli, $row[16]) . "',
'" . mysqli_real_escape_string($mysqli, $row[17]) . "',
'" . mysqli_real_escape_string($mysqli, $row[18]) . "',
'" . mysqli_real_escape_string($mysqli, $row[19]) . "',
'" . mysqli_real_escape_string($mysqli, $row[20]) . "',
'" . mysqli_real_escape_string($mysqli, $row[21]) . "',
'" . mysqli_real_escape_string($mysqli, $row[22]) . "',
'" . mysqli_real_escape_string($mysqli, $row[23]) . "',
'" . mysqli_real_escape_string($mysqli, $row[24]) . "',
'" . mysqli_real_escape_string($mysqli, $local_time) . "'
)";
if(!$mysqli->query($sql)) {
echo "\n Error while importing row $line.<br>";
$errcount++;
}
$line++;
}
thanks
Set tab as the wanted delimiter like this:
while (($row = fgetcsv($getdata,0,"\t")) !== FALSE) {
The zero indicates no limit with respect to the length of longest line. Documentation: http://php.net/manual/en/function.fgetcsv.php
am doing an online admission system as my project.
Am having issues with the on duplicate query..
this is my php script.
$save="INSERT INTO student_reg (Reg_number,username,password,surname,fname,mname,sex,address,city,state,country,
Email,Prog_code,dept_code)
VALUES('".$_SESSION['random']."','".$_SESSION['uname']."','".$_SESSION['password']."','".$_SESSION['sname']."',
'".$_SESSION['fname']."','".$_SESSION['mname']."','".$_SESSION['sex']."',
'".$_SESSION['address']."','".$_SESSION['city']."','".$_SESSION['state']."','".$_SESSION['country']."',
'".$_SESSION['email']."','".$_SESSION['progcode']."','".$_SESSION['deptcode']."')
ON DUPLICATE KEY UPDATE
username= '" . $_POST['username'] . "',password = '" . $_POST['password'] . "',
surname='" . $_POST['surname'] . "',fname = '" . $_POST['fname'] . "',mname = '" . $_POST['mname'] . "',
sex = '" . $_POST['sex'] . "',address= '" . $_POST['address'] . "',
city= '" . $_POST['city'] . "',state= '" . $_POST['state'] . "',country = '" . $_POST['country'] . "',
Email = '" . $_POST['email'] . "',Prog_code = '" . $_SESSION['progcode'] . "',dept_code = '".$_SESSION['deptcode']."'
";
$result=mysql_query($save)or die(mysql_error());
if($save==TRUE){
echo"save";
}
else{
echo "not saved";
}
The s_session(random) is used to automatically assign
Reg_numbers to students after their form has been saved and the value is stored in a unique field in d database called reg_number.
When I execute the query,the insert option works perfectly
but the update doesn't work rather,it kips inserting a new record over and over again into the database once the submit button is click..
I want to update all column values, as you can see from the code. But only the first three columns get updated and last two values get updated.
Home_number
Office_number
Fax_number
does not get updated.
Please help solve the following problem.
if (isset($_POST["submit"]) && $_POST["submit"] !="")
{
$usersCount = count($_POST["F_name"]);
echo "$userCount";
for ($i = 0; $i < $usersCount; $i++)
{
mysql_query("UPDATE contactss set F_name='" .
$_POST["F_name"][$i] . "', L_name='" . $_POST["L_name"][$i] . "', mob_number='" . $_POST["mob_number"][$i] . "', Home_number='" . $_POST["Home_number"][$i] . "', Office_number='" . $_POST["Office_number"][$i] . "', Fax_number='" . $_POST["Fax_number"][$i] . "', email='" . $_POST["email"][$i] . "', Address='" . $_POST["Address"][$i] . "' WHERE C_id='" . $_POST["C_id"][$i] . "'");
}
header("Location:list_user.php");
}