Deleting records from MySQL inside foreach loop - PHP - 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());

Related

Use mysql_insert_id in single query

Ok, don't know if this is simple in practice as it is in theory but I want to know.
I have a single INSERT query were by in that query, i want to extract the AUTO_INCREMENT value then reuse it in the same query.
For example
//values to be inserted in database table
$a_name = $mysqli->real_escape_string($_POST['a_name']);
$details = $mysqli->real_escape_string($_POST['details']);
$display_type = $mysqli->real_escape_string($_POST['display_type']);
$getId = mysqli_insert_id();
//MySqli Insert Query
$insert_row = $mysqli->query("INSERT INTO articles (a_name,details,display_type,date_posted) VALUES('$a_name','$details','$display_type$getId',CURRENT_TIMESTAMP)");
Apparently, am getting a blank value(I know because the mysqli_insert_id() is before the query, but I've tried all i could but nothing has come out as i want. Can some please help me on how to achive this
From my knoweldge this cant be done. Because no query has been run, MySQL is unable to return the ID of said query.
You could use a classic approach, pull the id of the previous record and add 1 to it, this is not a great solution as if a record is deleted, the auto increment value and the last value +1 may differ.
Run multiple queries and then use the insert_id (MySQLi is different to what you are using, you are best using $db->lastInsertId(); as mentioned in the comments.
Run a query before hand and store it as a variable;
SELECT auto_increment FROM INFORMATION_SCHEMA.TABLES WHERE table_name = 'tablename'
I strongly recommend Option 2, it is simply the cleanest and most reliable method for what you are looking to achieve.
It seems the value required for $display_type is :$display_type + (max(id) + 1).
In order to get the max_id you'll have to do this query before :
$sql = "SELECT id FROM articles ORDER BY id DESC LIMIT 1";
$result = mysqli->query($sql);
$maxid = $result->fetch_array(MYSQLI_NUM);
// $maxid[0] will contains the value desired
// Remove the mysqli_insert_id() call - Swap $getid by ($maxid[0] + 1)
// and u're good to go
N.B. update the name of ur primary key in the query $sql.
EDIT :
Assuming the weakness of the query and the quick resarch i did.
Try to replace $sql by (don't forget to Update DatabaseName & TableName values) :
$sql = SELECT `AUTO_INCREMENT`
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'DatabaseName'
AND TABLE_NAME = 'TableName';
That Should do it . More info on the link below :
Stackoverflow : get auto-inc value
I don't think this can be done. You'll have to first insert the row, then update display_type, in two separate queries.
Thanks guys for your opinions, out of final copy, paste, edit and fix; here is the final working code(solution)
`
//values to be inserted in database table
$a_name = $mysqli->real_escape_string($_POST['a_name']);
$details = $mysqli->real_escape_string($_POST['details']);
$display_type = $mysqli->real_escape_string($_POST['display_type']);
//Select AUTO_INCREMENT VALUE
$sql = "SELECT `AUTO_INCREMENT`
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'chisel_bk'
AND TABLE_NAME = 'articles'";
$result = $mysqli->query($sql);
$maxid = $result->fetch_array(MYSQLI_NUM);
$getId = $maxid[0];
//MySqli Insert Query
$insert_row = $mysqli->query("INSERT INTO articles (a_name,details,display_type,date_posted) VALUES('$a_name','$details','$display_type$getId',CURRENT_TIMESTAMP)");
This happens to do the magic!!!
`

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'].",,";
}

mysql nested subqueries with 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

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

Can I make a MySQL var equal to a MySQL command?

If I perform the following MySQL query through PHP:
UPDATE pictures
SET category = '0'
WHERE category = '$categoryID'
AND username = '$username'";
$queryUncat = mysql_query($uncategorise) or die(mysql_error());
It works fine and any category that was equal to $categoryID gets changed to 0. However, if I perform the following:
UPDATE pictures
SET category = '0',
pictureorder = (SELECT COUNT(category) + 1 WHERE category='0' AND username='$username')
WHERE category = '$categoryID'
AND username = '$username'";
$queryUncat = mysql_query($uncategorise) or die(mysql_error());
Not only does pictureorder not equal to the count of the category row plus one, but the category no longer gets changed if equal to $categoryID. I'm not too good at figuring this out as I know only basic MySQL through PHP and am not familiar with it through its own console.
Thanks in advance for any suggestions.
This form of query is not valid. First, your subquery is missing a FROM clause. Second, you cannot select from the same table you are updating in the same query.
http://dev.mysql.com/doc/refman/5.1/en/update.html

Categories