返回False的PHP SQL Execute语句[重复]
This question already has an answer here:
- MySQL Insert Where query 25 answers
I am trying to run a basic SQL statement, but I can't figure out what I am doing wrong. Here is the context:
I have a database named: my_database
a table named: users
Two columns: service_id which type is BIGINT
and video_id which type is varchar(20)
Here is my code:
$video_id = "chartext";
$service_id = 12345678910;
$bdd = new PDO("mysql:host=127.0.0.1;dbname=moods_db", "user", "pass");
$query = $bdd->prepare("INSERT INTO users(video_id) VALUES (?) WHERE service_id = $service_id");
$query->execute([$service_id]);
var_dump($req->execute([$video_id]));
// which gives me false
Some info: My PHP_INT_MAX gives me 9223372036854775807
I am aware of SQL Injection and just removed it to be clearer
I var_dumped each steps and the execute one is the only one that is not working
I ran the statement in phpmyadmin console and it told me: "Syntax error near 'WHERE (service_id = '12345678910')' line 1
I also searched the usage of WHERE Clause but I did not understand if I could put it in an INSERT statement, I think I already did that and it worked, I am lost
Thanks in advance
</div>
PDOStatement::execute — Executes a prepared statement. It returns TRUE on success or FALSE on failure.
So for your case it is returning FALSE because In an INSERT statement you wouldn't have an existing row to do a WHERE clause.
You need to try like this way to insert one row with two values or use UPDATE query to update one row with one value based on another value on the existing row. Hope it clears your doubts now :)
$video_id = "chartext";
$service_id = 12345678910;
$bdd = new PDO("mysql:host=127.0.0.1;dbname=moods_db", "user", "pass");
$sql = "INSERT INTO users(video_id, service_id) VALUES (?,?)";
$array = array($video_id , $service_id );
$sth = $bdd->prepare($sql);
$sth->execute($array);
var_dump($sth);
Actually you can't use WHERE Clause with INSERT TO.
Here are some answers, https://stackoverflow.com/a/11913305/7183227 https://stackoverflow.com/a/485057/7183227
from MySQL Insert Where query
The problem is with the way you have written INSERT query. INSERT query does not contain where clause.
You have to update it your query as follows:
INSERT INTO users(video_id) VALUES (?)
You shouldn't use WHERE clause in INSERT query. so, either perform INSERT (it does not have WHERE) or try UPDATE where you can use WHERE clause. just visit here https://phpdelusions.net/pdo_examples/insert if you want to insert the record or here https://phpdelusions.net/pdo_examples/update if you want to update and check the syntax and perform it properly. :)