How can i do multiple select statements in one file? For example i have a list of products - i then want to get the stock level's for each of the products. However, it only ever returns the first product, not any other additional products.
$query = $db->query("SELECT * FROM `products` ORDER BY `productName` ASC");
while ($row = $query->fetch(PDO::FETCH_ASSOC)){
$productId = stripslashes($row['productId']);
$productName = stripslashes($row['productName']);
echo "<b>".$productName."</b><br />";
$query = $db->query("SELECT * FROM `stock` WHERE `productId` = $productId");
while ($row = $query->fetch(PDO::FETCH_ASSOC)){
$stockId = stripslashes($row['stockId']);
$stockFilename = stripslashes($row['stockFilename']);
}
echo "Stock level= " . $query-> rowCount();
}
Because your second $query is overwriting the first. Rename the second to $query2 (and change the the $query variables to $query2 beneath it). And change $row to $row2
By the way, you can also change your first query into a join to eliminate the second query alltogether.
Related
Im making a filter where you can select colors and select newest. It would filter them, but the order by doesn't work for some reason.
I tried it this way. It outputs the colors that match the database table, but it doesn't sort them by date.
$color_arr = ["red", "blue", "white"];
foreach($color_arr as $color) {
$data = $conn->query("SELECT * FROM `prod_items` WHERE item_color LIKE '%$color%' ORDER BY `item_date` DESC");
while ($row = $data->fetch()) {
print_r($row);
}
}
You can order by multiple fields, below is the MYSQL query:
SELECT * FROM `prod_items` WHERE item_color LIKE '%$color%' ORDER BY `item_date` DESC, `price` DESC"
This will first sort by item_date and then by price.
Don't run sql query inside loop.
$sql = array('0'); // Stop errors when $color_arr is empty
$color_arr = ["red", "blue", "white"];
foreach($color_arr as $color){
$sql[] = 'item_color LIKE "%'.$color.'%"';
}
$sql1 = implode(" OR ", $sql). " ORDER BY `item_date` DESC";
$sql = "SELECT * FROM `test` WHERE $sql1";
$data = $conn->query($sql);
while ($row = $data->fetch_array()) {
print_r($row);
}
I have an orders table in mysql and in that for some orders I set particular order status like 'review'.
I want to setup a way if any order placed by a particular customer(first and last name) for whom i have previously set order status as 'review' to display a warning in the list.
$sql = "select * from order where firstname = ".$firstname." AND lastname = ".$lastname." AND order_status = 'review';";
$SQLresult = mysql_query("$sql", $DBcon_MySQL);
while($row = mysql_fetch_array($SQLresult)) {
foreach($row as $row){
$result = "warning!";
echo $result;
}
}
The above code does not display anything. please let me know how to fix this.
[EDIT After Applying Answer]
This is how i am using it.
<td width="200">
<?
$sql = "select * from cust_order where firstname = '$firstname' AND lastname = '$lastname' AND order_status = 'review'";
$SQLResult = mysql_query("$sql", $DBcon_MySQL);
while($row = mysql_fetch_array($SQLResult )) {
//$result;
foreach($row as $row ){
//$result="";
$result = "Warning!";
}
?>
<p><? echo $result;?></p>
<?} ?>
</td>
How should i insert a check that it should display warning only once No matter how many orders from single customer are marked as review, display warning only once?
try this,
$sql = "SELECT
*
FROM
`order`
WHERE
firstname = '$firstname' AND lastname = '$lastname' AND
order_status = 'review' LIMIT 1";
$SQLresult = mysql_query($sql, $DBcon_MySQL);
while($row = mysql_fetch_array($SQLresult)) {
foreach($row as $row){
$result = "warning!";
echo $result;
}
}
Please be informed that mysql functions are deprecated and not recommended. USE MySQLi or PDO instead. have a reference from following queries.
http://php.net/manual/en/book.mysqli.php
http://php.net/manual/en/book.pdo.php
i have a query
$result = mysql_query("SELECT * FROM comprofiler WHERE cb_playstationgames LIKE '%FIFA%' ORDER BY id ASC");
in that query there is a user_id wich i need to perform a query on another table.
$gebruikerid = mysql_query("SELECT * FROM users where id LIKE '".$result['user_id']."'");
Now i want to use that value in a while loop
echo "<table><tr><th width=\"300\" align=\"left\" >Avatar</th><th width=\"300\" align=\"left\">Naam</th><th width=\"200\" align=\"left\">PSN Naam</th></tr>";
while($row2 = mysql_fetch_array($result))
{
echo "<tr><td><img height=\"50\" width=\"50\" src=\"/images/comprofiler/" . $row2['avatar'] . "\"></td><td>" . $gebruikernaam . "</td><td>" . $row2['cb_psnnaam'] . "</td></tr>";
}
echo "</table>";
I cannot get the query to read the values from the other table based on the id from the first table. Can someone help me?
In your case the best solution it's to use JOIN.
$result = mysql_query("SELECT comprofiler.*, users.* FROM comprofiler INNER JOIN users ON users.id = comprofiler.user_id WHERE cb_playstationgames LIKE '%FIFA%' ORDER BY comprofiler.id ASC");
You may have to manually specify the columns you want to select (after SELECT ) in case that you have same column names in both table and you need both.
$result = mysql_query("SELECT comprofiler.id as id_comprofiler, users.id as id_user, users.avatar ... " );
To answer your question why it does not work:
Second query does not use mysql_fetch_array.
$gebruikerid = mysql_fetch_array($gebruikerid);
It would be more secure & cleaner if you would use PDO or MySQLi prepared statements like:
$db = new \PDO(SEE PDO CUNSTRUCT)
$query1 = $db->prepare('
SELECT *
FROM comprofiler
WHERE cb_playstationgames LIKE :fifa
ORDER BY id ASC
');
$query2 = $db->prepare('
SELECT * FROM users where id LIKE :id
');
$query1->bindValue(':fifa', '%FIFA%', PDO::PARAM_STR);
$query1->execute();
while ($row = $query1->fetch(PDO::FETCH_ASSOC)) {
$query2->bindParam(':id', $row['user_id'], PDO::PARAM_INT);
$query2->execute();
//Holds associative array of second query
$row2 = $query->fetch(PDO::FETCH_ASSOC);
//$row1 holds associative array of first query
}
I am trying to run 2 database querys the second using an array from the first, any one have any ideas why this stops the page from loading?
$query = $this->db->query("SELECT category_id FROM listings WHERE listing_id = '1' LIMIT 1");
foreach ($query->result() as $row)
{
$query2 = $this->db->query("SELECT listing_title FROM listings WHERE listing_type = '".$row->category_id."' ORDER BY RAND() LIMIT 2");
foreach ($query2->result() as $row)
{
echo $row->listing_title;
}
}
You are overwriting the outer $row in your inner loop
$query = $this->db->query("SELECT category_id FROM listings WHERE listing_id = '1' LIMIT 1");
foreach ($query->result() as $row)
{
$query2 = $this->db->query("SELECT listing_title FROM listings WHERE listing_type = '".$row->category_id."' ORDER BY RAND() LIMIT 2");
foreach ($query2->result() as $row2) // <--- $row2 not $row
{
echo $row2->listing_title;
}
}
Try this:
(Take advantage of prepare statements, the prepare() function, etc)
$query = "SELECT category_id FROM listings WHERE listing_id = '1' LIMIT 1;";
$query2 = "SELECT listing_title FROM listings WHERE listing_type = :categoryId ORDER BY RAND() LIMIT 2;";
$db = $this->db;
$statement = $db->prepare($query);
$statement->execute();
$statement->setFetchMode(PDO::FETCH_ASSOC);
while($row = $statement->fetch())
{
$categoryId = $row['category_id'];
$statement2 = $db->prepare($query2);
$statement2->execute(array(':categoryId' => $categoryId));
$statement2->setFetchMode(PDO::FETCH_ASSOC);
while($row2 = $statement2->fetch())
{
$listingTitle = $row2['listing_title'];
echo $listingTitle;
}
}
This is not very good code. Why use a foreach loop when the Select query has Limit 1?
Since you are going for a category id where listing_id=1 (with LIMIT 1), your code could just be shortened to:
SELECT listing_title FROM listings WHERE listing_id=1 ORDER BY RAND() LIMIT 2
Also, ORDER BY RAND() is a big resource killer on large tables. I recommend finding a more proper way to order your results.
EDIT: Full code that I would use:
$db=$this->db; //Just so we don't have to keep referencing $this (assuming you are not in a class)
$sql="SELECT listing_title
FROM listings
WHERE listing_id=?
ORDER BY RAND()
LIMIT 2";
$statement=$db->prepare($sql);
$statement->execute(array(1));
while($result=$statement->fetchObject()){
echo $result->listing_title;
}
I have the following code:
$query = mysql_query("SELECT * FROM activity ORDER BY activity_time DESC LIMIT 50");
while($result = mysql_fetch_array($query)) {
extract($result);
if ($activity_type == "discussion") {
$query = mysql_query("SELECT * FROM discussions WHERE discussion_uuid = '$activity_ref'");
while($result = mysql_fetch_array($query)) {
extract($result);
echo $discussion_user . " said:<br>" . $discussion_text . "<br>";
}
} elseif ($activity_type == "file") {
}
}
But it just returns the last row. My goal is to have a chronological list of "activities" each displayed slightly differently depending on their type.
Your using $query and $result twice so the second loop is overwriting the result of the first and stopping...
$query = mysql_query("SELECT * FROM activity ORDER BY activity_time DESC LIMIT 50");
and
$query = mysql_query("SELECT * FROM discussions WHERE discussion_uuid = '$activity_ref'");
same with $results var...
I would suggest you change to $query and $query2 but best to use something like
$activies = mysql_query("SELECT * FROM activity ORDER BY activity_time DESC LIMIT 50");
while($activity = mysql_fetch_array($activies)) {
and
$discussions = mysql_query("SELECT * FROM discussions WHERE discussion_uuid = '$activity_ref'");
while($discussion = mysql_fetch_array($discussions)) {
I would also avoid using extract - as you might be overwriting vars your not expecting to...
You have to create another connection to the database so that you can run them at the same time.
OR
You can load the results of the first one into an array, and then just loop through the array.