I keep getting this error in my php. It worked fine when I hard set the values but doesn't seem to work with variables.
Error: INSERT INTO ContactUS (name, email, subscribed) VALUES (TEST, my#email.com, 1)
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Anis, my#email.com, 1)' at line 1
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO ContactUS (name, email, subscribed) VALUES ($name, $email, $subscribed)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Values should be quoted:
$sql = "INSERT INTO ContactUS (name, email, subscribed) VALUES ('$name', '$email', '$subscribed')";
Perhaps it's better to use prepared statements as this is done automatically for you and you won't be vulnerable to SQL injections.
Use quotes around variables, as PHP will replace its value, leaving an invalid query:
$sql = "INSERT INTO ContactUS (name, email, subscribed) VALUES ('$name', '$email', '$subscribed')";
but please use prepared statements, otherwise you'll be victim of SQL injection
Related
I am trying to put data in MySQL with PHP but is not showing any error but values are not entered in database too.
$query = "INSERT INTO orders (username, servicename, link, quantity, cost, date)
VALUES('$username', '$service_name', '$link', '$quanitiy', '$cost', '$date')";
$insert=mysqli_query($db, $query);
I think your query should look something like that:
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// create the query
$query = "INSERT INTO orders (username, servicename, link, quantity, cost, date)
VALUES('$username', '$service_name', '$link', '$quanitiy','$cost', '$date')";
// preform the query
$insert=mysqli_query($conn, $query);
// you need to check if the insert succeeded before closing the connection
// close connection to DB
mysqli_close($conn);
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')
Im having a problem with my PHP code, it says the error is "Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1"
It connects to the database ok as it echos "Database Connection Successful" but it dosnt insert the data into the database. This worked fine before, but now all of a sudden its stopped working. Can anyone help?
<?php
$username = "student";
$password = "student";
$hostname = "localhost";
$db = "details";
$link = new mysqli($hostname, $username, $password, $db);
if ($link->connect_errno)
printf("Connect failed: %s\n", $link->connect_error);
else
echo "Database Connection Successful \n";
echo nl2br("\n");
$Urgency = "Urgency";
if(isset($_POST['submit'])){
$TypeOfProblem = $_POST['problemtype'];
$ProblemDescription = $_POST['problem'];
$RoomNo = $_POST['roomno'];
$Problem = $_POST['reporter'];
$Urgency = $_POST['Urgency'];
$Date = $_POST['date'];
//Insert into Database
$sql = "INSERT INTO `details`.`problem` (`Type Of Problem`, `Problem Description`, `RoomNo`, `Urgency`, `UserIDProblem`,`Date` ) VALUES ('$TypeOfProblem', '$ProblemDescription', '$RoomNo', '$Urgency', '$Problem', $Date)";
if (!mysqli_query($link, $sql))
{
die('Error: ' . mysqli_error($link));
}
echo "\n Thank you. Your Helpdesk Call has been submitted.";
mysqli_close($link);
}//////// end isset submit if ////////
?>
Thanks
Try using this, the problem is the single quote ` should be '
$sql = "INSERT INTO 'details'.'problem' ('Type Of Problem', 'Problem Description', 'RoomNo', 'Urgency', 'UserIDProblem','Date' ) VALUES ('$TypeOfProblem', '$ProblemDescription', '$RoomNo', '$Urgency', '$Problem', '$Date')"
Or try to set an echo $sql and test the query directly on de dbms
The date '$Problem', $Date)"; needs single-quotes '$Problem', '$Date')";
First, it is a good idea to leave out the database name:
$sql = "INSERT INTO `problem` (`Type Of Problem`, `Problem Description`, `RoomNo`, `Urgency`, `UserIDProblem`, `Date`) VALUES ('$TypeOfProblem', '$ProblemDescription', '$RoomNo', '$Urgency', '$Problem', $Date)";
Are you sure, that your column names have spaces in it? I mean this would work, but this is not a good idea, I think.
I cannot find another problem in your query, maybe you should quote the date:
$sql = "INSERT INTO `problem` (`Type Of Problem`, `Problem Description`, `RoomNo`, `Urgency`, `UserIDProblem`, `Date`) VALUES ('$TypeOfProblem', '$ProblemDescription', '$RoomNo', '$Urgency', '$Problem', '$Date')";
Otherwise, please provide us with the full query:
die("INSERT INTO `problem` (`Type Of Problem`, `Problem Description`, `RoomNo`, `Urgency`, `UserIDProblem`, `Date`) VALUES ('$TypeOfProblem', '$ProblemDescription', '$RoomNo', '$Urgency', '$Problem', $Date)");
And you SHOULD notice, that your code is exploitable with SQL-Injections! Use mysqli_real_escape_string.
For debugging this, output the actual SQL text that is being submitted to the database, using echo or vardump e.g.
$sql = "INSERT INTO ...";
echo "SQL=" . $sql ;
That will show you the actual statement that's going to be submitted to the database, and you can usually debug the problem from there.
If date isn't a numeric, if it represents a DATE datatype or a string, the value needs to be enclosed in single quotes. Otherwise, it's likely going to be interpreted in a numeric context.
Note that this code appears to be vulnerable to SQL Injection, because it includes potentially unsafe values in the SQL text. Consider what happens when a value contains "special" characters, like a single quote, or comma.
Potentially unsafe values must be properly escaped. With mysqli, you can use the mysqli_real_escape_string function.
A better pattern is to use a prepared statement with bind placeholders.
As an example of what that would look like (before it's cluttered up with code to checks for errors from the return of the mysqli_ function calls)
$sql = "INSERT INTO `details`.`problem`
(`Type Of Problem`,`Problem Description`,`RoomNo`,`Urgency`,`UserIDProblem`,`Date`)
VALUES (?,?,?,?,?,?)";
$sth = mysqli_prepare($link,$sql);
if (!$sth) {
echo "error:" . mysqli_error($link);
)
mysqli_stmt_bind_param($sth,"ssssss"
,$TypeOfProblem,$ProblemDescription,$RoomNo,$Urgency,$Problem,$Date);
mysqli_stmt_execute($sth);
hello i am a java developer but new to php here i am trying to insert data in to the database using prepared statements as mentioned in here http://www.php.net/manual/en/pdo.prepared-statements.php but i am getting an error may i know what sort of error is this and any help to resolve this.
Error: Fatal error: Call to undefined method mysqli_stmt::bindParam() in G:****\xampp\htdocs****\registrationControl.php on line 17
<?php
$con = new mysqli("127.0.0.1", "root", "", "ksbka");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$firstname = mysqli_real_escape_string($con, $_POST['username_first']);
$username_email = mysqli_real_escape_string($con, $_POST['username_email']);
$username_tele = mysqli_real_escape_string($con, $_POST['username_tele']);
echo $firstname."#####".$username_email;
$query="INSERT INTO instructorregistration (Id, Name, email, telephone) VALUES (?, ?, ?, ?)";
$pst = $con->prepare($query);
$pst->bindParam(1, "");
$pst->bindParam(2, $firstname);
$pst->bindParam(3, $username_email);
$pst->bindParam(4, $username_tele);
$pst->execute();
if (!mysqli_query($con,$pst)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
I think if you want to use bindParam() method, the value should be an instance of PDOStatement .
The doc you see as bellow:
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$dbh is a PDO instance, I think, NOT mysqli instance. Because there is no mysqli::bindParam().
To solve this problem, you can:
use PDO class instead of Mysqli
create the query as the simplest way:
$query="INSERT INTO instructorregistration (Id, Name, email, telephone) VALUES (NULL, $firstname, $username_email, $username_tele)";
you have to use the mysqli methods, when you use mysqli
$stmt = $con->prepare($query);
$stmt->bind_param(1, "");
...
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
/* explicit close recommended */
$stmt->close();
/* Non-prepared statement */
$res = $mysqli->query("SELECT id FROM test");
var_dump($res->fetch_all());
edit: added some code from the official documentation
I am new to using MySQLi. I try to use MySQLi in order to insert data in my database. But does not work. Where may be the error?
echo 'connected';
$con = mysqli_connect("localhost",$username,$password,$database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// mysqli_select_db($con,"kraus");
$firstname = $_POST['uname'];
$lastname = $_POST['address'];
$age = $_POST['pass'];
$sql = "INSERT INTO registration('uname', 'address', 'password') VALUES ('$firstname', '$lastname', '$age')";
mysqli_query($con,$sql);
echo "1 record added";
mysqli_close($con);
Why is line this commented out? You are selecting the database in mysqli_connect("localhost","root","root","kraus") but it makes no sense why that is there:
// mysqli_select_db($con,"kraus");
Should you not have that commented like this?
mysqli_select_db($con,"kraus");
Also there is no space here between registration and the fields in (…) as well as the quotes around your fields:
$sql = "INSERT INTO registration('uname', 'address', 'password') VALUES ('$firstname', '$lastname', '$age')";
That should be like the following with a space added between the table name & the fields. And since there should just be no quotes around your field names so the final query should be this:
$sql = "INSERT INTO registration (uname, address, password) VALUES ('$firstname', '$lastname', '$age')";
Or perhaps have back ticks like this:
$sql = "INSERT INTO registration (`uname`, `address`, `password`) VALUES ('$firstname', '$lastname', '$age')";
Also, you should really refactor & cleanup your whole codebase like this:
// Set the connection or die returning an error.
$con = mysqli_connect("localhost","root","root","kraus") or die(mysqli_connect_errno());
echo 'connected';
// Select the database.
// mysqli_select_db($con, "kraus");
$post_array = array('uname','address','pass');
foreach ($post_array as $post_key => $post_value) {
$$post_key = isset($_POST[$post_value]) && !empty($_POST[$post_value]) ? $_POST[$post_value] : null;
}
// Set the query.
$sql = "INSERT INTO registration (uname, address, password) VALUES (?, ?, ?)";
// Bind the params.
mysqli_stmt_bind_param($sql, 'sss', $uname, $address, $pass);
// Run the query.
$result = mysqli_query($con, $sql) or die(mysqli_connect_errno());
// Free the result set.
mysqli_free_result($result);
// Close the connection.
mysqli_close($con);
echo "1 record added";
Note how I am using mysqli_stmt_bind_param and also setting an array of $_POST values & rolling throughout them. Doing those two basic things at least enforce some basic validation on your input data before it gets to the database.
You have quotes around the column names in your query. Maybe you meant to use backticks instead:
(`uname1`, `address`,...)
You are also vulnerable to sql injection. Look into mysqli prepared statements.