mysql nested subqueries with php - php

I have two tables. I want to be able to get the orders of each id in the credit table from the orders table code below:
$downlinequery = "SELECT recid, Level, sp1 FROM credit
WHERE sp1 = '$id' or sp2 = '$id' or sp3 = '$id' or sp4 = '$id'
or sp5 = '$id' or sp6 = '$id' or sp7 = '$id' or sp8 = '$id'" ;
$downlineresult = mysql_query($downlinequery) ;
while ($downlinerow = mysql_fetch_array($downlineresult)) {
extract($downlinerow) ;
$orderquery = "SELECT date,cc,cop FROM order WHERE userid='1127'" ;
$orderresult = mysql_query($orderquery) or die("unable to get orders");
while($orderrow = mysql_fetch_array($orderresult)){
extract($orderrow);
echo "$date,$cc,$cop" ;
}
}
but i keep getting the error: unable to get orders
Is it possible to make queries while another is running ?

The error might happend because "ORDER" is a reserved word in MySQL. You should escape it with backticks:
$orderquery = "SELECT date,cc,cop FROM `order` WHERE userid=1127" ;
Same should be for "date", although that's being tolerated (see further down in the same page I linked)
As for your question, of course you can do queries in a loop (although that's not really the best in terms of performance). But if your tables have a foreing key (I'm guessing 'recid' and 'userid') you can build a JOINed query instead

To your actual question:
I don't think the question is right. The first query is not running. It ran and it filled result in $downlineresult (mysql_query) and then, you are just iterating thru the parts of the result (mysql_fetch_array).
It seems you have error in your MySQL query, so you should use:
echo mysql_error();
See the description of the methods you use:
mysql_query
mysql_fetch_array

Related

Deleting records from MySQL inside foreach loop - PHP

I'm checking a project and I found this code that is suppose to delete records from MySQL, despite this is not the best aproach to achieve this I have to make this works, but for me is fine, that's why I'm here, because I don't see the error or what is wrong with this code, is not displaying errors, warning, nothing I tested the code directly in PHPMyAdmin and it works well, so this is the code...
$get_records = mysql_query('SELECT id_detail FROM my_table WHERE user_id = "'.$user_id.'" AND last_date BETWEEN "'.$date1.'" AND "'.$date2.'"') or die (mysql_error());
$array_details = array();
while ($details = mysql_fetch_array($get_records)) {
$array_details[] = $details['id_detail'];
}
$array_details = array_unique($array_details);
foreach ($array_details as $id_detail) {
$delete_detail = mysql_query("DELETE FROM my_table WHERE user_id = '".$user_id."' AND id_detail = '".$id_detail."'") or die (mysql_error());
}
I got two records in the same table with the same ID detail (this works that way), so If I get the ID correcly with the query inside the foreach loop it should delete all the records with that id_detail and user_id doesn't matter if in the query I say between which dates get those IDs, it deletes only one, and that one is which has the date between that range
I have no idea why is not deleting both, some idea about what I'm missing?
NOTE: As I said before if I do that query directly in PHPMyAdmin it works fine and if I do from PHP it delete only one.
Does replacing that code with this query work for you?
$delete_detail = mysql_query("DELETE FROM my_table WHERE user_id = '".$user_id."' AND id_detail IN (SELECT id_detail FROM my_table WHERE user_id = '".$user_id."' AND last_date BETWEEN '".$date1."' AND '".$date2."')") or die (mysql_error());

mysql update clause is being ignored

I have a table with a date, ID1, ID2 score1 and score2. I am trying to update one row through php when the user has entered the specific date and id's in an html form. I have validated all the user entries. When I run my query it updates all rows in the table instead of just one. Here is a snippet of my code:
include('connect.php');
$q = mysqli_query($dbc, "SELECT * from Game");
while ($row =mysqli_fetch_array($q, MYSQLI_ASSOC))
{
mysqli_query($dbc, "UPDATE Game SET score1 ='".$points1."', score2='".$points2."'
WHERE '".$date."' = '".$row['Date']."' AND '".$id."' = '".$row['ID1']."' ");
}
mysqli_close($dbc);
Shouldn't your where clause be:
WHERE Date = '".$row['Date']."' AND ID1 = '".$row['ID1']."' ");
instead of
WHERE '".$date."' = '".$row['Date']."' AND '".$id."' = '".$row['ID1']."' ");
In the latter you - probably by accident - use some variables as field names as well, which might cause some unwanted issues. For example in your case it's likely to cause an identity condition in your where clause, which will result that all of your rows will get updated.
The WHERE clause in your update statement references only literals. There are no column references.
For debugging, I suggest you concatenate your SQL into a string, and echo it out.
$sql = "UPDATE Game SET score1 ='".$points1."', score2='".$points2."'
WHERE '".$date."' = '".$row['Date']."' AND '".$id."' = '".$row['ID1']."' ";
echo $sql;
mysqli_query($dbc, $sql);
With the values of these variables set as shown here:
$date = 'fee'
$row['Date'] = 'fi'
$id = 'fo'
$row['ID1'] = 'fum'
The WHERE clause in the generated UPDATE update statement would look like this:
WHERE 'fee' = 'fi' AND 'fo' = 'fum'
MySQL sees the values enclosed in single quotes as string literals. There's nothing wrong with that in terms of SQL (it's valid syntax) but it's much more likely you want the WHERE clause to be more like this:
WHERE fee = 'fi' AND fo = 'fum'
with fee and fo as references to columns.

Can't access row with 'fieldName' using MAX() in PHP MYSQL

