I have tried using multi_query but I keep getting a strict Standards message popping up.
$querystring = "INSERT INTO responses VALUES('1', '2', '3', '4'); INSERT INTO responses VALUES('1', '2', '3', '4')";
if (mysqli_multi_query($db, $querystring)) {
do {
if ($result = mysqli_store_result($db)) {
//
}
} while (mysqli_next_result($db));
}
echo "end";
The error message I get is:
Strict Standards: mysqli_next_result(): There is no next result set. Please, call mysqli_more_results()/mysqli::more_results() to check whether to call this function/method
I've tried adding and removing -; but had no luck.
While pipodesign corrected the error within the $querystring and alleviated the problem, the actual solution was not provided regarding the Strict Standards error.
I disagree with SirBT's advice, changing from DO WHILE to WHILE is not necessary.
The Strict Standards message that you receive is quite informative.
To obey, use this:
do{} while(mysqli_more_results($db) && mysqli_next_result($db));
Then, there is no need for you to write a conditional exit or break inside of the loop because the while condition will break the loop on the first occurrence of an error. *note, the if statement before the do-while will deny entry to the loop if the first query has an error.
In your example, you are only running INSERT queries, so you won't receive any result sets to process. If you want to count how many rows you've added, use mysqli_affected_rows().
As a complete solution for your question:
if(mysqli_multi_query($db,$querystring)){
do{
$cumulative_rows+=mysqli_affected_rows($db);
} while(mysqli_more_results($db) && mysqli_next_result($db));
}
if($error_mess=mysqli_error($db)){echo "Error: $error_mess";}
echo "Cumulative Affected Rows: $cumulative_rows";
Output:
// if no errors
Cumulative Affected Rows: 2
// if error on second query
Error: [something]
Cumulative Affected Rows: 1
// if error on first query
Error: [something]
Cumulative Affected Rows: 0
LATE EDIT:
Since people new to mysqli are stumbling across this post, I'll offer a general yet robust snippet to handle queries with/without result sets using multi_query() and add a feature to display which query in the array is being handled...
Classic "IF(){DO{} WHILE}" Syntax:
if(mysqli_multi_query($mysqli,implode(';',$queries))){
do{
echo "<br><br>",key($queries),": ",current($queries); // display key:value # pointer
if($result=mysqli_store_result($mysqli)){ // if a result set
while($rows=mysqli_fetch_assoc($result)){
echo "<br>Col = {$rows["Col"]}";
}
mysqli_free_result($result);
}
echo "<br>Rows = ",mysqli_affected_rows($mysqli); // acts like num_rows on SELECTs
} while(next($queries) && mysqli_more_results($mysqli) && mysqli_next_result($mysqli));
}
if($mysqli_error=mysqli_error($mysqli)){
echo "<br><br>",key($queries),": ",current($queries),"Syntax Error:<br>$mysqli_error"; // display array pointer key:value
}
//if you want to use the snippet again...
$mysqli_error=null; // clear variables
reset($queries); // reset pointer
Reinvented Wheel "WHILE{}" Syntax (...for those who don't like post-test loops):
while((isset($multi_query) && (next($queries) && mysqli_more_results($mysqli) && mysqli_next_result($mysqli))) || (!isset($multi_query) && $multi_query=mysqli_multi_query($mysqli,implode(';',$queries)))){
echo "<br><br>",key($queries),": ",current($queries); // display array pointer key:value
if($result=mysqli_store_result($mysqli)){
while($rows=mysqli_fetch_assoc($result)){
echo "<br>Col = {$rows["Col"]}";
}
mysqli_free_result($result);
}
echo "<br>Rows = ",mysqli_affected_rows($mysqli); // acts like num_rows on SELECTs
}
if($mysqli_error=mysqli_error($mysqli)){
echo "<br><br>",key($queries),": ",current($queries),"Syntax Error:<br>$mysqli_error"; // display array pointer key:value
}
//if you want to use the snippet again...
$multi_query=$mysqli_error=null; // clear variables
reset($queries); // reset pointer
So, either snippet given the following queries will offer the same output:
Query array:
$queries[]="SELECT * FROM `TEST`";
$queries[]="INSERT INTO `TEST` (Col) VALUES ('string1'),('string2')";
$queries[]="SELECT * FROM `TEST`";
$queries[]="DELETE FROM `TEST` WHERE Col LIKE 'string%'";
Output:
0: SELECT * FROM `TEST`
Rows = 0
1: INSERT INTO `TEST` (Col) VALUES ('string1'),('string2')
Rows = 2
2: SELECT * FROM `TEST`
Col = string1
Col = string2
Rows = 2
3: DELETE FROM `TEST` WHERE Col LIKE 'string%'
Rows = 2
Modify my snippets per your needs. Leave a comment if you discover a bug.
The reason why you get this warning, is simply because you use a do...while loop that evaluates the condition after running the command block. So when there are no more results, the contents of the loop are ran one additional time, yielding that warning.
Using a while ($mysql->next_result())...do loop should fix this. (On a general note: Using post-test loops like you did is quite uncommon in database programming)
If code is poetry, I am trying to be Shakespeare!
(Posted answer on behalf of OP).
Solved:
$querystring = "INSERT INTO responses VALUES('1', '2', '3', '4'); INSERT INTO responses VALUES('1', '2', '3', '4')";
if (mysqli_multi_query($db, $querystring)) {
do {
if (!mysqli_more_results($db)) {
exit();
}
} while (mysqli_next_result($db));
}
echo "end";
Related
I am using PDO to execute a query for which I am expecting ~500K results. This is my query:
SELECT Email FROM mytable WHERE flag = 1
When I run the query in Microsoft SQL Server management Studio I consistently get 544838 results. I wanted to write a small script in PHP that would fetch these results for me. My original implementation used fetchAll(), but this was exhausting the memory available to php, so I decided to fetch the results one at a time like so:
$q = <<<QUERY
SELECT Email FROM mytable WHERE flag = 1
QUERY;
$stmt = $conn->prepare($q);
$stmt->execute();
$c = 0;
while ($email = $stmt->fetch()[0]) {
echo $email." $c\n";
$c++;
}
but each time I run the query, I get a different number of results! Typical results are:
445664
445836
445979
The number of results seems to be short 100K +/- 200 ish. Any help would be greatly appreciated.
fetch() method fetches one row at a time from current result set. $stmt->fetch()[0] is the first column of the current row.
Your sql query has no ordering and can have some null or empty values (probably).
Since you are controlling this column value in while loop, if the current row's first value is null, it will exit from the loop.
Therefore, you should control only fetch(), not fetch()[0] or something like that.
Also, inside the while loop, use sqlsrv_get_field() to access the columns by index.
$c = 0;
while ($stmt->fetch()) { // You may want to control errors
$email = sqlsrv_get_field($stmt, 0); // get first column value
// $email can be false on errors
echo $email . " $c\n";
$c++;
}
sqlsrv_fetch
I'm wrapping up my website, but I've an issue with breaking
if statement inside foreach statement,
I want when a student try to pick a job that he/she already had chosen, the if() fail and break from the WHOLE foreach() loop, this is my code,the break inside the if() only break out the if(), not the whole foreach
please please help me.
thank you
foreach($_POST['JobId'] AS $i){
$sqlCheckingBeofrAdding ="SELECT * FROM JobsLists WHERE JobId = '".$i."' AND SSU = '".$SSU."' ";
$rs = mysqli_query($dbCIE ,$sqlCheckingBeofrAdding);
$row1 = mysqli_fetch_assoc($rs);
if($row1 > 0){
echo "You Already Have this Job In your List";
break;
}
//insert into junction table..
$sqlUpdate = "UPDATE Jobs SET NoStudent=NoStudent-1 WHERE JobId = '" . $i . "'";
$resultUpdate = mysqli_query($dbCIE,$sqlUpdate) or die(mysqli_error($dbCIE));
$sqlInsert ="INSERT INTO JobsLists(`JobID` , `SSU`) VALUES(".$i.",'".$SSU."' )";
$MyQuery= mysqli_query($dbCIE, $sqlInsert) or die(mysqli_error($dbCIE));
}
If your query is only return the single student record than you can use return and this will not execute the further code inside the loop.
If your query returns multiple students record than you can use continue
For point 1:
if($row1 > 0){
echo "You Already Have this Job In your List";
return;
}
For point 2:
if(condition){
echo "You Already Have this Job In your List";
continue;
}
You can use break; OR return; (if this is a function.) Let me know if you need code.
The break statement in PHP accepts a numeric argument.
Try changing your break; to break 2; or use a return;
The php manual says:
break ends execution of the current for, foreach, while, do-while or switch structure.
I do not think your break is breaking out of the if. I suspect a different problem with your code.
Break does not break ifs. This is how the language works.
Ensure you have a debug line before and after the if instead of simple MySQL operations. This seems to be a problem with the code.
For example, add some echo lines before and after the if and you'll have a better idea on what's going on.
The code itself seems to have a lot of problems:
1-You don't need to retrieve all fields (select *) in order to see if at least one entry exists. This is a misuse of the database layer.
2-In case you need to check if one entry exists, add LIMIT 1 to your SQL query. This will avoid MySQL to scan the entire table in case the query is not using any unique key, which is very likely.
3-mysqli_fetch_assoc returns an associative array, but then you compare the array against "> 0". Would you confirm that Array() > 0 ?
4-You seem to be using camelCased variables, but then all of the sudden you have $MyQuery, when it should be $myQuery to match the convention you're using.
5-You're storing the result of the query, in a variable named $MyQuery. This is a bad practice, as the variable name should describe what it contains. Therefore you'll want to call it $myResult or $rs as you did in the first query.
6-None of the variables used in the SQL statements are escaped.
Double check your code using the rubber duck technique and I'm sure you'll find the issue is not related to the if/break; but to something else. Not to offend, but this code seems very immature.
I have created a query that loops through a group of table ID's to get a sum of their combined values. with error handling i get a "Table 'asterisk.custom_' doesn't exist" error and the query is killed obviously. but if i remove the error handling then i get an "mysql_fetch_array() expects parameter 1 to be resource" and the query completes as it should.
Thank in advance for your help.
include("currentday.php");
//---used for testing passing variables
//echo $customID[0];
//echo "<br>".$numrows;
$i = 0;
while($i<=$numrows)
{
mysql_select_db("asterisk") or die(mysql_error()); //This line determines the database to use
$query = "SELECT
vicidial_users.user,
vicidial_users.full_name,
sum(vicidial_agent_log.pause_sec) as sumPause,
sum(custom_$customID[$i].d_amt) as sumDamnt,
sum(custom_$customID[$i].up_amt) as sumUpamnt,
sum(custom_$customID[$i].md_amt) as sumMdamnt,
sum(custom_$customID[$i].s_amount) as sumSamnt,
sum(vicidial_agent_log.dispo_sec)
FROM
vicidial_agent_log
INNER JOIN
vicidial_users
ON
(vicidial_agent_log.user = vicidial_users.user)
INNER JOIN
custom_$customID[$i]
ON
(vicidial_agent_log.lead_id = custom_$customID[$i].lead_id)
WHERE
vicidial_users.user = 'tcx'
GROUP BY
vicidial_users.full_name
ORDER BY
vicidial_agent_log.event_time DESC
";
$queryResult = mysql_query($query);// or die(mysql_error());
while ($rowResult = mysql_fetch_array($queryResult))
{
$pauseResult[] = $rowResult["sumPause"];
$sumdamntResult[] = $rowResult["sumDamnt"];
$sumupamntResult[] = $rowResult["sumUpamnt"];
$summdamntResult[] = $rowResult["sumMdamnt"];
$sumsamntResult[] = $rowResult["sumSamnt"];
}
//print_r($pauseResult);
//echo $pauseResult[0];
$i++;
}
Update:
The table exist in the database:
custom_2346579543413
custom_5466546513564
they are created by the dialer software and im calling them from another query that provides me the numeric part of the table name so this query loops through the values in customID array to make the query, Thanks again
Update:
Sammitch, thank you for the suggestion, however they did not work.
Solution:
Thanks Marc, you confirmed a suspicion i had in that it was looping correctly but for some reason it was looping more times that there we keys. so i echoed $i to confirm and in fact it was it was outputting 0,1,2,3 and since i know there is only 3 keys the last one didn't return anything and so error handling caught it and killed the entire loop and why it appeared correct when error handling was turned off. The solution was actually rather simple and it was in the while loop evaluation string i had used
while($i<=$numrows)
while($i<$numrows)//this worked, the equals part of that gave it an extra loop
and the query completes as it should.
No, it doesn't. "mysql_fetch_array() expects parameter 1 to be resource" means "the query failed, and you didn't bother to check before calling mysql_fetch_array()".
Your problem is that variable expansion inside of a string doesn't like array indexes. You need to change:
"sum(custom_$customID[$i].d_amt) as sumDamnt,"
To:
"sum(custom_{$customID[$i]}.d_amt) as sumDamnt,"
Or:
"sum(custom_" . $customID[$i] . ".d_amt) as sumDamnt,"
For it to work properly.
Why won't this query work?!?
Error
Parse error: syntax error, unexpected T_STRING in E:\xampp\htdocs\pf\shop\buy.php on line 5
Example Info For Variables
$character->islots = 20
$chatacter->name = [RE] Tizzle
$e2 = 10
The Function
function increaseSlots($e2) {
$slots = ($character->islots)+($e2);
mysql_query('UPDATE `phaos_characters` SET `inventory_slots`="'.$slots.'" WHERE `name`="'.$character->name.'"'); // <-- Line 5
if (mysql_affected_rows() != 0) {
echo 'Inventory Size Incresed By '.$e2.' Slots';
}else{
echo mysql_error();
}
}
Look at the docs: http://php.net/manual/en/function.mysql-num-rows.php
Retrieves the number of rows from a result set. This command is only valid for statements like SELECT or SHOW that return an actual result set. To retrieve the number of rows affected by a INSERT, UPDATE, REPLACE or DELETE query, use mysql_affected_rows().
You need to use mysql_affected_rows() or better yet, PDO or mysqli.
$slots = ($character->islots)+($e2);
Looks like there is a typo. Try:
$slots = ($character->slots)+($e2);
First off you should know that mysql_num_rows only returns a valid result for SELECT or SHOW statements, as stated in the PHP documentation. You can use mysql_affected_rows() for your particular needs.
However, the old PHP MySQL API (that you are using) is being phased out, so I would recommend using mysqli or PDO for your DB connection needs.
While keeping with your requirements, though, you can try to use the following syntax to make sure you receive the MySQL error if it throws one. Your PHP script will stop, but you will see the error.
$query = sprintf('UPDATE `phaos_characters` SET `inventory_slots`=%d WHERE `name`="%s"',$slots,$character->name)
$result = mysql_query($query) or die(mysql_error());
As a final idea, in situations like this it helps to print out your resulting $query and run it manually through something like phpMyAdmin to see what happens.
Bleh... I Found a better way to do it for the time being.. sorry to waste your guys' time...
I just threw the $character object into a variable before processing the function.
function increaseSlots($e2,$charname,$charslots) {
$slots = $charslots+$e2;
mysql_query('UPDATE `phaos_characters` SET `inventory_slots`="'.$slots.'" WHERE `name`="'.$charname.'"');
if (mysql_affected_rows() != 0) {
echo 'Inventory Size Incresed By '.$e2.' Slots';
}
}
I am trying to get the number of rows affected in a simple mysql update query. However, when I run this code below, PHP's mysql_affected_rows() always equals 0. No matter if foo=1 already (in which case the function should correctly return 0, since no rows were changed), or if foo currently equals some other integer (in which case the function should return 1).
$updateQuery = "UPDATE myTable SET foo=1 WHERE bar=2";
mysql_query($updateQuery);
if (mysql_affected_rows() > 0) {
echo "affected!";
}
else {
echo "not affected"; // always prints not affected
}
The UPDATE statement itself works. The INT gets changed in my database. I have also double-checked that the database connection isn't being closed beforehand or anything funky. Keep in mind, mysql_affected_rows doesn't necessarily require you to pass a connection link identifier, though I've tried that too.
Details on the function: mysql_affected_rows
Any ideas?
Newer versions of MySQL are clever enough to see if modification is done or not. Lets say you fired up an UPDATE Statement:
UPDATE tb_Employee_Stats SET lazy = 1 WHERE ep_id = 1234
Lets say if the Column's Value is already 1; then no update process occurs thus mysql_affected_rows() will return 0; else if Column lazy had some other value rather than 1, then 1 is returned. There is no other possibilities except for human errors.
The following notes will be helpful for you,
mysql_affected_rows() returns
+0: a row wasn't updated or inserted (likely because the row already existed,
but no field values were actually changed during the UPDATE).
+1: a row was inserted
+2: a row was updated
-1: in case of error.
mysqli affected rows developer notes
Have you tried using the MySQL function ROW_COUNT directly?
mysql_query('UPDATE myTable SET foo = 1 WHERE bar = 2');
if(mysql_result(mysql_query('SELECT ROW_COUNT()'), 0, 0)) {
print "updated";
}
else {
print "no updates made";
}
More information on the use of ROW_COUNT and the other MySQL information functions is at: http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_row-count
mysqli_affected_rows requires you to pass the reference to your database connection as the only parameter, instead of the reference to your mysqli query. eg.
$dbref=mysqli_connect("dbserver","dbusername","dbpassword","dbname");
$updateQuery = mysqli_query($dbref,"UPDATE myTable SET foo=1 WHERE bar=2");
echo mysqli_affected_rows($dbref);
NOT
echo mysqli_affected_rows($updateQuery);
Try connecting like this:
$connection = mysql_connect(...,...,...);
and then call like this
if(mysql_affected_rows($connection) > 0)
echo "affected";
} else { ...
I think you need to try something else in update then foo=1. Put something totaly different then you wil see is it updating or not without if loop. then if it does, your if loop should work.
You work this?
$timestamp=mktime();
$updateQuery = "UPDATE myTable SET foo=1, timestamp={$timestamp} WHERE bar=2";
mysql_query($updateQuery);
$updateQuery = "SELECT COUNT(*) FROM myTable WHERE timestamp={$timestamp}";
$res=mysql_query($updateQuery);
$row=mysql_fetch_row($res);
if ($row[0]>0) {
echo "affected!";
}
else {
echo "not affected";
}
This is because mySql is checking whether the field made any change or not,
To over come this, I created a new TINY field 'DIDUPDATE' in the table.
added this to your query 'DIDUPDATE=DIDUPDATE*-1'
it looks like.
$updateQuery = "UPDATE myTable SET foo=1, DIDUPDATE=DIDUPDATE*-1 WHERE bar=2";
mysql_query($updateQuery);
if (mysql_affected_rows() > 0)
{
echo "affected!";
}
else
{
echo "not affected";
}
it works fine!!!
Was My Tought !
I was just about to tell to check if the function's being called many times !
Just a little advice:
try using isset() & POST / GET or something like that;
if ( isset( $_POST['Update'] == 'yes' ) ) :
// your code goes here ...
endif;
Hope it was clear and useful, Ciao :)