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;
Related
When I add AND operator in mysql_query() function, it stops working and anything after that stops working!
For Example:
When i wrote this:
$query1 = mysql_query("SELECT * FROM chat1 where friendname = '$_POST[fname]' ");
$row= mysql_fetch_array($query1) or die(mysql_error());
echo "$row[message]";
The above query runs successfully !
But when i do this :
$query1 = mysql_query("SELECT * FROM chat1 where friendname = '$_POST[fname]' AND username = '$_POST[uname]' ");
$row= mysql_fetch_array($query1) or die(mysql_error());
echo "$row[message]";
I get Null output!
I think the "AND" operator is not working!!!
please help me with this!!
Have a look at my complete code and Database Snapshot!
Click here
If it is returning NULL then probably the record doesn't exists. Try to output this query on the screen and post the raw query here.
Maybe your search needs a LIKE instead of a =
Likely, the row(s) you are looking for do not exist.
The AND is a boolean operator that requires that both expressions have to evaluate to true. In the context of your query, that means for a row to be returned, both of the conditions have to be true on that single row.
I suspect that you may want an OR those two conditions. Did you want to return only rows that meet both criteria, or did you want any rows that have fname with a certain value, along with any rows that have uname of a specific value? If the first query is returning rows, then replacing AND with OR should return you some rows.
For debugging this type of problem, generate the SQL text into a variable, and then echo or var_dump the SQL text, before you send it to the database.
e.g.
$sql = "SELECT * FROM chat1 where friendname = '"
. mysql_real_escape_string($_POST['fname'])
."' ";
echo "SQL=" . $sql ; # for debugging
Take the text of SQL statement that's emitted to another client, to test the SQL statement, to figure out if the SQL statement is actually returning the resultset you expect it to return.
(In your code, reference the $sql in the function that prepares/executes the SQL statement.)
Follow this pattern for all dynamically generated SQL text: generate the SQL text into a variable. For debugging, echo or var_dump or otherwise emit or log the contents of the variable. Take the SQL text to another client and test it.
Dumping code that isn't working on to StackOverflow is not the most efficient way to debug your program. Narrow down where the problem is.
How to debug small programs http://ericlippert.com/2014/03/05/how-to-debug-small-programs/
NOTES
You probably want to verify that $_POST['fname']) contains a value.
It's valid (SQL-wise) for a SELECT statement to return zero rows, if there are no rows that satisfy the predicates.
Potentially unsafe values must be properly escaped if you include them in the text of a SQL statement. (A better pattern is to use prepared statements with bind placeholders, available in the (supported) mysqli and PDO interfaces.
Also, use single quotes around fname.... e.g.
$_POST['fname']
^ ^
I want to a select query and an insert query that I want to do them together using function(mysql_query),but it's not working.
I'm tying to do somthing like this:
$sql="select * from texts; insert into date ('time') values ('2012');";
mysql_query($sql);
is there any way to do it?
mysql_query() sends a unique query (multiple queries are not supported) .
That's the default behaviour.However there is a bypass for this.
However the result code of the first query alone will be given as output of mysql_query() if you do this.
You just have to pass flag 65536 as mysql_connect's 5th parameter . the flag is defined in MySQL Client flags.
#define CLIENT_MULTI_STATEMENTS 65536 /* Enable/disable multi-stmt support */
#define CLIENT_MULTI_RESULTS 131072 /* Enable/disable multi-results */
So edit your mysql_connect() code to match this:
mysql_connect($host, $username, $password, false, 65536);
Warning:
You will get the result of mysql_query($query) for the first query only in the given $query . You can try concatenating 131072 with 65536 for getting multiple results.
This will not work on PHP < 4.3.0
This will not work if sql.safe_mode is set as 1 in php.ini
Another alternative will be to use mysqli instead of mysql library. It supports $mysqli->multi_query() and gives output within an array for each query.
MySQL don't allow passing more than one select query in single statement.
None of the mysql api can deal with several queries simultaneously, even mysql consol utility parses your input and executes one query after another and php's mysql_query doesn't. You just can write your own function doing it or just put all queries in an array and execute mysql_query for each element in a loop.
You can use mysqli_multi_query function but with PHP mysqli extension. (I recommend you to use mysqli instead of mysql extension of PHP because it includes much more features & facilities)
mysql_query() sends a unique query
see mysql_query
for multiple query you can see mysqli
mysql_query() doesn't support multiple queries execution in normal way.
use something like below.
<?php
$str="query1;query2;"; // say $str="select * from texts; insert into date ('time') values ('2012');";
$query = explode(';',$str);
// Run the queries
foreach($query as $index => $sql)
{
$result = mysql_query($sql);
// Perform an additional operations here
}
?>
I have the following SQL that works directly in MySQL
INSERT INTO `my_tabel` (`data`) VALUES ("my_value");
SELECT * from `my_tabel` ORDER BY `id` DESC LIMIT 1
It inserts a row, and then gets the new row so that I can return the new ID to use later.
When I try to run the SQL in codeIgniter I get an error message stating that I have an error in my SQL
$m = new my_model();
$sql = 'INSERT INTO `my_tabel` (`data`) VALUES ("'.$my_value.'"); SELECT * from `my_tabel` ORDER BY `id` DESC LIMIT 1';
$m->query($sql);
Running a single SQL statement works fine in codeIgniter, but not when I add the second SELECT... statement.
Any ideas (or alternative solutions)?
Thanks
This is not a limitation of CI but that of the database client libraries.
only a single query can be executed at a time.
Why not run two $m->query() statements? That way you can check the success of each individually from CI.
In most SQL interfaces, having multiple statements in a query is problematic because of the different types of result from each. Even when calling a stored procedure, it is necessary to carefully craft the stored procedure not to return extraneous results, though even that can usually be handled with a special, relaxed api which allows multiple results.
insert_id() is your friend!
$this->db->insert_id()
From here http://codeigniter.com/user_guide/database/helpers.html
So something like:
$insert_data = array(
'data' => $my_value
);
$this->db->insert('my_table', $insert_data);
$last_id = $this->db->insert_id();
Instead of running 2 queries, to get the id created after the insert query use:
$this->db->insert_id();
As noted in the other answers, use $this->db->insert_id() is better because there is a chance that another user inserts a row between your two queries. Since PHP can only execute one query at a time, this can become a race condition.
Thanks for everyone's help. The solution that worked for me was
$m = my_model();
$m->data = $value;
$m->save();
echo $m->id;
http://www.codeigniter.com/userguide2/database/active_record.html#caching
You can use Caching to control multiple queries without conflicts.
This question already has answers here:
Getting raw SQL query string from PDO prepared statements
(16 answers)
Closed 6 years ago.
In PHP, when accessing MySQL database with PDO with parametrized query, how can you check the final query (after having replaced all tokens)?
Is there a way to check what gets really executed by the database?
So I think I'll finally answer my own question in order to have a full solution for the record. But have to thank Ben James and Kailash Badu which provided the clues for this.
Short Answer
As mentioned by Ben James: NO.
The full SQL query does not exist on the PHP side, because the query-with-tokens and the parameters are sent separately to the database.
Only on the database side the full query exists.
Even trying to create a function to replace tokens on the PHP side would not guarantee the replacement process is the same as the SQL one (tricky stuff like token-type, bindValue vs bindParam, ...)
Workaround
This is where I elaborate on Kailash Badu's answer.
By logging all SQL queries, we can see what is really run on the server.
With mySQL, this can be done by updating the my.cnf (or my.ini in my case with Wamp server), and adding a line like:
log=[REPLACE_BY_PATH]/[REPLACE_BY_FILE_NAME]
Just do not run this in production!!!
You might be able to use PDOStatement->debugDumpParams. See the PHP documentation .
Using prepared statements with parametrised values is not simply another way to dynamically create a string of SQL. You create a prepared statement at the database, and then send the parameter values alone.
So what is probably sent to the database will be a PREPARE ..., then SET ... and finally EXECUTE ....
You won't be able to get some SQL string like SELECT * FROM ..., even if it would produce equivalent results, because no such query was ever actually sent to the database.
I check Query Log to see the exact query that was executed as prepared statement.
I initially avoided turning on logging to monitor PDO because I thought that it would be a hassle but it is not hard at all. You don't need to reboot MySQL (after 5.1.9):
Execute this SQL in phpMyAdmin or any other environment where you may have high db privileges:
SET GLOBAL general_log = 'ON';
In a terminal, tail your log file. Mine was here:
>sudo tail -f /usr/local/mysql/data/myMacComputerName.log
You can search for your mysql files with this terminal command:
>ps auxww|grep [m]ysqld
I found that PDO escapes everything, so you can't write
$dynamicField = 'userName';
$sql = "SELECT * FROM `example` WHERE `:field` = :value";
$this->statement = $this->db->prepare($sql);
$this->statement->bindValue(':field', $dynamicField);
$this->statement->bindValue(':value', 'mick');
$this->statement->execute();
Because it creates:
SELECT * FROM `example` WHERE `'userName'` = 'mick' ;
Which did not create an error, just an empty result. Instead I needed to use
$sql = "SELECT * FROM `example` WHERE `$dynamicField` = :value";
to get
SELECT * FROM `example` WHERE `userName` = 'mick' ;
When you are done execute:
SET GLOBAL general_log = 'OFF';
or else your logs will get huge.
What I did to print that actual query is a bit complicated but it works :)
In method that assigns variables to my statement I have another variable that looks a bit like this:
$this->fullStmt = str_replace($column, '\'' . str_replace('\'', '\\\'', $param) . '\'', $this->fullStmt);
Where:
$column is my token
$param is the actual value being assigned to token
$this->fullStmt is my print only statement with replaced tokens
What it does is a simply replace tokens with values when the real PDO assignment happens.
I hope I did not confuse you and at least pointed you in right direction.
The easiest way it can be done is by reading mysql execution log file and you can do that in runtime.
There is a nice explanation here:
How to show the last queries executed on MySQL?
I don't believe you can, though I hope that someone will prove me wrong.
I know you can print the query and its toString method will show you the sql without the replacements. That can be handy if you're building complex query strings, but it doesn't give you the full query with values.
I think easiest way to see final query text when you use pdo is to make special error and look error message. I don't know how to do that, but when i make sql error in yii framework that use pdo i could see query text
This question already has answers here:
Getting raw SQL query string from PDO prepared statements
(16 answers)
Closed 6 years ago.
In PHP, when accessing MySQL database with PDO with parametrized query, how can you check the final query (after having replaced all tokens)?
Is there a way to check what gets really executed by the database?
So I think I'll finally answer my own question in order to have a full solution for the record. But have to thank Ben James and Kailash Badu which provided the clues for this.
Short Answer
As mentioned by Ben James: NO.
The full SQL query does not exist on the PHP side, because the query-with-tokens and the parameters are sent separately to the database.
Only on the database side the full query exists.
Even trying to create a function to replace tokens on the PHP side would not guarantee the replacement process is the same as the SQL one (tricky stuff like token-type, bindValue vs bindParam, ...)
Workaround
This is where I elaborate on Kailash Badu's answer.
By logging all SQL queries, we can see what is really run on the server.
With mySQL, this can be done by updating the my.cnf (or my.ini in my case with Wamp server), and adding a line like:
log=[REPLACE_BY_PATH]/[REPLACE_BY_FILE_NAME]
Just do not run this in production!!!
You might be able to use PDOStatement->debugDumpParams. See the PHP documentation .
Using prepared statements with parametrised values is not simply another way to dynamically create a string of SQL. You create a prepared statement at the database, and then send the parameter values alone.
So what is probably sent to the database will be a PREPARE ..., then SET ... and finally EXECUTE ....
You won't be able to get some SQL string like SELECT * FROM ..., even if it would produce equivalent results, because no such query was ever actually sent to the database.
I check Query Log to see the exact query that was executed as prepared statement.
I initially avoided turning on logging to monitor PDO because I thought that it would be a hassle but it is not hard at all. You don't need to reboot MySQL (after 5.1.9):
Execute this SQL in phpMyAdmin or any other environment where you may have high db privileges:
SET GLOBAL general_log = 'ON';
In a terminal, tail your log file. Mine was here:
>sudo tail -f /usr/local/mysql/data/myMacComputerName.log
You can search for your mysql files with this terminal command:
>ps auxww|grep [m]ysqld
I found that PDO escapes everything, so you can't write
$dynamicField = 'userName';
$sql = "SELECT * FROM `example` WHERE `:field` = :value";
$this->statement = $this->db->prepare($sql);
$this->statement->bindValue(':field', $dynamicField);
$this->statement->bindValue(':value', 'mick');
$this->statement->execute();
Because it creates:
SELECT * FROM `example` WHERE `'userName'` = 'mick' ;
Which did not create an error, just an empty result. Instead I needed to use
$sql = "SELECT * FROM `example` WHERE `$dynamicField` = :value";
to get
SELECT * FROM `example` WHERE `userName` = 'mick' ;
When you are done execute:
SET GLOBAL general_log = 'OFF';
or else your logs will get huge.
What I did to print that actual query is a bit complicated but it works :)
In method that assigns variables to my statement I have another variable that looks a bit like this:
$this->fullStmt = str_replace($column, '\'' . str_replace('\'', '\\\'', $param) . '\'', $this->fullStmt);
Where:
$column is my token
$param is the actual value being assigned to token
$this->fullStmt is my print only statement with replaced tokens
What it does is a simply replace tokens with values when the real PDO assignment happens.
I hope I did not confuse you and at least pointed you in right direction.
The easiest way it can be done is by reading mysql execution log file and you can do that in runtime.
There is a nice explanation here:
How to show the last queries executed on MySQL?
I don't believe you can, though I hope that someone will prove me wrong.
I know you can print the query and its toString method will show you the sql without the replacements. That can be handy if you're building complex query strings, but it doesn't give you the full query with values.
I think easiest way to see final query text when you use pdo is to make special error and look error message. I don't know how to do that, but when i make sql error in yii framework that use pdo i could see query text