PHP + convert array for use with IN statement - php

Lets say I want to send an email to the people who like big sized candy.
When I do this:
$query1 = mysql_query("SELECT id_candy FROM `candylist` WHERE
candysize > 100") or die(mysql_error());
$result = mysql_fetch_array( $query1 );
$query2 = mysql_query("SELECT mail FROM `buyers` WHERE
candysizeinterest IN ($result)
") or die(mysql_error());
This query2 is of course the issue.
$result is not in a proper format to be used and then I get the obvious error of:
**Unknown column 'Array' in 'where clause'**
I need help to format the results of the query in a way that it looks like:
($val1, $val2, $val3....and so on)
Then I will be able to use it for an IN statement.
But I just do not know how to do so.

Try
$array = array();
while($result = mysql_fetch_array( $query1 ))
{
$array[] = $result['id_candy'];
}
Then use implode
$in_condition = implode(',', $array);
At last
$query2 = mysql_query("SELECT mail FROM `buyers` WHERE candysizeinterest IN ($in_condition)
NOTE : please switch to PDO or mysqli_*

you have a mistake in your sintax of $query2 you place array instead of actual value
change
$query2 = mysql_query("SELECT mail FROM `buyers` WHERE candysizeinterest IN ($result)
to
$query2 = mysql_query("SELECT `mail` FROM `buyers` WHERE `candysizeinterest` IN ('".$result['id_candy']."')");
I would like to also to remember you that mysql_ functions are deprecated so i would advise you to switch to mysqli or PDO for new projects.

You can use implode() to turn your array into a comma separated string:
implode(',',$result);
You can use that with IN

To convery an array to a comma sepearted string you would use
implode (",",$array)

Related

How to use an array to query

Is there any way I can use the array from $query and use it in another query like the $query2 below? It works but it only returns the first data of the array...
Already tried these links already but none of them worked in my case
Array in SQL Query?
How to query a database with an array? WHERE = 'array()'
$query = mysqli_query($db, "SELECT * FROM patient_details WHERE discharged_date >= '2019-03-01' AND discharged_date < '2019-03-30'");
while ($row = mysqli_fetch_array($query)){
$result = $row['hosp_patient_no'];
$query2 = mysqli_query($db, "SELECT deficiencies_id FROM deficiency_patient_details WHERE hosp_patient_no = '$result'");
}
you are using mysqli_fetch_array which will "Fetches a result row as an associative, a numeric array, or both", but your requirement says it otherwise so you should use mysqli_fetch_all which "Fetches all result rows as an associative array, a numeric array, or both".
so your syntax should look like this
$query = mysqli_query($db, "SELECT * FROM patient_details WHERE discharged_date >= '2019-03-01' AND discharged_date < '2019-03-30'");
while ($row = mysqli_fetch_all($query)){
$result = $row['hosp_patient_no'];
$query2 = mysqli_query($db, "SELECT deficiencies_id FROM deficiency_patient_details WHERE hosp_patient_no = '$result'");
}
infact i would suggest you to do this in a single query using subquery.

How to get substring value from database?

How can we get the value from mysql database using this code in php?
code:
$query = "select substring(yr,1,4) from bday where id ='1'";
$sql=mysql_query($query);
$res = mysql_fetch_array($sql);
I tried this code $res['yr'] to know its value but it gives me 'Array'.
How can i get its real value from mysql database?
Mysql_fetch_array will fetch data as an array so you have to use indexes.
Try
echo $res[0]
or use an alias
$query = "select substring(yr,1,4) as yr from bday where id ='1'";
$sql=mysql_query($query);
$res = mysql_fetch_array($sql);
echo $res['yr'];
Dosc link: http://php.net/manual/en/function.mysql-fetch-array.php
Note: Please try to use PDO or Mysqli.
PDO learning Links.
http://www.phpro.org/tutorials/Introduction-to-PHP-PDO.html
http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
http://www.youtube.com/watch?v=o2h-sw9fZq0
Mysqli Learning tutorials:
http://codular.com/php-mysqli
http://www.phphaven.com/article.php?id=65
Give alias to the value substring(yr,1,4) like :
$query = "select substring(yr,1,4) as sb_string from bday where id ='1'";
$sql=mysql_query($query);
$res = mysql_fetch_array($sql);
echo $res['sb_string'];

how can i stop duplicate values from being shown?

Ok, so I Have been trying to figure this out for 2 days with no real success
This is the code I have
$splash_list = '';
$splash_array = array();
$sql = "SELECT * FROM pm WHERE receiver='$username' OR sender='$username'";
$query = mysqli_query($db, $sql);
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
if($username == $row['sender']){
$otuser = array_push($splash_array, $row['receiver']);
$this_user = $row['sender'];
} else {
$otuser = array_push($splash_array, $row['sender']);
$this_user = $row['receiver'];
}
}
foreach($splash_array as $otuser){
$splash_list .= '<div>'.$otuser.'<br></div>';
}
The output is
otuser1
otuser1
otuser1
otuser2
otuser2
If any one can give me a pointer on how i'd go about
only outputting each value once like so
otuser1
otuser2
It'd be greatly appreciated :)
Well you could do SELECT DISTINCT ... (DISTINCT optimization docs)
But there's some other serious concerns with your code...
SELECT * is evil
mysql_* functions are deprecated
Your code is vulnerable to SQL injections
Look into using PHP's PDO for more help.
Your resulting code will look something like
$query = $db->prepare("
SELECT DISTINCT sender, receiver
FROM pm
WHERE receiver = :username
or sender = :username
");
$result = $query->execute(array("username" => $username));
Notice the documentation suggests you should use a colon like this → ":username" => $username. A little known goodie about PDO parameter binding is that the : is optional. Youpi!
I think DISTINCT would not work for this. Because DISTINCT will return unique combinations of sender and reciever, so ('otuser1', 'otuser2') and ('otuser2', 'otuser1') would be different.
Easiest solution:
array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )
http://de2.php.net/manual/en/function.array-unique.php

mysql union and order not working

I am trying to combine all the results as i go through the loop
$result = ....;
$finalresult = 0;
while($row = mysql_fetch_assoc($result))
{
$clubID = $row['clubID'];
$finalresult = mysql_query('"'.$finalresult.'" UNION ALL SELECT * FROM events WHERE clubID = "'.$clubID.'"');
}
However, this isn't working. Is there another way to do this?
This should do the trick:
$clubIDs = array();
while($row = mysql_fetch_assoc($result)) {
$clubIDs[] = $row['clubID'];
}
$finalresult = mysql_query("SELECT * FROM events WHERE clubID IN (" . implode(',', $clubIDs) . ")");
It's generating a list of clubIDs from your previous query, and putting them in an array. Then, it's using that array to generate an IN clause, and retrieving all the data in one go.
A couple of caveats - this will fail if there are no valid club IDs, so you'll want to add some error checking.
Secondly, mysql_* is deprecated in PHP 5.5, so you should look at using mysqli_* or PDO instead - they're both much more secure.

While returning no results

I've got the following query in an existing script - but it's not always returning a value even though it should based off what's in the database. There are plenty of things in the database it SHOULD be grabbing - they are there.
Don't see anything wrong with it - but I barely do this anymore :) See anything?
$query = "SELECT id FROM xtags WHERE tag_id = '$tagid' ORDER BY RAND() Limit 2";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$query = "SELECT * FROM xtable WHERE id = '$row[id]'";
$result = mysql_query($query) or die(mysql_error());
$row2 = mysql_fetch_assoc($result);
echo $row2[title];
}
$result is being used inside the loop and outside, try making a new variable inside and not reusing the outside one.
You're reusing the $result variable inside the loop which overwrites the value for use in the while condition. Use a different name for $query and $result inside the loop.
I don't know if is ok, but you are using $result twice, one before the "while" and another inside the "while".
I would personally split the string and the variable $row.
Why not use var_dump() to see $row and the other variables ???
I don't understand what you are trying to do actually, but try this:
$query = "SELECT id FROM xtags WHERE tag_id = '".$tagid."' ORDER BY RAND() Limit 2";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$query2 = "SELECT * FROM xtable WHERE id = '".intval($row[id])."'";
$result2 = mysql_query($query2) or die(mysql_error());
$row2 = mysql_fetch_assoc($result2);
echo $row2[title];
}
Problem solved - did a join statement.

Categories