Trying to delete all rows in database that do not match array - php

I am trying to figure out how to delete all ids in the database that do not exist in an array. I have been trying to use NOT IN in my query but I am not sure why it wont work when running it in a script the same way it works when I manually enter it into mysql. Here is an example.
mysqli_query($con, "DELETE FROM table WHERE id NOT IN ($array)");
$array is a list of ids from a json api. I use CURL to fetch the ids and I am trying to delete all ids in the database that do not match the ids in $array.
First I use another simple CURL script to scrape the apis and insert the ids found into the database and what I am trying to do here is basically make a link/data checker.
If the ids in the database are not found in the array when rechecking them then I want them deleted.
I thought that the query above would work perfect but for some reason it doesn't. When the query is ran from a script the mysql log shows the queries being ran as this.
Example:
DELETE FROM table WHERE id NOT IN ('166')
or this when I am testing multiple values.
DELETE FROM table WHERE id NOT IN ('166', '253', '3324')
And what happens is it deletes every row in the table every time. I don't really understand because if I copy/paste the same query from the log and run it manually myself it works perfect.
I have been trying various ways of capturing the array data such as array_column, array_map, array_search and various functions I have found but the end result is always the same.
For right now, just for testing I am using these 2 bits of code for testing 2 different apis which gives me the same sql query log output as above. The functions used are just a couple random ones that I found.
//$result is the result from CURL using json_decode
function implode_r($g, $p) {
return is_array($p) ?
implode($g, array_map(__FUNCTION__, array_fill(0, count($p), $g), $p)) :
$p;
}
foreach ($result['data'] as $info){
$ids = implode_r(',', $info['id']);
mysqli_query($con, "DELETE FROM table WHERE id NOT IN ($ids)");
}
And
$arrayLength = count($result);
for($i = 0; $i < $arrayLength; $i++) {
mysqli_query($con, "DELETE FROM table WHERE id NOT IN ('".$result[$i]['id']."')");
}
If anyone knows what is going on i'd appretiate the help or any suggestions on how to achieve the same result. I am using php 7 and mysql 5.7 with innodb tables if that helps.

It probably doesn't work because your IN value is something like this
IN('1,2,3,4');
When what you want is this
IN('1','2','3','4')
OR
IN( 1,2,3,4)
To get this with implode include the quotes like this
$in = "'".implode("','", $array)."'";
NOTE whenever directly inputting variables into SQL there is security Implications to consider such as SQLInjection. if the ID's are from a canned source you're probably ok, but I like to sanitize them anyway.

You can't mix array and string.
This works:
mysqli_query($con, "DELETE FROM table WHERE id NOT IN (".implode(',', $ids).")");

Related

How to DELETE multiple rows using values provided with an array PHP | SQL

I've restructuring my code to better fit the application and the one problem I can't seem to wrap my head around is deleting multiple rows with an array I'm providing to the back-end.
The query I'm using is as follows
$items = json_decode(file_get_contents('php://input'))
//the item is passed as an object {"values": ["string1", "string2", "string3"]}
$values = implode(",", $items->values);
$sql = "DELETE FROM products WHERE value IN($values)";
Before the changes this query was used to delete with ids instead of looking up specific values in rows.
$ids = json_decode(file_get_contents('php://input'))
$values= implode(",", $ids->ids);
$sql = "DELETE FROM products WHERE id IN($values)";
This worked without a hitch, but trying to run the new query keeps throwing the error
unknown column in where clause
I've tried multiple different approaches but can't get this to work.
help would be much appreciated.

Is there any solution to run the same query inside foreach with different variable, using PHP?

I'm running the following PHP code bellow. I have a string with seperated data (separated by ";"). I want to split this data into an array and with foreach I want to run the same INSERT sql query, changing with the array actual item only.
After I runned the code the succesfully message appearing. But as I described only one record get into the database (and only one time so if I do the same thing at the second time no more record added, also not the record before what is there in the database already too. (This is why I got so confused.)
String example: "email#email.com;email2#email2.com;"
The PHP code:
$connection = dbconnect();
$mail_addresses = explode(";",$_POST["mailaddresslist"]);
for($i = 0; $i < count($mail_addresses); $i++){
$query = "INSERT INTO `tablename` (`emsd_email`, `emsd_theme`, `emsd_timerdate`) VALUES ('".$mail_addresses[$i]."','". $_POST["themes"]."','".$_POST["emailsenddate"] ."');";
$connection->query($query);
}
print_note("E-mail successfully added!");
There is no any error message the code is running down. In the first time it create one record (just with the first item in the array), but after that the code doesn't make any effect at all. It no matters that how many times I run it does nothing. There's no more record appearing in the database.
I solved it. The problem was the record must have a unique id, and it must be Auto Increment. Now it works fine. :)*

Display MySQL Results in Different Sections of Page

