PHP MySQLI prepared insert to handle quotes and double quotes - php

I have a prepared mysqli insert statement but when I try to insert data with quotes or double quotes I get this error: Prepare failed: (1064) 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 'Ask me in six months.' We don’t have six months to wait," he said. "I have a p' at line 1
when I use mysqli_real_escape_string around my text that I am trying to insert, it inserts into my database as empty data.
Is there a better way to handle single or double quotes? Or is there something wrong with my code?
$connection = new mysqli("localhost", "username", "password", "database");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if (!($stmt = $connection->prepare("INSERT INTO `in-the-press` (title, `date`, preview, description, image, detailImage, showDetailImage) VALUES ('" . $title . "', '" . $date . "', '" . $preview . "', '" . $description . "','" . $image . "', '" . $detailImage . "', " . $showDetailedImage . ")"))) {
echo "Prepare failed: (" . $connection->errno . ") " . $connection->error;
}else{
$stmt->execute();
echo 'Press has been added <br>';
}
I have tried with mysqli_real_escape_string($title), mysqli_real_escape_string($preview) & mysqli_real_escape_string($description), but like I said it would insert it to the database as empty strings :(

As Micheal said in his comment
Since you're using mysqli with prepare() & execute() you'll be better off harnessing bind_param()
$stmt = $mysqli->prepare("INSERT INTO `in-the-press` (title, `date`, preview, description, image, detailImage, showDetailImage) VALUES (?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param('sssssss', $title, $date, $preview, $description, $image, $detailImage, $showDetailedImage);
/* execute prepared statement */
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
/* close statement and connection */
$stmt->close();
The above is just an example, I don't know what your database schema/structure looks like
Breakdown:
s means string.
d means double.
You can read more on the types (i, s, d, b) in the bind_param link above.

Related

how to allow users to write queries without being executed

well im making a blog that is almost done.. i wana allow users to post questions where they can post a query as there comment without allowing this query to be actually executed .. i tried making some security .. i used mysql_real_escape_string, htmlentities(), htmlspecialchars(), strip_tags() and addslashes()
.. however when i write something like
SELECT * FROM TABLE an error occurs disallowing me from posting the comment
im inserting the comments using this query
$sql = 'INSERT INTO comments (topic_id,commenters_id,comment,media,mediaType) VALUES ("' . $topic_id . '", "' . $commenter_id . '", "' . $comment . '", "' . $media . '", "' . $mediaType . '")';
You should be able to insert a comment containing SQL without it being executed. The reason you are having trouble is that you are concatenating user input into your SQL string. If you use prepared statements and bind the user input as parameters instead, you won't have this problem.Here is an example of how to do that (adapted from the PHP quickstart guide on mysqli prepared statements).
$sql = 'INSERT INTO comments
(topic_id,commenters_id,comment,media,mediaType) VALUES (?, ?, ?, ?, ?)';
// prepare
if (!($stmt = $mysqli->prepare($sql))) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
// bind parameters (I'm not sure if I picked the correct types here)
if (!$stmt->bind_param("iisss", $topic_id, $commenter_id, $comment, $media, $mediaType)) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
// execute
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}

Error: You have an error in your SQL syntax; near ')' at line 1

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);

how to insert in to database using prepared statments in php

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

SQL Syntax error at line one - query is the same as a working one though?

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 'Order, Name, URL, UserName, Password, SiteName, Notes) VALUES ('','','','','',' at line 1
The sql is exactly the same as a working insert query; apart from the field/table names.
Here is the code:
<?php
$con = mysqli_connect('HOST', 'USER', 'PASS','DATABASE');
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
$sql="INSERT INTO RemoteLinks (Order, Name, URL, UserName, Password, SiteName, Notes) VALUES('$_POST[Order]','$_POST[Name]','$_POST[URL]','$_POST[UserName]','$_POST[Password]','$_POST[SiteName]','$_POST[Notes]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
header('Location: ' . $_SERVER['HTTP_REFERER']);
mysqli_close($con);
?>
Not too sure why this isnt working as its working in a similar query. Thanks for any help, its appreciated.
ORDER is a reserved word used in order by clause - surround with backticks "`"
Update
Here is a list of Reserved Words in MySQL.
You'd generally want to avoid using backticks to escape those reserved words, because backticks decrease portability of the code. So, you might need to learn those and use other words for column names, tables, databases, etc.
IMPORTANT
You should definitely use mysqli_prepare() and mysqli_stmt_bind_param()!
You need to use back ticks ` for reserved colum names (Order) and Prepare SQL statement for execution and bind params to prevent sql injection:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "my_database");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$insertQuery = 'INSERT INTO RemoteLinks (`Order`, Name, URL, UserName, Password, SiteName, Notes) '.
'VALUES (?, ?, ?, ?, ?, ?, ?)';
if ($stmt = $mysqli->prepare($insertQuery))
{
$stmt->bind_param(
"sssssss",
$_POST['Order'],
$_POST['Name'],
$_POST['URL'],
$_POST['UserName'],
$_POST['Password'],
$_POST['SiteName'],
$_POST['Notes']);
$stmt->execute();
$stmt->close();
}
$mysqli->close();
?>

Error when inserting into SQL table with PHP

This is my code:
function function() {
$isbn = $_REQUEST["isbn"];
$price = $_REQUEST["price"];
$cond = $_REQUEST["cond"];
$con = mysql_connect("localhost","my_usernam", "password");
if (!$con) die('Could not connect:' . mysql_error());
mysql_select_db("my_database",$con);
$sql="INSERT INTO 'Books' (isbn, price, condition)
VALUES ('$isbn','$price','$cond')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
mysql_close($con);
return "It works";
But when run it results in:
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 ''Books' (isbn, price....
Anyone know why this is happening?
You should use backticks instead of single quotes for table and field names:
$sql="INSERT INTO `Books` (`isbn`, `price`, `condition`)
VALUES ('$isbn','$price','$cond')";
will work.
ps. to prevent all kinds of nasty security holes, escape the input fields with:
$isbn = mysql_real_escape_string($_REQUEST["isbn"]);
// etc etc for all fields
Wrap table names in backticks, not quotes, and make sure to escape your input for security:
$sql="INSERT INTO `Books` (`isbn`, `price`, `condition`)
VALUES ('" . mysql_real_escape_string($isbn) . "',
'" . mysql_real_escape_string($price) . "',
'" . mysql_real_escape_string($cond) . "')";

Categories