I have small PHP script which has
$query = "SELECT MAX(id) FROM `dbs`";
//query run
$row = mysql_fetch_array($result);
$val = $row[0];
Which runs fine, but I want to understand why i can't access the row with the fieldname, like if i have this
$query = "SELECT id FROM `dbs`";
i am able to use the folowing
$val = $row['id'];
but whenever i use this MAX() function, i have to change to
$val = $row[0];
to access the values
I have no clue about this. Any help would be appreciated. Thankss
You need to give it an alias:
<?php
$query = "SELECT MAX(id) AS `id` FROM `dbs`";
//query run
$row = mysql_fetch_array($result);
$val = $row['id'];
Edit:
To explain this it's probably best to show an example of a different query:
SELECT MAX(`id`) AS `maxId`, `id` FROM `dbs`
Using the above it will return as many rows are in the table, with 2 columns - id and maxId (although maxId will be the same in each row due to the nature of the function).
Without giving it an alias MYSQL doesn't know what to call it, so it won't have an associative name given to it when you return the results.
Hope that helps to explain it.
SELECT MAX(id) AS myFieldNameForMaxValue
FROM `dbs`
and then
$row = mysql_fetch_array($result);
$val = $row['myFieldNameForMaxValue'];
If you run this query on mysql commandline you'll see that the field name returned by mysql is MAX(id). Try running on phpmyadmin and you'll see the same. So if you try $row['MAX(id)'] it'll work. When using a mysql function, it gets added to the name, so use an alias, like other said here, and you're good to go: SELECT MAX(id) AS id FROM dbs. Also, never forget to use the ` chars, just in case you have some columns/tables with reserved names, likefrom`.

Incorrect usage of UPDATE and ORDER BY

I have written some code to update certain rows of a table with a decreasing sequence of numbers. To select the correct rows I have to JOIN two tables. The last row in the table needs to have a value of 0, the second last -1 and so on. To achieve this I use ORDER BY DESC. Unfortunately my code brings up the following error:
Incorrect usage of UPDATE and ORDER BY
My reading suggests that I can't use UPDATE, JOIN and ORDER BY together. I've read that maybe subqueries might help? I don't really have any idea how to change my code to do this. Perhaps someone could post a modified version that will work?
while($row = mysql_fetch_array( $result )) {
$products_id = $row['products_id'];
$products_stock_attributes = $row['products_stock_attributes'];
mysql_query("SET #i = 0");
$result2 = mysql_query("UPDATE orders_products op, orders ord
SET op.stock_when_purchased = (#i:=(#i - op.products_quantity))
WHERE op.orders_id = ord.orders_id
AND op.products_id = '$products_id'
AND op.products_stock_attributes = '$products_stock_attributes'
AND op.stock_when_purchased < 0
AND ord.orders_status = 2
ORDER BY orders_products_id DESC")
or die(mysql_error());
}
Just remove your ORDER BY in your UPDATE statement, then put it in your SELECT statement.
sample:
$query = "SELECT ........ ORDER BY ..."
$result = mysql_query($query);
while(....){.... }
UPDATE statement wont accept ORDER BY clause.
You could use a SELECT call to loop through the rows, and include your WHERE and ORDER BY statements there, and then within your while($row = mysql_fetch_assoc($query)){ loop you'd have your UPDATE table SET key = 'value' WHERE id = '{$row['id']}' statement.
Sure, this would require executing mysql_query() a lot, but it'll still run pretty fast, just not at the same speed a single query would.
Why do you need an order by in an update. I think you could just remove it and you update will update everything that respect your where statement.
EDIT: And maybe you could call a stored proc to simplify your code

PHP & MySQL: How can I use "SET #rank=0;" in $query=

In my PHP file, I use this line to pull data from my mySQL database:
$query = "SET #rank=0; SELECT #rank:=#rank +1 as rank, Blah Blah...";
If I check the SELECT statement in phpMyAdmin's SQL window (without $query= ) it works fine.
But, if I use it in PHP, then I get an error. It doesn't like the "SET #rank=0;" bit. Is there a way to use "SET #rank=0;" when it's in "$query=" ? Is there a workaround?
The rest of the code is standard stuff for pulling data from a db:
public function getmyData() {
$mysql = mysql_connect(connection stuff);
$query = "SELECT #rank:=#rank +1 as rank, formatted_school_name, blah blah";
$result = mysql_query($query);
$ret = array();
while ($row = mysql_fetch_object($result)) {
$tmp = new VOmyData1();
$tmp->stuff1 = $row-> stuff1;
$tmp->stuff2 = $row->stuff2;
$ret[] = $tmp;
}
mysql_free_result($result);
return $ret;
}
Update: I'm trying to use Amerb's suggestion of using multi-query. I concatenated the query like so:
$query = "SET #rank = 0";
$query .= "SELECT #rank:=#rank +1 as rank...
I changed the result to:
$result = $mysqli_multi_query($query);
But, it's failing for some reason. I'm on a machine running PHP 5.2. Any suggestions?
This guy here seems to have a way of setting the variable in the same query to zero. I don't have MySQL set on up on this machine to try it, though.
Here's the query he suggests in his blog post:
select #rownum:=#rownum+1 ‘rank’, p.* from player p, (SELECT #rownum:=0) r order by score desc limit 10;
(Is there some homework assignment coming due somewhere having to do with computing ranks? This is the third question I've seen on this in two days.)
Are you checking for duplicate scores?
Try executing it as 2 separate successive queries.
You have to enable the use of multiple queries in one, but i forgot how do do this at the moment. It's a security feature.
Use mysql_multi_query() or rather mysqli_multi_query() instead of mysql_query()

Categories