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";
}
Related
What I'm trying to do is to assign variables based upon a sql query.
The field "County" is a varchar containing the names of Counties.
$sql="SELECT County from GAINLP WHERE SpeciesName LIKE '%Actias_luna%'";
($result=mysqli_query($connect,$sql));
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
if (in_array("Porter", $row)) {
$Porter='Present';
}
else {$Porter='Not Present';
};
echo $Porter;
What happens is that in_array is only detecting the very first county in the array. If I echo $row, I get this:
OwenPikeParkeOwenOwenScottMorganGreeneHendricksLawrenceSt.JosephWashingtonVigoMorganOwenDuboisJeffersonSwitzerlandMadisonGreeneFayetteMarionOrangeParkeClarkJeffersonFayetteFountainMontgomeryHendricksHowardOwenElkhartMarionHendricksWashingtonTippecanoePutnamWashingtonBrownHendricksJenningsOwenWhitleyKosciuskoPorterVermillionHendricks
If I assign the needle as "Owen," echo $Porter returns "Present". All other values echo "Not Present." If I loop it, even "Owen" returns "Not Present" to $Porter. What am I doing wrong here?
This also does not work:
$sql="SELECT County from GAINLP WHERE SpeciesName LIKE '%Actias_luna%'";
($result=mysqli_query($connect,$sql));
while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
if (in_array("Porter", $row)) {
$Porter='Found it';
}
else {$Porter='Didn\'t Find it';
}};
echo $Porter;
the line
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
will only retrieve the first row of the database.
If you want to check every row to see if ANY of them are Porter, then you will need to set the flag to a default of "no", loop your results, and set the flag if you find it:
$Porter="Not Present";
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
if($row['County'] == "Porter"){
$Porter = "Present";
}
}
echo $Porter;
(this is just a basic example; you can optimize it farther by breaking out of the loop when you first find the result for example, but this will do the job)
mysqli_fetch_array only fetches one row. Use while loop to go over all rows:
while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
If you don't want to check per row but want to check if the value exists in any of the rows use mysqli_fetch_all:
$sql="SELECT County from GAINLP WHERE SpeciesName LIKE '%Actias_luna%'";
$result=mysqli_query($connect,$sql);
$rows=mysqli_fetch_all($result,MYSQLI_ASSOC);
if (in_array("Porter", $rows)) {
$Porter='Present';
} else {
$Porter='Not Present';
};
echo $Porter;
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.
Hello everyone I have really chalenging task I have to sort an array by condition with mysql select or by another array. Imagine something like that
$arrayINeedToSort = array(5,4,7,96,1,0,55);
// Dont know if it is important cause of next step
sort($arrayINeedToSort);
$arrayToCheckDuplicData = array();
foreach($arrayINeedToSort as $aid)
{
$sql = mysql_query("SELECT column FROM `some_table` WHERE arrayValueId = $aid ");
$num = mysql_num_rows($sql);
if($num)
{
echo $aid;
}
else
{
// skip this id cause it is not in array but i would like to push at the end of an array again sorted
if(in_array($aid,$arrayToCheckDuplicData))
{
echo $aid;
}
else
{
$arrayINeedToSort[] = $aid;
}
$arrayToCheckDuplicData[] = $aid;
}
}
Thats my idea, pushing array values to the end of acutal array with another simple array check but i am open to different/better ideas.
UPDATE //////////////////////////////////////////////
I need to see all ids so i cant skip them and I need them sorted.
TO BE MORE SPECIFIC i would liek to have input like this
1,4,96 (of values which are in database ) 0,5,7,55 (of values which are not in databse) at the end array will look like this
$outputSortedArray(1,4,96,0,5,7,55);
Could you please be more specific in what you want. On what is the input and what you want in your output.
If you need to sort the array $arrayINeedToSort then use sort function.
Give an example of the input and output array. Also the table with condition you wanted to check.
Check the following code and verify if this is what you want:
`
$arrayINeedToSort = array(5,4,7,96,1,0,55);
$in_cond = implode(",", $arrayINeedToSort);
$arrayToCheckDuplicData = array();
$result = mysql_query("SELECT column FROM `some_table` WHERE arrayValueId IN (" . $in_cond . ") ORDER BY arrayValueId ASC");
$num = mysql_num_rows($result);
while ($row = mysql_fetch_assoc($result)) {
if (in_array($row["arrayValueId"], $arrayINeedToSort)) {
echo $row["arrayValueId"];
}
else {
if (in_array($row["arrayValueId"], $arrayToCheckDuplicData)) {
echo $row["arrayValueId"];
}
$arrayToCheckDuplicData[] = $row["arrayValueId"];
}
}
`
You can use php array sorting functions: http://www.php.net/manual/en/array.sorting.php
There is also a function called array_unique, which is delete multiple values from an array.
If you want to sort the array in the MySQL query, use "ORDER BY ASC/DESC".
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.