What are rules for using single and double quote in php? - php

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.

Related

Need to insert a string that may have double quotes

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

Error in insert into statement MySQL PHP

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

php mysql insert statement using variables

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

MySQL Insert from PHP

I'm having a little trouble with my insert statement this morning. Yes, I am using the deprecated mysql_query function. My insert statement looks as follows:
$query3 = "INSERT INTO ".$db_prefix ." offer_det
(fname, lname, 10k, 14k, 18k, 21k, 22k, 24k, 925, coins, bars)
VALUES '".$fname."', '".$lname."', '".$_10k."', '".$_14k."',
'".$_18k."', '".$_21k."', '".$_22k."', '".$_24k."',
'".$_925."', '".$coins."', '".$bars."')";
$result3 = mysql_query($query3);
My PHP form values are all the variables listed in the first part of the insert statement, 'fname', etc.
My variables are set to pull from the post and are listed as the values going into the insert.
I had to change the variables to underscore before they started, I guess PHP didn't like that.
My questions:
Are those 10k, 14k, etc, okay mysql table row names?
Is there an issue I'm missing here?
The datatype for fname and lname are varchar and for the 10k through bars are decimal (7,3).
The column name 925 must be quoted using backticks.
(`fname`, `lname`, `10k`, `14k`, `18k`, `21k`, `22k`, `24k`, `925`, `coins`, `bars`)
You may also want to consider changing the column names to something else to avoid further similar problems in the future.
You should quote the 925 column name, as per MySQL Schema Object names
So correctly:
$query3 = "insert into ".$db_prefix."offer_det (fname, lname, 10k, 14k, 18k, 21k, 22k, 24k, `925`, coins, bars)
values
('".$fname."', '".$lname."', '".$_10k."', '".$_14k."', '".$_18k."', '".$_21k."',
'".$_22k."','".$_24k."', '".$_925."', '".$coins."', '".$bars."')";
Another recommendation: you should escape the incoming strings, because SQL injection is a nasty thing to experience...
Use the QUERY as like follow..
$query3 = "insert into ".$db_prefix."offer_det (fname, lname, 10k, 14k, 18k, 21k, 22k, 24k, 925, coins, bars)
values ('$fname', '$lname', '$_10k', '$_14k', '$_18k', '$_21k', '$_22k',
'$_24k', '$_925', '$coins', '$bars')";
$query_exec=mysql_query($query3) or die(mysql_error());
And for inserting a variable you need to use single codes only..
Can I be bold and suggest a change in your implementation?
/// put your vars in an easier to use format
$insert = array(
'fname' => $fname,
'lname' => $lname,
'10k' => $_10k,
/* and so on ...*/
);
/// considering you are using mysql_query, use it's escape function
foreach ( $insert as $field => $value ) {
$insert[$field] = mysql_real_escape_string($value);
}
/// pull out the keys as fields and the values as values
$keys = array_keys($insert);
$vals = array_values($insert);
/// the following should auto backtick everything... however it should be
/// noted all the values will be treated like strings as you were doing anyway
$query = "INSERT INTO `" . $db_prefix . "offer_det` " .
"(`" . implode('`,`', $keys) . "`) " .
"VALUES ('" . implode("','", $vals ) . "')";

Inserting Integer value into mysql int using INSERT

I'm trying to insert a new record in a MySQL database from PHP, which I've done a million times before, but for some reason, I can't get it to work this time, and it really bugs me.
Inserting strings into all the varchar collumns are going great, but when I get to inserting a value into the int column, I get an error telling me that I have a syntax error.
Basically, the first query works just fine, but the second one returns the error, and as you can see, I've made damn sure it really is an integer I'm trying to insert.
I hope somebody can help. I'm really starting to develop a headache over this :/
$groupId2 = 5;
$groupId = (int)$groupId2;
if(!mysqli_query($link, "INSERT INTO contestants (firstName, lastname, email) VALUES ('$firstName', '$lastName', '$email')"))
echo "First: " . mysqli_error($link);
if(!mysqli_query($link, "INSERT INTO contestants (firstName, lastname, email, group) VALUES ('$firstName', '$lastName', '$email', '$groupId')"))
echo "Second: " . mysqli_error($link);
group is a mysql keyword use back quotes around it
"INSERT INTO contestants (firstName, lastname, email, `group`)
VALUES ('$firstName', '$lastName', '$email', '$groupId')"
The error is because you surrounded your int with ' ', you need to get rid of your apostrophes and it will work just fine.
if(!mysqli_query($link,
"INSERT INTO contestants
(firstName, lastname, email, group) VALUES
('$firstName', '$lastName', '$email', $groupId)"))
^^^^^^^^^
To clarify, when inserting numerical fields you do not need them.
According to pst this is wrong, although, the fact you do not need single quotes is still correct.

Categories