This question already has answers here:
MySQL Insert query doesn't work with WHERE clause
(31 answers)
Closed 4 years ago.
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
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. :)
Related
In my test-surroundings there is a database containing some Person Information (Name, E-Mail, Adress etc.). These Informations can be inserted by anyone into the database via a form. In the background they are inserted with a parameterized INSERT into the database after submission.
What I now would like to do is to detect if some person tries to insert the same values into the database again, and if he does, not inserting the new values and instead showing an error message. (So every person name in the database is unique, there are no multiple rows linked to one name).
I had a numerous number of ideas on how to accomplish this. My first one was to use a query like REPLACE or INSERT IGNORE, but this method would not give me feedback so I can display the error message.
My second attempt was to first do a SELECT-query, checking if the row already exists, and if num_rows is greater than 0, exit with the error message (and else do the INSERT-part). For this to work I will have to use parameterized queries for the SELECT too, as I´m putting some user input into it. Figuring that parameterized queries need special functions for everything you could normally do with way less lines of code, I researched in the internet on how to get num_rows from my $statement parameterized-statement-object. This is what I had in the end:
$connection = new mysqli('x', 'x', 'x', 'x');
if (mysqli_connect_error()) {
die("Connect Error");
}
$connection->set_charset("UTF-8");
$statement = $connection->stmt_init();
$statement = $connection->prepare('SELECT Name FROM test WHERE Name LIKE ?');
flags = "s";
$statement->bind_param($flags, $_POST["person_name"]);
$statement->execute();
$statement->store_result();
$result = $statement->get_result(); //Produces error
if ($result->num_rows >= 1) {
$output = "Your already registered";
} else {
$output = "Registering you...";
}
exit($output);
After all, I can´t get why mysqli still won´t give me num_rows from my statement. Any help is appreciated, thanks in advance!
Oh, and if you guys could explain to me what I have to do to get affected_rows,that would be awesome!
EDIT: I know I could to this by using unique constraints. I also found out that I can find out if INSERT IGNORE skipped the INSERT or not. But that won´t answer my complete question: Why does the SELECT num_rows alternative not work?
ANOTHER EDIT: I changed the code snippet to what I now have. Although my mysql(i)-version seems to be 5.6.33 (I echo´d it via $connection->server_info) get_result() produces the following error message:
Fatal error: Call to undefined method mysqli_stmt::get_result() in X on line X (line of get_result)
The behaviour of mysqli_num_rows() depends on whether buffered or unbuffered result sets are being used. For unbuffered result sets, mysqli_num_rows() will not return the correct number of rows until all the rows in the result have been retrieved. Note that if the number of rows is greater than PHP_INT_MAX, the number will be returned as a string.
Also make sure that you declare ->store_result() first. Moreover the function doesn't work with LIMIT used jointly with SQL_CALC_FOUND_ROWS. If you want to obtain the total rows found you must do it manually.
EDIT:
If nothing from the suggestions does not work for you, then I would propose to rewrite your SQL query:
SELECT `Name`, (SELECT COUNT(*) FROM `Persons`) AS `num_rows` FROM `Persons` WHERE `Name` LIKE ?
This query will return the total number from your Persons table, as well as Name, if exist.
$query = "INSERT INTO directory_level_one (child_categories)
VALUES
('$category_name')
WHERE
category = '$parent'";
currently, I get the following error when I add the WHERE part in the above sql query.
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 'WHERE category = 'Philosophy'' at line 4
You can't have a where clause for an Insert statement. Are you trying to update existing database records instead? In that case, use the Update statement.
INSERT statements don't have a WHERE clause.
Perhaps you want an UPDATE statement instead?
UPDATE directory_level_one
SET child_categories = 'your_category_name'
WHERE category = 'your_parent'
you can't use a where clause with an insert statement.
where clause can not be used in INSERT statment
please read this before preceding further http://dev.mysql.com/doc/refman/5.5/en/insert.html
What you want to do is this:
$query = "UPDATE directory_level_one SET child_categories='$category_name' WHERE category = '$parent'";
I think you might want to change your INSERT to an UPDATE
How can I add data from a HTML page, into a MySQL Database based on the attributes?
It's already scraped data, but I would like to import links into a particular field in a table and remove some things from them (ill work that out) and another from into another field in a table.
I have PHP/MySQL and Linux. Should I use curl, and if so how do I actually add data into a MySQL DB?
Some PHP example to Insert and update data:
//***************************************
// Connect to database
//
mysql_connect('127.0.0.1','MyUserName','MyPassword',false,MYSQL_CLIENT_SSL|MYSQL_CLIENT_COMPRESS);
mysql_select_db('MyDatabase');
// If you work with UTF-8 it would be a good idea to set the character set as well to be sure.
//mysql_set_charset('utf8_general_ci');
//***************************************
// Insert new data
//
$MyURL = mysql_real_escape_string("http://www.exampledomain.com/product/");
$Result = mysql_query("INSERT INTO ProductTable (URLField) VALUES ('".$MyURL."')");
if($Result)
print mysql_affected_rows();
//***************************************
// Update existing data
//
$MyURL = mysql_real_escape_string("http://www.exampledomain.com/newproduct/");
$RecordID = 123;
$Result = mysql_query("UPDATE ProductTable SET URLField='".$MyURL."' WHERE ID=".$RecordID);
if($Result)
print mysql_affected_rows();
Connect to the MySQL Server with mysql_connect() and use mysql_select_db() to select the database.
I'm not native English and use UTF-8 to get all the special character correct. If you have no need of this you can ignore this line.
All data that goes into a SQL server should be be sanitized, meaning escaping control characters such as quotes. The Variable $MyURL is sanitized with mysql_real_escape_string() before it is used in the SQL statement.
The SQL statement is executed with mysql_query() and returns true or false (for INSERT and UPDATE statements). With mysql_affected_rows() you can see how many rows that was affected by the SQL statement, a way to see if it worked as expected.
Next comes an UPDATE example to change data in a single column and/or row. The $RecordID variable is the record ID you want to update (you need to know what record you want to update). This example is pinpointing a single record. By changing the WHERE clausule you can update a whole bunch of rows at the same time. For example
UPDATE ProductTable SET URLField='".$MyURL."' WHERE URLField='http://www.exampledomain.com/oldproduct/'
...will update all rows that have 'http://www.exampledomain.com/oldproduct/' in the field URLField.
I think this will get you going for a while...
http://us3.php.net/manual/en/function.mysql-query.php
You will then use a MySQL query like "INSERT INTO table_name (column1,column2) VALUES ('Testing','Testing 2')
I have a table user_name with 3 fields, id, Name, Email (id is auto_increment field). I want to execute the following query in PHP, but its not returning any result.
INSERT INTO user_name (Name, Email) VALUES ('Example', 'example#xyz.com');
SELECT LAST_INSERT_ID() AS 'userid';
When I am executing the above query in PHP as below then its not returning anything.
$_SQL="INSERT INTO user_name (Name,Email) VALUES ('Example', 'example#xyz.com');
SELECT LAST_INSERT_ID() AS 'userid';";
$result_last_id = #mysql_query($_SQL);
$rs_insert = mysql_fetch_array($result_last_id);
$new_userid = $rs_insert['userid'];
Can anyone please tell me how to execute both queries into one.
Give a look to the mysql_insert_id() function.
mysql_query($insertStatementOnly);
$new_userid = mysql_insert_id();
It appears you don't need to execute multiple queries, but I included how to do it below. What you want is the last inserted id, which you get from mysql_insert_id.
To execute multiple queries
From comments on documentation of mysql_query:
The documentation claims that "multiple queries are not supported".
However, multiple queries seem to be supported. You just have to pass flag 65536 as mysql_connect's 5 parameter (client_flags). This value is defined in /usr/include/mysql/mysql_com.h:
#define CLIENT_MULTI_STATEMENTS (1UL << 16) /* Enable/disable multi-stmt support */
Executed with multiple queries at once, the mysql_query function will return a result only for the first query. The other queries will be executed as well, but you won't have a result for them.
Alternatively, have a look at the mysqli library, which has a multi_query method.
Simple answer really: You just can't do it.
http://php.net/mysql_query
May I also suggest you avoid the error-suppression operator '#' in mysql_query as you may not be made aware of any mysql errors. At the very least do
mysql_query($sql) or die("error: " . mysql_error()) ;
If you are using the Zend Framework with a PDO defined MySQL database, you would just use:
$database=Zend_Db::factory('PDO_MySQL',Array('hostname'=>'localhost','username'=>'x','password'=>'y','dbname'=>'z');
$connectionHandle=$database->getConnection();
$rowsInserted=$connectionHandle->insert('database_name','INSERT INTO x (a,b) VALUES (c,d)');
if ($rowsInserted>0) {
$autoIncrementValue=$connectionHandle->lastInsertId();
}
Yes You can using Shell command <BR>
mysql -user -p -h database -e '
SQL STATEMENT 1;
SQL STATEMENT 2;
SQL STATEMENT 3;
.......;
'
Php / MYSQL Programmer
this might do what u want:
insert into table1 (Name,Emails) values ('qqq','www');
select max(id) as lastinserted from table1;
Hi guys I was hoping from some help here, please.
I have a INSERT query to a table, after this is done I am calling:
mysql_insert_id();
In order to send the last ID inserted into the table to the next page like this:
$insertGoTo = "confirm_booking.php?booking_ID=" .$_POST['booking_ID']. "";
Unfortunately it does not work, all I get is a zero.
The table I am inserting into has an auto increment number and values are inserted into it.
I have also tried SELECT MAX(id) FROM mytable. This dosn't work neither.
I know that this problem has been talked about already. I read all posts but nothing came useful.
Many thanks Francesco
You have to use the value returned by MySql_Insert_Id () when you generate your link:
// your query
$newId = MySql_Insert_Id ();
$insertGoTo = "confirm_booking.php?booking_ID=" . $newId;
It is possible that your table does not have any AUTO_INCREMENT field!
It could also happen because you have two or more mysql connections at the same time.
In this case you should use a link identifier.
$link = mysql_connect( ... );
mysql_select_db('mydb', $link);
mysql_query('INSERT mytable SET abc="123"', $link);
$inserted_id = mysql_insert_id($link);
Some key points from the PHP Manual:
The ID generated for an AUTO_INCREMENT
column by the previous query on
success, 0 if the previous query does
not generate an AUTO_INCREMENT value,
or FALSE if no MySQL connection was
established.
If not having an AUTO_INCREMENT field is not your problem, you might want to try storing the result of the mysql_query call and using that as an argument to the id function
$result = mysql_query("...");
$id = mysql_insert_id($result);
Had an issue using a query like this:
INSERT INTO members (username,password,email) VALUES (...)
reason being that the id (which is my primary key and Auto Increment field) is not part of the query.
Changing it to:
INSERT INTO members (id,username,password,email) VALUES ('',...)
using a an empty value '' will have MySQL use the Auto Increment value but also allow you to use it in your query so you can return the insert id
mysql_insert_id may return 0 or false if your insert fails right?
So if you have trouble with mysql_insert_id not retunring what you expect confirm that you don't have a unique constraint or some other problem with your sql that would cause the insert to fail. Using max is a terrible idea if you consider this.
Make sure to put mysql_insert_id()after the
mysql_query($sql, $con); //Execute the query
Above query responsible for execute your Insert INTO ... command.
After you can get the last ID inserted
I have also suffer from this problem. Finally I found that the problem occur in my connection to the database. You can use this following connection code to connect the database then you can easily use mysqli_insert_id().
$db_connect = mysqli_connect("localhost", "root", "", "social");
Then you can use mysqli_insert_id() as
$id = mysqli_insert_id($db_conx);
I hope this will help you. I you have any problem then leave your comment.
The mysqli_insert_id function has been deprecated. This may be your problem.
Instead, try $mysqli->insert_id. See the documentation for more info.