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;
Related
I am selecting a value from database and want to print it in the html page. I have tried this piece of code:
$queryreg = mysql_query("SELECT available FROM hospital WHERE h_name='$hospital' ");
$a= $queryreg;
echo $a;
But the result is showing as "Resource id #7". Please help me out
$queryreg = mysql_query("SELECT available FROM hospital WHERE h_name='$hospital' ");
$queryreg = mysql_fetch_assoc($queryreg);
$a= $queryreg;
echo $a['available'];
mysql_query() returns a resource on success. You will have to use mysql_fetch_row to retrieve values that returns a numerical array that corresponds to the fetched row and moves the internal data pointer ahead.
$queryreg = mysql_query("SELECT available FROM hospital WHERE h_name='$hospital' ");
if($queryreg)
{
if(mysql_num_rows($queryreg) > 0)
{
$a = mysql_fetch_row($queryreg);
echo $a[0];
}
else
echo "No records found.";
}
else
echo "Cannot fetch records ".mysql_error();
In cases when there are multiple rows returning from query, you can use mysql_fetch_array() that fetches a result row as an associative array, a numeric array, or both
$queryreg = mysql_query("SELECT available FROM hospital WHERE h_name='$hospital' ");
if($queryreg)
{
if(mysql_num_rows($queryreg) > 0)
{
while($result = mysql_fetch_array($queryreg))
{
echo "<br>".$result[0];
}
}
else
echo "No records found.";
}
else
echo "Cannot fetch records ".mysql_error();
$query=$db->prepare("SELECT *...
while($data=$query->fetch(PDO::FETCH_ASSOC)){...}
I have a query use while loop print out the data.
How can I check if while loop didn't fetch out any data(0 row from db), so I can print "0 result" on screen.
I don't want to make extra query for COUNT(*), is any way do check from while loop?
You have to use $sth = $query->execute() (and $sth->fetch() instead of $query->fetch() ) first, then $sth->rowCount will give you the number of results.
Just put a flag inside the loop to ensure you entered at least once.
Something like:
$flag = false;
$query=$db->prepare("SELECT *...");
while($data=$query->fetch(PDO::FETCH_ASSOC)){
$flag = true;
}
if ($flag) {} //entered
Added semicolon, thanks #Fred -ii
So you want to count the amount of results you get. In that case, you can just count a var up inside the loop:
while($data=$query->fetch(PDO::FETCH_ASSOC)){
$i++;
//your code here
}
If you want to check if you got no data, you can check $data:
while($data=$query->fetch(PDO::FETCH_ASSOC)){
if($data === false) {
echo "0 result";
}
}
I have a small problem and since I am very new to all this stuff, I was not successful on googling it, because I dont know the exact definitions for what I am looking for.
I have got a very simple database and I am getting all rows by this:
while($row = mysql_fetch_array($result)){
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
Now, my question is: how do I filter the 2nd result? I thought something like this could work, but it doesnt:
$name2= $row['name'][2];
Is it even possible? Or do I have to write another mysql query (something like SELECT .. WHERE id = "2") to get the name value in the second row?
What I am trying to is following:
-get all data from the database (with the "while loop"), but than individually display certain results on my page. For instance echo("name in second row") and echo("id of first row") and so on.
If you would rather work with a full set of results instead of looping through them only once, you can put the whole result set to an array:
$row = array();
while( $row[] = mysql_fetch_array( $result ) );
Now you can access individual records using the first index, for example the name field of the second row is in $row[ 2 ][ 'name' ].
$result = mysql_query("SELECT * FROM ... WHERE 1=1");
while($row = mysql_fetch_array($result)){
/*This will loop arround all the Table*/
if($row['id'] == 2){
/*You can filtere here*/
}
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
$counter = 0;
while($row = mysql_fetch_array($result)){
$counter++;
if($counter == 2){
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
}
This While loop will automatically fetch all the records from the database.If you want to get any other field then you will only need to use for this.
Depends on what you want to do. mysql_fetch_array() fetches the current row to which the resource pointer is pointing right now. This means that you don't have $row['name'][2]; at all. On each iteration of the while loop you have all the columns from your query in the $row array, you don't get all rows from the query in the array at once. If you need just this one row, then yes - add a WHERE clause to the query, don't retrieve the other rows if you don't need them. If you need all rows, but you wanna do something special when you get the second row, then you have to add a counter that checks which row you are currently working with. I.e.:
$count = 0;
while($row = mysql_fetch_array($result)){
if(++$count == 2)
{
//do stuff
}
}
Yes, ideally you have to write another sql query to filter your results. If you had :
SELECT * FROM Employes
then you can filter it with :
SELECT * FROM Employes WHERE Name="Paul";
if you want every names that start with a P, you can achieve this with :
SELECT * FROM Employes WHERE Name LIKE "P%";
The main reason to use a sql query to filter your data is that the database manager systems like MySQL/MSSQL/Oracle/etc are highly optimized and they're way faster than a server-side condition block in PHP.
If you want to be able to use 2 consecutive results in one loop, you can store the results of the first loop, and then loop through.
$initial = true;
$storedId = '';
while($row = mysql_fetch_array($result)) {
$storedId = $row['id'];
if($initial) {
$initial = false;
continue;
}
echo $storedId . $row['name'];
}
This only works for consecutive things though.Please excuse the syntax errors, i haven't programmed in PHP for a very long time...
If you always want the second row, no matter how many rows you have in the database you should modify your query thus:
SELECT * FROM theTable LIMIT 1, 1;
See: http://dev.mysql.com/doc/refman/5.5/en/select.html
I used the code from the answer and slightly modified it. Thought I would share.
$result = mysql_query( "SELECT name FROM category;", db_connect() );
$myrow = array();
while ($myrow[] = mysql_fetch_array( $result, MYSQLI_ASSOC )) {}
$num = mysql_num_rows($result);
Example usage
echo "You're viewing " . $myrow[$view_cat]['name'] . "from a total of " . $num;
I have a variable called $uid, and I would like to print a message if the variable $uid is not contained in the "loginid" field of a MySQL table "tweets" on any row that has another variable, $submissionid. I think my query $tweetquery is okay. Basically, I would like the message to echo if the loginid variables pulled from "tweets" never equal $uid.
How can I do this?
Thanks in advance,
John
$tweetquery = "SELECT loginid
FROM tweets
WHERE submissionid = '$submissionid'";
$tweetresult = mysql_query($tweetquery);
if...
echo '<div>Message</div>';
Have a look at mysql_num_rows($result).
if ( mysql_num_rows($result) > 0 )
{
// Do something
}
else
{
echo 'No results';
}
Call me crazy, but using mysql_num_rows is not the way I'd do this. mysql_fetch_array does not do anything destructive if nothing is returned, so call that as normal.
$row = mysql_fetch_array( $resource );
if(!$row)
{
//do what you would do if the query returned nothing
}
else
{
do
{
// do what you would do with the row
} while( $row = mysql_fetch_array( $resource ) );
}
The problem with mysql_num_rows is that it actually represents a call to the database asking for how many rows exist in the pointer. It is a, frankly, needless back-and-forth which can easily be avoided. So why not avoid it?
You can use mysql_num_rows:
if (mysql_num_rows($tweetresult) > 0)
// results found
Use mysql_num_rows():
if (mysql_num_rows($tweetresult) == 0) {
echo 'Message';
}
if(mysql_num_rows($tweetresult) == 0)
echo "<div>Message</div>";
else {
//Do something if $uid was found
}
mysql_num_rows() returns the numbers of rows fetched from the database. If rows fetched are zero echo a message.
$tweetquery = "SELECT loginid
FROM tweets
WHERE submissionid = '$submissionid'";
$tweetresult = mysql_query($tweetquery);
if(mysql_num_rows($tweetresult) > 0){
// your results here
} else {
echo '<div>Message</div>';
}
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";
}