I have a query as follows:
$this->db->query('INSERT INTO board_member (name, position, address) VALUES (?, ?, ?)', array($name, $position, $address));
The name may contain double quotes, for a nickname, such as:
James "Jimbo" Smith
However, if I insert that value, It gets cut off before the first double quote, leaving me with just James. What do I need to do to make this work?
EDIT: I've tried $this->db->escape_string(), which left me with this:
'James \
Always enclose HTML tag attributes in quotes.
Always use htmlspechialchars() when using a PHP variable in HTML tag attribute.
Use mysql_real_escape_string
mysql_real_escape_string — Escapes special characters in a string for use in an SQL statement
Example
`$name = mysql_real_escape_string($_POST['name']);
$position = file_get_contents($_FILE['file']['tmp_name']);
$address=mysql_real_escape_string($_POST['address]);
$this->db->query('INSERT INTO board_member (name, position, address) VALUES (?, ?, ?)', array($name, $position, $address));`
Reference
Related
I've been searching for an answer for a while now, but can't seem to find anything.
I'm looking for a way to use mysqli_bind_param to insert a row into a table, where the param (?) is part of a larger string.
This is my code:
$query = "INSERT INTO CDBusers_activity (order_ID, activity_text_desc) VALUES (?, 'Price edited from ? to ?')";
$stmt = mysqli_prepare($DB_conn, $query);
mysqli_bind_param($stmt, "sss", $orderID, $product_editPrice_was, $product_editPrice_now);
mysqli_stmt_execute($stmt);
I'm looking for a way to add the $product_editPrice_was and $product_editPrice_now into the row.
I could create a string:
$text = "Price edited from $product_editPrice_was to $product_editPrice_now"
and then bind that, but I am interested if there is a simpler way? For example:
$query = "INSERT INTO CDBusers_activity (order_ID, activity_text_desc) VALUES (?, 'Price edited from ' ? ' to ' ?)";
Asking your primary question - no, you can't replace part of inserted value with a placeholder.
The solution is:
$query = "INSERT INTO CDBusers_activity (order_ID, activity_text_desc) VALUES (?, ?)";
$stmt = mysqli_prepare($DB_conn, $query);
$text = "Price edited from $product_editPrice_was to $product_editPrice_now";
mysqli_bind_param($stmt, "ss", $orderID, $text);
mysqli_stmt_execute($stmt);
Another solution is to create to different fields like price_before, price_after.
But if you can't do it, you can try using mysql CONCAT() and placeholders for example, but i'm not sure if it works:
INSERT INTO CDBusers_activity (order_ID, activity_text_desc) VALUES (?, CONCAT('Price edited from ', ?, ' to ', ?)
but I am interested if there is a simpler way?
This is an interesting question. In a way.
$text = "Price edited from $product_editPrice_was to $product_editPrice_now";
is apparently the easiest way to create a text string. While this text string can be bound to a query the usual way with a placeholder. Besides, you will have your SQL and data separated from each other, which will help you to organize your code better.
So I think that there are things you should not make simpler. Because such an attempt will likely make things more complex.
I am having error and I am not able to identify the problem. I will really appreciate help.
$sql = "INSERT INTO scrapeddata (Id,Store, ImageURL, ShortDescription, CashPercentage, ShoppingPoints, LongDescription, Contact, Information)
VALUES ($ID, $name, $ImageUrl, $ShortDecription, $CashBack, $SallingPoints, $LongtDecription, $Contact, $Information)";
Structure of my Table is :
Update :
Following image illustrate the actual error, php variable is resolved dynamically to retreive the string , but "with in the string" it contains single quotes ' according to me these quotes are causing error . Help !!
Put quotations on string variables.
And escape all ur variables before inserting in query.
mysql-escape-string
$name = mysql_escape_string($name);
$sql = "INSERT INTO scrapeddata (Id,Store, ImageURL, ShortDescription, CashPercentage, ShoppingPoints, LongDescription, Contact, Information)
VALUES ('$ID', '$name', '$ImageUrl', '$ShortDecription', '$CashBack', '$SallingPoints', '$LongtDecription', '$Contact', '$Information')";
my php code which is throwing errors is as follows:
$stmt = $con->prepare('INSERT INTO listOfRides (address, time) VALUES
('$address', '$time')') ;
I have looked at other posts and it seems I am using the variables correctly with the single quotes around them however the following error is being shown when visiting the URL:
Parse error: syntax error, unexpected T_VARIABLE in /home/gbidjght/public_html
/insertRide.php on line 79
Any help is appreciated
If you escaped the single quotes you would end up with the string literals "$address" and "$time" being inserted into your DB:
$stmt = $con->prepare('INSERT INTO listOfRides (address, time) VALUES (\'$address\', \'$time\')');
However assuming that they should be variables, you should use double quotes around your SQL statement to allow PHP to actually parse your variables as their values:
$stmt = $con->prepare("INSERT INTO listOfRides (address, time) VALUES ('$address', '$time')");
That being said, since you're already preparing your statement, why not just use placeholders anyway? It'll be a safer way to protect against SQL injection.
$stmt = $con->prepare("INSERT INTO listOfRides (address, time) VALUES (?, ?)");
$stmt->execute(array($address, $time));
change the outer quotes to double quotes
$stmt = $con->prepare("INSERT INTO listOfRides (address, time) VALUES
('$address', '$time')") ;
You can't put mysql ' in php '
Use this
$stmt = $con->prepare("INSERT INTO listOfRides (address, time) VALUES
('$address', '$time')") ;
Because of the 's the error is coming. Add " instead of '.Try this -
$stmt = $con->prepare("INSERT INTO listOfRides (address, time) VALUES ('$address', '$time')") ;
$stmt = $con->prepare("INSERT INTO `listOfRides` (`address`, `time`)
VALUES
($address, $time)") ;
Thanks for helping me out.
I'm trying to do something simple : just 2 inserts in the database.
The first one works well:
$stmt = $db->prepare("INSERT INTO sessions(date, lieu, trainer) VALUES (?,?,?)");
$stmt->bind_param("sss", $date, $location, $trainer);
$stmt->execute();
$session = $stmt->insert_id;
$stmt->close();
Then, I try to do another insert: I have a table 'users' which has 4 columns : an Id, auto-incremented, a username (column called 'fullName'), a sessionId (an int) and a contactInfo (a varchar).
Here's my code for the second insert:
//var_dump($session); returns an int
$stmt = $db->prepare("INSERT INTO users(fullName, sessionId, contactInfo) VALUES (?,?,?)");
$stmt->bind_param("sis", "$username", "$session", "$contactinfo");
$stmt->execute();
$newId = $stmt->insert_id;
$stmt->close();
From what I could read from other posts, it seems that this issue comes when you try to pass a parameter that's not a parameter (e.g.:an int) but in my case it's a variable, I reuse "$session" from the first block ($session = $stmt->insert_id;)
Am I allowed to do that? What did I miss?
Thanks!
EDIT: removed the single quotes and put double quotes, but that doesn't seem to cut it. Tried to put them for both strings but not for session but it doesn't change the result.
EDIT2:following the good advice from serjoscha, I printed the query to have an idea of what it looks like:
echo "INSERT INTO users (fullName, sessionId, contactInfo) VALUES ($username,$session,$contactinfo)";
which gives me something like
INSERT INTO users (fullName, sessionId, contactInfo) VALUES (Paul Honour,56,Location Liège Belgium Email ph#ph.be +329999999)
The query only works if I put it like this:
INSERT INTO users (fullName, sessionId, contactInfo) VALUES ('Paul Honour',56,'Location Liège Belgium Email ph#ph.be +329999999')
Any idea what's wrong?
Your issue are the single quoted variables. Just remove the single quotes or use double quotes for the content of double quotes is partitial evaluated / parsed:
$a=3;
echo '$a'; // prints: $a
echo "$a"; // prints: 3
echo $a; // prints: 3 and this is just what you need
You do not need the quotes for variables, so just remove them:
$stmt->bind_param("sis", $username, $session, $contactinfo);
Found out the issue:
it was failing on "Liège", some problem with the accent. I made sure I had the same encoding on both sides, and I can finally insert!
My code now looks like:
$contactinfo = $db->real_escape_string($contactinfo);
$stmt = $db->prepare("INSERT INTO users (fullName, sessionId, contactInfo) VALUES (?,?,?)");
$stmt->bind_param("sis", $username, $session, $contactinfo);
$stmt->execute();
$userId = $stmt->insert_id;
$stmt->close();
I would like to know when to use a single quote within a double quote and vice-versa. The scenario becomes more complicated when there is a variable involved.
For example, I was trying to insert values into the database using the following code:
$sql = 'INSERT INTO demo_table (name, dob, age, address) VALUES ("$name", "$dob", "$age", "$address")';
It did work but it interpreted $name, $dob, $age and $address as strings and not a variable holding values, so actual values were not saved.
Are there any rules when to use single quote, double quote, quotes with backslash(like \' or \") and what to do when there is need to use quotes within quotes. I have also seen some codes using concatenation sign(.) within quotes. What is the logic behind that?
database characters requires single quotes ' '.
So keep the characters in query in ' '.
$query="INSERT INTO table_name (name, email, password) VALUES ('$username','$email','$password')";
It should be like this:
$sql = "INSERT INTO demo_table (name, dob, age, address) VALUES ('".$name."', '".$dob."', '".$age."', '".$address."')";
In php a string in single quotes is a constant value and a string in double quotes is a dynamic string.
so you can use:
$sql = "INSERT INTO demo_table (name, dob, age, address) VALUES ('$name', '$dob', '$age', '$address')";
OR
$sql = "INSERT INTO demo_table (name, dob, age, address) VALUES ('".$name."', '".$dob."', '".$age."', '".$address."')";
Notice the . either side of the $name, $dob, $age, $address variable which concatenates string values.
And it may be better to create your queries as strings. Doing that allows you to echo the queries when checking to ascertain that produces values you are expecting.
Hope that helps.