Trying to use a string of coma separated values compiled from a mysql query within an in_array() statement. The problem is that the statement fails because the output of $array does not work in the in_array() function even though the pasted output of array does work...
$quiz = mysql_query("SELECT id FROM quiz WHERE quiz_page = '2'");
$array1=array();
while($quiz2 = mysql_fetch_assoc($quiz))
{
$array1[]=$quiz2["id"];
}
$array = implode(",", $array1);
echo $array;
echo '<br>';
if (in_array(184, array($array))) {
echo '184 in $array';
} else {
echo '184 not in $array';
}
echo '<br>';
if (in_array(184, array(77,82,85,90,180,181,182,183,184,185))) {
echo '184 in array';
} else {
echo '184 not in array';
}
The result of the code above:
77,82,85,90,180,181,182,183,184,185
184 not in $array
184 in array
You need to be checking if (in_array(184, $array1)) {... instead. $array1 already contains each of numbers in a separate elements, like you have in your second if condition, e.g.
array(77,82,85,90,180,181,182,183,184,185)
When you do array($array) You get an array with one element, the entire imploded string, e.g
array("77,82,85,90,180,181,182,183,184,185")
I'm not sure exactly what you're doing with this, but it looks like you might be able to eliminate the whole in_array problem by just including the 184 in your query
SELECT id FROM quiz WHERE quiz_page = '2' AND id = 184
And checking whether or not the query returns anything.
Related
I queried a table into an array but I would like to exclude certain values from one of the columns as to spits out each row. For example.
foreach($results as $row)
{
if($row['sku'] != "sku-1"){
echo $row['sku']." ";
}
}
So lets say the table has 4 rows with a value of sku-1, sku-2, sku-3 and sku-4. The above Foreach code would echo out "sku-2 sku-3 sku-4". Is there a way I can make an array of what values I would want to exclude? Like I'd have an array called $skuarray = "sku-2, sku-4" and instead of
if($row['sku'] != "sku-2" || $row['sku'] != "sku-4"){
have that $skuarray in there where it'll echo "sku-1, sku-3"? Thanks!
EDIT
I could somehow exclude it when I query it. I'm querying it from table SKUTABLE and the column is SKU. The problem is I need to exclude unique values from column SKU so I thought if there was an easy way to just throw in all the ones I want to exclude into an array that'd be great.
You could use the array_diff(array1, array2, [...arrayN]) function, which takes at least two arrays, and returns an array of only those values of array1 which are not in any of the subsequent arrays. Example:
$input = array(0=>'sku-1',1=>'sku-2',2=>'sku-3',3=>'sku-4');
$exclude = array('sku-1','sku-3','sku-4');
$result = array_diff($input, $exclude);
print_r($result);
Will print
array(1=>'sku-2');
Use in_array:
$skuarray = array("sku-2", "sku-4");
foreach($results as $row)
{
if(!in_array($row['sku'], $skuarray)){
echo $row['sku']." ";
}
}
You can use array_filter in combination with in_array.
$filtered_results = array_filter($results, function ($row) {
return in_array($row["sku"], $skuarray) === false;
});
I'm trying to show the max value of column teams from mysql. Above the while loop I've selected teams from my mysql table and then as you can see in my code below I have included max($teams) - but it is returning an error? Where am I going wrong.
while ($rows = mysql_fetch_assoc($result)) {
$teams = $rows['teams'];
if($teams > "1") {
echo '<div class="bestbettor">'.'<span class="redtext">'."Bettor: ".'</span>'. $rows['username'].'</div>';
echo '<div class="bestbettor">'.'<span class="redtext">'." Bet: ".'</span>'.max($teams). " team accumulator".'</span>'.'</div>';
}
}
you must pass an array to max().
$teams = $rows['teams']; // saves as string.
if your teams were delimited by a comma then you could do something like:
$teams = explode(",",$rows['teams']); // saves as array
then you could do max()
If one parameter is given to max() it has to be an array of values of which max() will return the highest value in that array. It seems like you've just given it a single string.
I'm experimenting with MySQLi and using the following code to check differences for how I should approach my array formatting/usage for fetch_array(MYSQLI_ASSOC);
here is my code:
include "Database.php";
$ArrayQuery = $mysqli->query("SELECT * FROM accountinformation");
while ($ArrayResults = $ArrayQuery->fetch_array(MYSQLI_ASSOC))
{
echo count($ArrayResults);
echo "<br>";
}
echo "<br><br><bR><br>";
$Empty = array();
while ($ArrayResult = $ArrayQuery->fetch_array(MYSQLI_ASSOC))
{
foreach ($ArrayResult AS $ArrayRes)
{
$Empty[] = $ArrayRes;
}
}
print_r($Empty);
The problem is, that i'm using the same Variable for my while loop, the first one returns 3 then 3 Which is expected.
But the problem is, with my second query; it returns a blank array
array( ) when print_r();
and when I do:
while ($ArrayResult = $ArrayQuery->fetch_array(MYSQLI_ASSOC))
{
print_r($ArrayResult);
}
For my Second while loop, it returns nothing for output.
I have checked my variables $ArrayResults and $ArrayResult are not duplicates, they are in fact unique.
Why is my second while loop returning nothing when my first one is working?
Update
When I produce a second query into the mixture with a different starting variable:
$ArrayQuer = $mysqli->query("SELECT * FROM accountinformation");
and modify my second while loop:
while ($ArrayResult = $ArrayQuer->fetch_array(MYSQLI_ASSOC))
{
print_r($ArrayResult);
}
I get the expected output? So is it a case of MySQLi not allowing the same parameters to be used twice throughout the script?
mysqli_data_seek
Adjusts the result pointer to an arbitrary row in the
result
while ($ArrayResults = $ArrayQuery->fetch_array(MYSQLI_ASSOC))
{
echo count($ArrayResults);
echo "<br>";
}
echo "<br><br><bR><br>";
mysqli_data_seek($ArrayQuery,0); // Addition Made Here
$Empty = array();
while ($ArrayResult = $ArrayQuery->fetch_array(MYSQLI_ASSOC))
{
foreach ($ArrayResult AS $ArrayRes)
{
$Empty[] = $ArrayRes;
}
}
print_r($Empty);
To re-use an already fetched array; you should use mysqli_data_seek(); (Notice I have added it above your `$Empty Variable) This should be the problem.
See the manual here:
http://us.php.net/manual/en/mysqli-result.data-seek.php
Think of this scenario; Why would you re-buy something you already own?
Fits perfectly in your case
Yesterday another user helped out with building a generic function for handling MySQL Queries. It looks like this:
function fetchAll($query) {
$res = mysql_query($query) or trigger_error("db: ".mysql_error()." in ".$query);
$a = array();
if ($res) {
while($row = mysql_fetch_assoc($res)) {
$a[]=$row;
}
}
return $a;
}
And to output the returned results I simply do the following:
$data = fetchAll("SELECT * FROM news_table ORDER BY id LIMIT 10");
foreach ($data as $row) {
echo $row['title'];
}
My question relates to outputting the result when there's only one result in the array. Like when displaying the current blog post of a page. I want to know if I can do it without first calling the foreach loop? Is there a way to output just the first result from the array as I do not need to loop through it.
Perhaps I could have an alternate function, as opposed to the fetchAll() one above? One that just outputs one row?
Cheers,
Scott
Yes. For example:
echo $data[0]['title'];
Basically your $data is a two-dimensional array, with the first dimension being the row number (count starts with 0), so you can access any of the rows directly if you know its number. If you only have one row, it's necessarily 0.
Just count the array
if(count($data) == 1) {
// Only one dataset
} else if(count($data) > 0) {
// foreach
} else {
// no content
}
echo $data[0]['title'];
Should print exactly what your looking for. In 2D arrays the first dimension is the array index and as array index start at 0, the above code will echo the first row in that array.
The code below doesn't seem to work or find anything on an array. I'm using "in_array" to search for the needle in the stack. I also tried exploding the contents with comma separated and won't work. Any suggestions? Also I tried "array_search".
$q4 = "SELECT domain_name,slots_config.bid FROM slots_pid,slots_config,slots_sites
WHERE slots_config.bid=slots_pid.bid && slots_sites.aid=slots_pid.aid";
$result4 = mysql_query($q4);
while($row = mysql_fetch_array($result4))
{
$resultarray[] = $row;
}
if (in_array("test",$resultarray))
{
echo "Match found";
}
else
{
echo "Match not found";
}
It looks like what you have here is an 'array of arrays'. That is, in your while() loop, $row is an array which corresponds to the data from your mysql query. So each element of $resultarray actually contains an array, rather than a string.
Try doing this: print_r($resultarray). This will display the entire structure of $resultarray, and you can see how you're creating an array-of-arrays.
To use in_array, you woul need to do something akin to in_array("test", $resultarray[0])
in_array() won't work with that sort of array, because it's multi-dimensional.
Your array looks like this:
$resultarray[0]['domain_name'] = 'first row domain name';
$resultarray[0]['bid'] = 'first row bid';
$resultarray[1]['domain_name'] = 'second row domain name';
...
You can't use in_array() to search in that, so you'll have to do it with another method, something like looping over the array, or building $resultarray differently.
Similarly, array_search() doesn't work on multidimensional arrays, so you could do something like looping over the first dimension and array_search()-ing each second dimension.
Let me know if you want more detail.
$q4 = "SELECT domain_name,slots_config.bid FROM slots_pid,slots_config,slots_sites
WHERE slots_config.bid=slots_pid.bid && slots_sites.aid=slots_pid.aid";
$result4 = mysql_query($q4);
while($row = mysql_fetch_array($result4))
{
if (in_array("test",$row))
{
echo "Match found";
}
else
{
echo "Match not found";
}
}
I believe the problem you are having is that it in_array only searches the first dimension of your two dimensional array. I also don't understand why you're loading the whole result into an array before you search (but perhaps that's useful elsewhere in your program).
Try:
$found = false;
while($row = mysql_fetch_array($result4))
{
if (in_array($needle, $row){
print "here it is";
$found = true;
break;
}
if (!$found) {
print "not found";
}