Running mysql inside a while loop - php

I have a while loop of a mysql call but I also am trying to run another mysql query inside of the while loop but it is only doing it once. I can not figure it out.
Here is my code:
$sql = "SELECT * FROM widget_layout WHERE module_id=".mysql_real_escape_string($id)." AND state='".mysql_real_escape_string($page)."' AND position=".mysql_real_escape_string($position);
$query = mysql_query($sql);
while ($row = mysql_fetch_assoc($query)) {
$layout .= $row['widget_id'].'<br/>'; //test if it is looping through all rows
$sql2 = "SELECT title FROM widgets WHERE id=".$row['widget_id'];
$query2 = mysql_query($sql2);
$result2 = mysql_fetch_array($query2);
$layout .= $result2[0]; // test the title output
}
It is looping through the first query no problem but the second query is only load the title of the first widget, return null for the rest. Any idea of why this is doing this?

You don't have to use a WHILE loop -- this can be done in a single SQL statement:
SELECT wl.widget_id,
w.title
FROM WIDGET_LAYOUT wl
JOIN WIDGETS w ON w.id = wl.widget_id
WHERE wl.module_id = mysql_real_escape_string($id)
AND wl.state = mysql_real_escape_string($page)
AND wl.position = mysql_real_escape_string($position);
The issue with NULL title values depends on if the WIDGET.title column is NULLable, or there isn't a record in the WIDGETS table for the id value. You need to check the values coming back from the first query, confirm they have supporting records in the WIDGETS table first, then look at the title value...

Directly from the mysql_query() docs: multiple queries are not supported. Your innery query is killing the outer one.

Related

How to store a PHP variable from a SQL table INT camp

This is my table:
All I want to do is to obtain the '75' int value from the 'expquim' column to later addition that number into another (75+25) and do an UPDATE to that camp (now it is 100).
Foremost, there are dozens of ways to accomplish what you want to do. If you're querying the table, iterating over results and doing some conditional checks, the following will work for you. This is pseudo code... Check out the function names and what parameters they require. $db is your mysqli connection string. Obviously replace tablename with the name of your table. The query is designed to only select values that are equal to 75. Modify the query to obtain whatever results you want to update.
This should get you close to where you want to be.
$query = "SELECT * FROM tablename WHERE idus='1'";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_assoc($result)) {
if($row['expquim'] == 75){
$query2 = "UPDATE tablename SET expquim='".$row['expquim']+25."' WHERE idus='".$row['idus']."' LIMIT 1 ";
$result2 = mysqli_query($db,$query2);
}
}

More efficient way to grab MySQL row populated with single value

Right now I'm trying to set a variable from an SQL response without doing it more than necessary.
The situation is I have a SQL result from a SELECT + JOIN query with a user_id column that has only a single value. The other columns are different per row and I need to loop through them for that data. I was wondering if there was a way to extract the homogeneous value from the user_id column without setting it over and over again to a variable in my while loop.
Code:
#where I would like the $user_id to be set
while($responseArray = $response->fetch_assoc()){
$userId = $responseArray["user_id"]; #what I don't want to do
#other fetching stuff
}
SQL:
SELECT users.username, users.user_id, posts.post_id, posts.post_content, posts.number_comments, comments.comment_id, comments.comment_post_id
FROM users
JOIN posts
JOIN comments
WHERE delete_bit = 0 AND username = "john";
You cannot get away from fetching at least one result row. Even the fetchOne()-type functions do this. But if you only want a single row, why even bother using a loop in the first place?
$result = $db->query(...);
$row = $result->fetchRow();
$value = $row['somefield'];
would be far better than something silly like
$result = $db->query(...);
while($row = $result->fetchRow()) {
$value = $row['somefield'];
break;
}

echo updated values instead of old values

How do I echo the latest values in column1? The below code echos the values before the update.
while($line = mysql_fetch_array($result)) {
$Student = $line["calss8"];
$querySf = "SELECT SUM(ABC) AS val1 FROM tbl1 WHERE student = '$Student'";
$resultSf = mysql_query($querySf);
$rSf = mysql_fetch_array($resultSf);
$totalSf = $rSf['val1'];
$totTMonth = $totalSf;
mysql_query("UPDATE tbl4 SET column1 = $totTMonth WHERE student = '$Student' LIMIT 1");
}
echo $line["column1"].",,";
As far as I know, you'll have to make a separate query to see what was just updated. I mean, run your select, perform your update, then do another select. You can get general information like how many rows were updated, but I don't think you can get specific information like the changed values in a column. Phil was right in suggesting that you should just print out the '$totTMonth' value since that is what you are updating your column with. That would be less overhead than doing another query to the database.
I think that problem starts before the code above. This code line will display the select results :echo $line["column1"].",,";. The variable $line is set before the code above. My solution is to do the following:
$result1 = mysql_query("SELECT column1 FROM student ..."); /* I insert the select query here */
While($row= mysql_fetch_array($result)) {
echo $row['column1'].",,";
}