I have a MySQLi query that returns all of the "assets" assigned to an employee based on their EmployeeID. This works great. The problem I'm facing is in the presentation.
I have an HTML table that has two sections: 1 for Hardware and 1 for software. What I am hoping to avoid is having to perform separate lookups that generate separate result sets for each type of asset. The end result needs to display as follows:
I can build the table just fine. The result sets contains a field of asset_type but I've not had any luck figuring out the code to use to iterate through my single result set. Is this even possible? Can I pull just the hardware assets from the result set with a while? Perhaps a
while($result['asset_type'] == "hardware"){
echo ""; // table row code
}
And then repeat the same thing later in my table code for asset_type software?
UPDATE 1
The code I've thought might work so far, but isn't doing anything, is
// SQL query
$q = "SELECT * FROM `assets_table` WHERE `emp_id` = '".$emp_id."'";
$r = mysqli_query($connect, $q);
$total_assets = mysqli_num_rows($r);
while($r){
if($r['category'] = "hardware"){
echo $r['asset_name']." - ".$r['hw_make']." ".$r['hw_model'];
}
}
I ended up going ahead and breaking out the query into multiple result sets and dealing with them that way. It'd be awesome if you could have a while() with a WHERE statement when iterating through result sets / arrays.

Creating an array by looping through a mySQL database, capturing entries only once in PHP

i'm relatively new to coding and I need a little help. I'm basically trying to loop through an entry in a mySQL database and push any new entry into an array , so that it only comes up once in my array.
// SQL query
$response = $bdd->query('SELECT serie_bd FROM inventaire_bd');
//creating array to group all elements from the db so that they do not repeat
$serie_bd_groupe=array();
while($data_collected = $response->fetch())
{
if(array_key_exists($data_collected,$serie_bd_groupe)==false)
{
array_push($data_collected,$serie_bd_groupe);
}
}
Will this work? - it seems like the loop will just stay stuck after it comes accross an entry a second time because the if statement wont execute itself.
Also in the future, are their any php equivalent to jsfiddle.net so i can test code syntaxically?
Thank you for your time
Your array keys will be default integers, so you don't want to check those. Instead of this:
if(array_key_exists($data_collected,$serie_bd_groupe)==false)
you should do this:
if(!(in_array($data_collected,$serie_bd_groupe)))
http://php.net/manual/en/function.in-array.php
On the other hand, if you're expecting your collected data to be the array key rather than value, you'd do something like this, instead of your array_push:
$serie_bd_groupe[$data_collected] = 1;
then your key check would work.
If you are looking for UNIQUE values (serie_bd) from your database, update your query to include "DISTINCT" like this:
$bdd->query('SELECT DISTINCT serie_bd FROM inventaire_bd');
On the other hand, I think you are looking for http://phpfiddle.org/

only retrieving 1 row of data from MYSQL database

I am trying to input multiple pieces of data through a form and all the data will be separated by (,). I plan to use this data to find the corresponding id for further processing through an sql query.
Below is the code I use.
$key_code = explode(",", $keyword);
//$key_count = count($key_code);
$list = "'". implode("','", $key_code) ."'";
//$row_count = '';
$sql4= "SELECT key_id FROM keyword WHERE key_code IN (".$list.")";
if(!$result4 = mysql_query($sql4, $connect)) {
mysql_close($connect);
$error = true;
}else{
//$i = 0;
while($row = mysql_fetch_array($result4)) {
$keyword_id[] = $row['key_id'];
//$i++;
}
//return $keyword_id;
}
The problem i see is that keyword_id[0] is the only element that contains any data (the data is accurate). Even if I input multiple values through the aforementioned form.
I thought it might be an error in the sql but I echo'ed it and it looks like:
SELECT key_id FROM keyword WHERE key_code IN ('WED','WATER','WASTE')
The values in the brackets are exactly what I inputted.
I even tried to figure out how many rows are being returned by the query and it shows only 1. I assume something is wrong with my query but I cannot figure where.
Any help will be greatly appreciated.
Edit: Alright Solved the problem. Thanks to suggestions made I copied and pasted the $sql_query I had echo'ed on the website into mysql console; which resulted in only 1 row being retrieved. After taking a closer look I realized that there was a whitespace between ' and the second word. I believe the problem starts when I input the key_code as:
WED, WATER, WASTE
Instead inputting it as
WED,WATER,WASTE
fixes the problem. I think I should make it so that it works both ways though.
Anyway, thank you for the help.
I am pretty sure that the query is ok. How many rows do you get with just
SELECT key_id FROM keyword
I think that there is just one line that matches your WHERE.
Check the query directly in the database(with phpmyadmin, or in the mysql console), however this query seems to be working as you may assumed. If it returns only 1 row when you use it directly in the db, then maybe there is only one row in your table wich matches this query.

Categories