only retrieving 1 row of data from MYSQL database - php

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.

Related

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

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).")");

Execute 2 mysql Queries with the second being based on the first

Hi I have two tables that I need to insert into.
the issue is that the first table has an ID field that is automatically generated and I need this field in the second query
members (table1):
|id|name|eyeColour|
assignedMembers (table 2):
|id|memberID|groupID|
I am currently using the below:
$addMember = $dbHandle->prepare("INSERT INTO members(name,date) VALUES(?,?)");
$addMember->bind_param("ss",$name,$eyeColour);
$addMember->execute();
$getID = $dbHandle->("SELECT id from members where name = ? LIMIT 1");
$getID->bind_param("s",$name);
$getID->execute();
$getID->bind_param($MID);
$assignMember= $dbHandle->prepare("INSERT INTO assignedMembers memberID,groupID) VALUES(?,4)");
$assignMember->bind_param("i",$MID);
$assignMember->execute();
This fails at the $assignMember->bind_param(); after troubleshooting I noticed that the $MID variable is empty.
it seems as though the row from the first INSERT is not added before the execution of the next statement is there a way to force this?
Thank you for taking the time to read this post, any help would be greatly appreciated
mysqli:$insert_id is what you are looking for.
$addMember = $dbHandle->prepare("INSERT INTO members(name,date) VALUES(?,?)");
$addMember->bind_param("ss",$name,$eyeColour);
$addMember->execute();
$id = $dbHandle->insert_id;
I think you should use
$getID->bind_result($MID);
$getID->fetch();
instead of
$getID->bind_param($MID);
Due to usage of '...->bind_param' I assume, you use MySQLi.
Check out: mysqli_insert_id — Get the ID generated in the last query

Select only rows with certain critiera then output data

So im developing a web page with the following sql query:
$sql=mysql_query("SELECT * FROM `fotf_images` WHERE `image_fotfnum` = '$Fivedigits'");
now, $fivedigits is a $_POST from a previous forms input data. So basically the form parses the mysql db for rows that contain ONLY $Fivedigits in a specific column. What i want to do, is output EVERY row that has these criteria. So far i used the following:
while ($row = mysql_fetch_array($sql, MYSQL_ASSOC)) {
print_r($row);
}
this only seems to output the first row, when i know as a fact there are exactly 2 rows that contain the criteria. Please help! Thanks!
try using
Select * from fotf_images
where Concat(image_fotfnum, '', field2, '', fieldn)
like concat('%','",$Fivedigits,"','%')
since its not only numeric you may need to use LOWER or UPPER case while comparing. This will help you search in every mentioned feilds of fotf_images table

PHP MySQL While loop for SELECT from two tables?

Hi there i am working on PHP code that is selecting columns from two tables.
Here is my code:
$result2 = mysql_query("SELECT *
FROM `videos`, `m_subedvids`
WHERE `videos.approved`='yes' AND
`videos.user_id`='$subedFOR'
ORDER BY `videos.indexer`
DESC LIMIT $newVID");
while($row2 = mysql_fetch_array($result2))
{
$indexer = addslashes($row2['videos.indexer']);
$title_seo = addslashes($row2['videos.title_seo']);
$video_id = addslashes($row2['videos.video_id']);
$title = addslashes($row2['videos.title']);
$number_of_views = addslashes($row2['videos.number_of_views']);
$video_length = addslashes($row2['videos.video_length']);
}
When i try to print $indexer with echo $indexer; it's not giving me any results.
Where is my mistake in this code?
It seems to me like the key 'indexer' isn't in your results. It's hard to tell, since you haven't listed a definition for your table and you're using SELECT * so we can't see the names.
It makes the program easier to read later, if instead of SELECT *..., you use SELECT col1, col2, .... Yes, SELECT * will save you some typing right now, but you'll lose that time later when you or anyone else who works on your code has to check the table definition every time they work with that line of code.
So, try changing your query to explicitly select the columns you use. If it's an invalid column you'll get an error right away rather than this silent failure you're getting now, and you'll thank yourself later as well.
So long as videos.indexer is a unique field name among all tables used in the query you can change
$indexer = addslashes($row2['videos.indexer']);
to
$indexer = addslashes($row2['indexer']);
You don't need to (or can not) use the table name when referring to the result.

php mysql result coming back wrong, every time from php, but is fine in sql pro and phpmyadmin

The following statement is returning a 1 in php. I've serialized and output the result and every other credential, and it is doing this on three seperate queries. When I run the query in sqlpro or phpmyadmin I get the result as 8. Please tell me someone has a bright idea.
$numRFPsSwitch = 0;
$bquery = " SELECT COUNT(rp.id) AS 'NumRFPs'
FROM rfp_proposal rp
WHERE rp.vendor_id = 1 AND rp.id IN(13,15,16,23,24,26,4,9) ";
$bresult = mysql_query($bquery, $connection);
$XMLFormatedString .= 'NumRFPs="';
while ($brow = mysql_fetch_object($bresult)){
$XMLFormatedString .= $brow->NumRFPs;
$numRFPsSwitch = 1;
}
What's returning 1? $numRFPsSwitch which is set to 1? :) $XMLFormatedString should have the correct value, your example works fine for me.
The result will always be a single row. So the loop should be replaced with an if.
Concerning the problem: Did you check your $connection?
Perhaps you could do a SELECT * (to return all rows involved), and then do a mysql_num_rows(...) on the result to find out the row count. If this returns the same result, then at least you can be sure it's not the query or concatenation that's at fault.
$query = "SELECT ...";
echo mysql_num_rows(mysql_query($query, $connection));
Are you sure you use the right login credentials in mysql_connect() and mysql_selectdb()?
Also: If you dó use the right credentials, are you sure you have the right permissions to select/update/delete etc.

Categories