简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM