PHP Prepared statement insert into database - php

Does anyone see anything that is wrong with this. It isn't posting to database at all. There is a basic form asking for name and address on the page. But after submitting the form it just goes to a blank page.
Here is my code. There is stuff above this that reaches out to an API to validate the address data and declares the variables. The dedup part of the code is working in case that matters.
if(empty($errorMessage))
{
// Dedupe the entry into the form
$dupesql = "SELECT * FROM formData WHERE (name = '$full_name' AND address = '$primary_number' AND city = '$city_name' AND state = '$state_abbreviation' AND zip = '$zipcode_full' )";
$duperaw = $mysqli->query($dupesql);
if($duperaw->num_rows > 0) {
$dupe .= "$full_name already exists on $primary_number \n";
}
else {
$sql = "INSERT INTO formData(name, address, city, state, zip, date) VALUES (?, ?, ?, ?, ?, ?)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("ssssss", $full_name, $primary_number, $city_name, $state_abbreviation, $zipcode_full, $date);
$stmt->execute();
header("location: index.php?success=1");
exit();
}
}
I have also tried using a query instead of a prepared statement but this just gives the success message and doesnt post to the DB
$sql = "INSERT INTO fromData (name, address, city, state, zip, date) VALUES (".
$full_name . ", " .
$primary_number . ", " .
$city_name . ", " .
$state_abbreviation . ", " .
$zipcode_full . ", " .
$date . ")";
$mysqli->query($sql);
Any help would be great!

Try this SQL
$sql = "INSERT INTO fromData (name, address, city, state, zip, date) VALUES ('$full_name', '$primary_number', '$city_name', '$state_abbreviation', '$zipcode_full', '$date')";
$mysqli->query($sql);
cHao was hinting towards it

Related

Inserting data into multiple different data tables