PHP query returns no results

I'm probably missing something obvious but when I try to execute this query, it returns no results. I plugged it directly into MySQL and also tried replacing the variable with a valid row value and I get the correct output. When I use a variable, it gives me no results. Anyone have any thoughs?
$query = "SELECT title FROM le7dm_pf_tasks WHERE project = (SELECT id FROM le7dm_pf_projects WHERE title = '".$ws_title."') ORDER BY title DESC LIMIT 1";
$result_query = mysql_query($query) or die("Error: ".mysql_error());
while ($row = mysql_fetch_assoc($result_query)) {
$result_title = $row['title'];
}
$result_title = substr($result_title,0,6);
echo $result_title;
Your SQL could do with some rework (though not the reason for your issue). No need for the nested select (which can also cause an error if it returns > 1 row). Try a join.
$sql = "
SELECT title FROM le7dm_pf_tasks t
INNER JOIN le7dm_pf_projects p ON t.project = p.id
WHERE p.title = '{$ws_title}'
ORDER BY title DESC LIMIT 1
";
You are also iterating over an unknown number of rows using the while statement. And then you exit and attempt a substring. How do you know that the last row iterated in the while had a value.
Try outputting $result_title inside the while loop itself to confirm data.
echo $result_title;
If you truly only have a single row, there is no need for the while loop. Just do
$row = mysql_fetch_assoc($result_query);
strip_tags($ws_title); - is what did it! The title was wrapped in an anchor tag that linked to that particular project page.
Thanks for all the good suggestions though. I'm gonna use some of them in the future when bug testing.

Updating multiple rows in MySQL

I'm trying to update multiple rows in one table in MySQL database by doing this. And its not working.
$query = "UPDATE cart SET cart_qty='300' WHERE cart_id = '21';
UPDATE cart SET cart_qty='200' WHERE cart_id = '23';
UPDATE cart SET cart_qty='100' WHERE cart_id = '24';";
mysql_query($query,$link);// $link is specified above
Anyone know what is wrong with this.
From the PHP documentation:
mysql_query() sends a unique query (multiple queries are not supported)
The ; separates SQL statements, so you need to separate the queries if you want to continue using the mysql_query function...
mysql_query can't use multiple queries.
The easiest thing is to just run them separately. I believe you can do multi query but I haven't tried it.
$updateArray = array(21=>300,23=>200,24=>100);
foreach($updateArray as $id=>$value)
{
$query = "UPDATE cart SET cart_qty='$value' WHERE cart_id = '$id'";
mysql_query($query,$link);// $link is specified above
}
This will accept a combination of IDs and their corresponding cart value. Looping though, it builds the query and executes it. The array can then come from a variety of sources (results from another query, form inputs or, as in this case, hard-coded values)
Update:
If you really need to execute all in one, heres the PHP info on multi query:
mysqli::multi_query
You can do it this way:
UPDATE table
SET col1 = CASE id
WHEN id1 THEN id1_v1,
WHEN id2 THEN id2_v1
END
col2 = CASE id
WHEN id1 THEN id1_v2,
WHEN id2 THEN id2_v2
END
WHERE id IN (id1, id2)
This example shows updating two different columns in two different rows so you can expand this to more rows and columns by cludging together a query like this. There might be some scaling issues that makes the case statement unsuitable for a very large number of rows.
You'll need to send them as separate queries. Why not add the queries as strings to an array, then iterate through that array sending each query separtely?
Also check this thread for another idea
This isn't the best method.. But if you need to do multiple queries you could use something like...
function multiQuery($sql)
{
$query_arr = explode(';', $sql);
foreach ($query_arr as $query)
{
mysql_query($query);
}
}
another example of a helper query
function build_sql_update($table, $data, $where)
{
$sql = '';
foreach($data as $field => $item)
{
$sql .= "`$table`.`$field` = '".mysql_real_escape_string($item)."',";
}
// remove trailing ,
$sql = rtrim($sql, ',');
return 'UPDATE `' . $table .'` SET '.$sql . ' WHERE ' .$where;
}
echo build_sql_update('cart', array('cart_qty' => 1), 'cart_id=21');

Categories