I was trying to insert data into multiple data tables. It's only working for single data tables, I'm just wondering how I would be able to insert data into two data tables. I've been struggling with this issue for the past few hours and can't seem to get to the bottom of it. If anyone has any advice please let me know. :)
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost","ivodatat","","");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Inputs for security
$fname = mysqli_real_escape_string($link, $_REQUEST['fname']);
$sname = mysqli_real_escape_string($link, $_REQUEST['sname']);
$address = mysqli_real_escape_string($link, $_REQUEST['address']);
$email = mysqli_real_escape_string($link, $_REQUEST['email']);
$phone = mysqli_real_escape_string($link, $_REQUEST['phone']);
$mac = mysqli_real_escape_string($link, $_REQUEST['mac']);
$installer = mysqli_real_escape_string($link, $_REQUEST['installer']);
$status = mysqli_real_escape_string($link, $_REQUEST['status']);
// Insert Query
$sql1 = "INSERT INTO leadlist (fname, sname, address, email, phone, mac, installer, status) VALUES ('$fname', '$sname', '$address', '$email', '$phone', '$mac', '$installer', '$status')";
$sql2 = "INSERT INTO $installer (fname, sname, address, email, phone, mac, installer, status) VALUES ('$fname', '$sname', '$address', '$email', '$phone', '$mac', '$installer', '$status')";
if (mysqli_multi_query($link, $sql1, $sql2)){
mysqli_close($conn);
header("Location: installercontrol.php");
exit;
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close The Connection
mysqli_close($link);
?>
To use mysqli_multi_query you need to append the queries to each other as it only takes one query argument. From the manual:
Executes one or multiple queries which are concatenated by a semicolon.
Try this instead:
mysqli_multi_query($link, $sql1 . ';' . $sql2)
You should probably also update your error message:
echo "ERROR: Could not able to execute $sql1;$sql2. " . mysqli_error($link);

MySQL not able to execute INSERT INTO [table]. Column count doesn't match value count at row 1

I'm trying to pull information from an HTML form and put this into a database using the following code:
$link = mysqli_connect("localhost", "user", "password", "MyDB");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "INSERT INTO interest (name, email, dob, address)
VALUES ('$fullname', '$email', '$dob' '$addr')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
}else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
mysqli_close($link);
It was working, and I've managed to get 2 test runs in, but now I'm getting the following error at the top of my submission page
ERROR: Could not able to execute INSERT INTO MyDB (name, email, dob,
address) VALUES ('test name', 'test#email.com', '2003-02-01'
'address'). Column count doesn't match value count at row 1
I have another variant of this which sends a PHP email, which is the file I'm using to base this database connection on.
There is also an autoincrement on ID column which is set as the primary key in the database if that makes a difference? SQL isn't my strong point unfortunately!
Given the syntax error you have in your query, being a missing comma in '$dob' '$addr'; you are open to an SQL injection and should be using a prepared statement.
Therefore, I am submitting this complementary answer for your own safety.
Here is an example of a prepared statement using the MySQLi API.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect('localhost', 'xxx', 'xxx', 'my_db');
if (!$link) {
die('Connect Error: ' . mysqli_connect_error());
}
// assuming these are the POST arrays taken from your HTML form if you're using one.
$fullname = $_POST['fullname'];
$email = $_POST['email'];
$dob = $_POST['dob'];
$addr = $_POST['addr'];
$sql = ("INSERT INTO interest (name, email, dob, address) VALUES (?, ?, ?, ?)");
$stmt = $link->prepare($sql) or die("Failed Execution");
$stmt->bind_param('ssss', $fullname, $email, $dob, $addr);
$stmt->execute();
echo $stmt->error;
echo "SUCCESS";
exit();
References:
How can I prevent SQL injection in PHP?
http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
http://php.net/pdo.prepared-statements
Foonotes:
If using the following failed because of the AI'd column:
$sql = ("INSERT INTO interest (name, email, dob, address) VALUES (?, ?, ?, ?)");
You may also try: (I used id as the AI'd column as an example)
$sql = ("INSERT INTO interest (id, name, email, dob, address) VALUES ('', ?, ?, ?, ?)");
This could be the case, as I have seen this type of SQL failure behaviour before.
You have missed comma here:
VALUES ('$fullname', '$email', '$dob' '$addr')
Thus (as it was clearly said in error text) column count doesn't mach values count.
It should be
VALUES ('$fullname', '$email', '$dob', '$addr')
You missed a comma
$sql = "INSERT INTO interest (name, email, dob, address)
VALUES ('$fullname', '$email', '$dob', '$addr')";
^here
You missed a comma:
VALUES ('$fullname', '$email', '$dob' '$addr')

Two tables for one php/MySQL form with a common field?

My form has an student ID , email and Name ...and checkboxes
I managed to store studentid and checkboxes in a table and created a new table to store all the other info related to the student id
Table 1
studentid ----- checkboxselections....
Table 2
studentid -----email ---- name
I have to insert into queries , one for studentid and checkboxes and one for (Table2)
$sql="INSERT INTO courses (studentid, ckb)
VALUES ('$studentid', '$cc')";
$sql2="INSERT INTO studentinfo (studentid, email, name)
VALUES ('$studentid', '$email', $fname)";
$sql2 fails to store data however $sql stores data just fine , how can I fix this ?
here's the full code
$studentid = mysqli_real_escape_string($dbcon, $_GET['studentid']); //echo $studentid;
$email = $dbcon->real_escape_string($_GET['email']);
$fname = $dbcon->real_escape_string($_GET['fname']);
$name = $_GET['ckb'];
if(isset($_GET['ckb'])) //checkboxes
{
foreach ($name as $courcess){
$cc=$cc. $courcess.',';
}
}
$sql="INSERT INTO courses (studentid, ckb)
VALUES ('$studentid', '$cc')";
$sql2="INSERT INTO studentinfo (studentid, email, name)
VALUES ('$studentid', '$email', $fname)";
if (!mysqli_query($dbcon,$sql)) {
die('Error: ' . mysqli_error($dbcon));
}
echo " Thank you for using IME Virtual Registeration ";
mysqli_close($dbcon);
?>
my form method is GET
i recommended you to use prepare statements and transaction instead mysqli query .
you forgot mysqli_query with second query:
$sql="INSERT INTO courses (studentid, ckb)
VALUES ('{$studentid}', '{$cc}')";
$sql2="INSERT INTO studentinfo (studentid, email, name)
VALUES ('{$studentid}', '{$email}', '{$fname}')";
if (!mysqli_query($dbcon,$sql)) {
die('Error: ' . mysqli_error($dbcon));
}
if (!mysqli_query($dbcon,$sql2)) {
die('Error: ' . mysqli_error($dbcon));
}
echo " Thank you for using IME Virtual Registeration ";
mysqli_close($dbcon);
?>
here is the example with prepare statement, and you don't need to use real_escape_string"
$stmt = $mysqli->prepare("INSERT INTO courses VALUES (?, ?)");
$stmt->bind_param('ds', $studentid, $cc);
$stmt->execute();
$stmt = $mysqli->prepare("INSERT INTO studentinfo VALUES (?, ?, ?)");
$stmt->bind_param('dss', $studentid, $email, $fname);
$stmt->execute();
Please Try this
if (!mysqli_query($dbcon,$sql))
{
die('Error: ' . mysqli_error($dbcon));
}
else
{
if (!mysqli_query($dbcon,$sql2))
{
die('Error: ' . mysqli_error($dbcon));
}
else
{
echo " Thank you for using IME Virtual Registeration ";
}
}
mysqli_close($dbcon);
if (!mysqli_query($dbcon,$sql))
{
die('Error: ' . mysqli_error($dbcon));
}
else
{
if (!mysqli_query($dbcon,$sql2)) {
die('Error: ' . mysqli_error($dbcon));
}
}
Hope it will help.....

Unable to locate sql error in php

Error message i've been recieving
Parse error: syntax error, unexpected 'INTO' (T_STRING) in D:\ServerFolders\Web\tokens\insert.php on line 17
Line 17
$sql= INSERT INTO users(Forename, Surname, Email, Username, Password, DOB)
Full code
<?php
//Connect to DB
$con=mysql_connect(localhost,root, "",APROJECT) or die (mysql_error());
// Check connection
if (mysql_connect_errno()) {
echo "Failed to connect to MySQL: " . mysql_connect_error();
}
// escape variables for security
$Forename = mysql_real_escape_string($con, $_POST['Forename']);
$Surname = mysql_real_escape_string($con, $_POST['Surname']);
$Email = mysql_real_escape_string($con, $_POST['Email']);
$Username = mysql_real_escape_string($con, $_POST['Username']);
$Password = mysql_real_escape_string($con, $_POST['Password']);
$DOB = mysql_real_escape_string($con, $_POST['DOB']);
//SQL query to add data to DB
$sql= INSERT INTO users(Forename, Surname, Email, Username, Password, DOB)
VALUES ($Forename, $Surname, $Email, $Username, $Password, $DOB);
if (!mysql_query($con,$sql)) {
die('Error: ' . mysql_error($con));
}
echo "1 record added";
mysql_close($con);
?>
First of all, mysql_* is not supported anymore and advised to use PDO or mysqli_* instead.
You should put query into quotes;
$sql= "INSERT INTO users(Forename, Surname, Email, Username, Password, DOB)
VALUES ($Forename, $Surname, $Email, $Username, $Password, $DOB)";
It may not work! Because you have to put values into single quotes. So better approach is using parameterized query.
For this time only I suggest using sprintf() function.
$sql= sprintf("INSERT INTO users(Forename, Surname, Email, Username, Password, DOB)
VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s')", $Forename, $Surname, $Email, $Username, $Password, $DOB);
Try adding quotes
$sql= "INSERT INTO users(Forename, Surname, Email, Username, Password, DOB)
VALUES ($Forename, $Surname, $Email, $Username, $Password, $DOB)";
$sql= INSERT INTO users(Forename, Surname, Email, Username, Password, DOB)
VALUES ($Forename, $Surname, $Email, $Username, $Password, $DOB);
The above line needs to be a string and in one line (variables in strings which start and end in " can be directly written into it):
$sql = "INSERT INTO users(Forename, Surname, Email, Username, Password, DOB) VALUES ($Forename, $Surname, $Email, $Username, $Password, $DOB)";
If you want it to be in multiple lines for better readability, you can use the nowdoc syntax with variables embeded in {}:
$sql <<<'EOD'
INSERT INTO users(Forename, Surname, Email, Username, Password, DOB)
VALUES ({$Forename}, {$Surname}, {$Email}, {$Username}, {$Password}, {$DOB})
EOD;
Last approach would be to concat the string with .:
$sql = "INSERT INTO users(Forename, Surname, Email, Username, Password, DOB) " .
"VALUES (" . $Forename . ", " . $Surname . ", " . $Email . ", " . $Username . ", " . $Password . ", " . $DOB . ")";
See this reference: http://php.net/manual/de/language.types.string.php
On a side note, don't forget to escape your variables in your mysql query with mysql_real_escape_string to prevent SQL Injection!
$sql = "INSERT INTO users(Forename, Surname, Email, Username, Password, DOB) " .
"VALUES (" . mysql_real_escape_string($Forename) . ", " . mysql_real_escape_string($Surname) . ", " . mysql_real_escape_string($Email) . ", " . mysql_real_escape_string($Username) . ", " . mysql_real_escape_string($Password) . ", " . mysql_real_escape_string($DOB) . ")";
It looks like you're just missing some quote around your sql query.
Something like
$sql= "INSERT INTO `users`(`Forename`, `Surname`, `Email`, `Username`, `Password`, `DOB`)
VALUES (".$Forename.", ".$Surname.", ".$Email.", ".$Username.", ".$Password.", ".$DOB.")";
Should fix your error.
It's also worth nothing that mysql_query is depreciated and can be pretty unsecure. It might be worth looking at PDO preapred statements if this is something that's going to be used in production. Check out http://php.net/manual/en/ref.pdo-mysql.php and Dream in Code PDO

php - Insert doesn't enter values to form

Hi guys i dont know what im doing wrong but my tables are correct, php error is on and it doesnt insert
I can get both first name and email echoed
<?php
if (isset($_POST['subs'])) {
function html_escape($html_escape) {
$html_escape = htmlspecialchars($html_escape, ENT_QUOTES | ENT_HTML5, 'UTF-8');
return $html_escape;
}
$name=html_escape($_POST['name']);
$email=html_escape($_POST['email']);
if (empty($name) || empty($email)) {echo"<div class='alert alert-danger'>Please enter both name and email address</div>";}
else {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo"<div class='alert alert-danger'>Invalid email address, please enter a correct email address!</div>";
}
else {
echo "INSERT into subs (first_name, email) VALUES ('$name','$email')";
$insert=mysql_query("INSERT into subs (first_name, email) VALUES ('$name','$email')");
if ($insert) {echo"<div class='alert alert-success'>Thank you for subscribing with us</div>";}
}
}}
?>
first of all, are you connected to mysql before running your query?
$conn=mysql_connect('localhost', 'your_db_username', 'your_db_password');
if(!$conn){
die('Cannot connect to mysql');
}
mysql_select_db('your_db_name');
Then, when you're sure you're connected to the db and your query is still not working, add or die(mysql_error()) after your query like this, this will help you know what's going wrong with your insert:
$insert=mysql_query("INSERT into subs (first_name, email)
VALUES ('$name','$email')")
or die(mysql_error());
As a general point, using the PDO class is preferred, and may give you more information about what the problem is.
e.g.
$pdo = new \PDO('mysql:host=localhost;dbname=<database_name>', '<database_username>', '<database_password>');
$sql = "INSERT into subs (first_name, email) VALUES (:name,:email)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$result = $stmt->execute();
This gives a lot of benefits. Take my word for it, or give "benefits of PDO" a quick Google.
$query = "INSERT INTO subs (first_name, email) VALUES ('" . $name . "','" . $email . "') ";
$insert = mysql_query($query);

Categories