SQL OR statement does not work in PHP - php

I want to get some elements from a database (phpmyadmin). The database "top" is set up like:
ID || Name
____________
1 || Home
2 || About
3 || Users
4 || Admin
...
I use the following Code to get the information:
<?php
$sql = "SELECT ID
FROM top
WHERE Name='Users' OR Name='Admin'";
$query = mysqli_query($dbconnect, $sql);
$oq = mysqli_fetch_assoc($query);
if(in_array($_GET['ID'], $oq)){
//Execute some Code
}
?>
If I execute the sql-code I get the result I want (ID 3 and 4) but in "$oq" there is only one element (the first one -> 3) left. Therefore the Code I want to execute is only displayed once.

You have to use a while loop:
$oq = array();
while($row = mysqli_fetch_assoc($query)) {
echo $row['ID'];
$oq[] = $row['ID'];
}
As you have done it you're only fetching one row in $oq. You will have to add each value to the array $oq in order to use in_array() for the test.
There are some other techniques you can use here, for instance you could fetch everything (an array of arrays) and loop through the array, depending on your needs.

You will have to use array to use have multiple DB values
$values=array();
while($row = mysql_fetch_array($result)){
$values = array('ID'=>$row['ID']);
}

Related

Array is not working well

I am new in PHP. I have a code in which i use 2 sql commands. First command fetch 1st latest row and second command fetch 2nd latest row. This code is place in file sqlquery.php
here is code of sqlquery.php
<?php
include ("connection.php");
Problem of my code is my array print same record in all rows. But in Db there is different records. My code is print only first record in each row
I want to output of my code is like this
The problem is the double loop, now for every result from the first query you add an array item for each result of the second query duplicating the array items effectively, you can change this
while($row1 = mysql_fetch_assoc($result1)){
while($row2 = mysql_fetch_assoc($result2)){
To:
while($row1 = mysql_fetch_assoc($result1) && $row2 = mysql_fetch_assoc($result2))
{
It would be better to change your sql query though to incorporate all values in one request.
Another thing you can do, though is less nice:
while($row1 = mysql_fetch_assoc($result1))
{
$opinion[]= $row1['opinion'];
$action[]= $row1['atitle'];
$long_term[]= $row1['ltitle'];
$outlook[]= $row1['otitle'];
$rating_type[]= $row1['ttitle'];
$short_term[]= $row1['stitle'];
}
while($row2 = mysql_fetch_assoc($result2))
{
$p_long_term[]= $row2['ltitle'];
$p_short_term[]= $row2['stitle'];
}

php foreach not iterating

$email is the name of a table in my database. When I execute the mysql query in phpmyadmin, I correctly get two casenums, 1 and 3.
However, when I try to loop through the array, echo $caseNum."<br>"; prints
1
1
instead of
1
3
The code:
$_SESSION['caseNums'] = mysql_fetch_array(mysql_query("SELECT `casenum` FROM `$email`"));
$_SESSION['cases'] = array();
foreach($_SESSION['caseNums'] as $caseNum) {
echo $caseNum."<BR>";
}
That's to be expected. mysql_fetch_array() returns a SINGLE row of data from your query, with dual string+integer keys.
In other words, you're printing out the value retrieved from the first row of data only, and printing it twice because it was duplicated in the returned array.
You need:
$result = mysql_query(...) or die(mysql_error());
while($row = mysql_fetch_row($result)) {
$_SESSION['caseNums'][] = $row[0];
}

MYSQL - Select specific value from a fetched array

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;

Get rows from mysql table to php arrays

How can i get every row of a mysql table and put it in a php array? Do i need a multidimensional array for this? The purpose of all this is to display some points on a google map later on.
You need to get all the data that you want from the table. Something like this would work:
$SQLCommand = "SELECT someFieldName FROM yourTableName";
This line goes into your table and gets the data in 'someFieldName' from your table. You can add more field names where 'someFieldName' if you want to get more than one column.
$result = mysql_query($SQLCommand); // This line executes the MySQL query that you typed above
$yourArray = array(); // make a new array to hold all your data
$index = 0;
while($row = mysql_fetch_assoc($result)){ // loop to store the data in an associative array.
$yourArray[$index] = $row;
$index++;
}
The above loop goes through each row and stores it as an element in the new array you had made. Then you can do whatever you want with that info, like print it out to the screen:
echo $row[theRowYouWant][someFieldName];
So if $theRowYouWant is equal to 4, it would be the data(in this case, 'someFieldName') from the 5th row(remember, rows start at 0!).
$sql = "SELECT field1, field2, field3, .... FROM sometable";
$result = mysql_query($sql) or die(mysql_error());
$array = array();
while($row = mysql_fetch_assoc($result)) {
$array[] = $row;
}
echo $array[1]['field2']; // display field2 value from 2nd row of result set.
The other answers do work - however OP asked for all rows and if ALL fields are wanted as well it would much nicer to leave it generic instead of having to update the php when the database changes
$query="SELECT * FROM table_name";
Also to this point returning the data can be left generic too - I really like the JSON format as it will dynamically update, and can be easily extracted from any source.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo json_encode($row);
}
You can do it without a loop. Just use the fetch_all command
$sql = 'SELECT someFieldName FROM yourTableName';
$result = $db->query($sql);
$allRows = $result->fetch_all();
HERE IS YOUR CODE, USE IT. IT IS TESTED.
$select=" YOUR SQL QUERY GOOES HERE";
$queryResult= mysql_query($select);
//DECLARE YOUR ARRAY WHERE YOU WILL KEEP YOUR RECORD SETS
$data_array=array();
//STORE ALL THE RECORD SETS IN THAT ARRAY
while ($row = mysql_fetch_array($queryResult, MYSQL_ASSOC))
{
array_push($data_array,$row);
}
mysql_free_result($queryResult);
//TEST TO SEE THE RESULT OF THE ARRAY
echo '<pre>';
print_r($data_array);
echo '</pre>';
THANKS

Mysql database retrieve multiple rows

I use a mysql database. When I run my query I want to be able to put each row that is returned into a new variable. I dont know how to do this.
my current code:
<?php
$result=mysql_query("SELECT * FROM table WHERE var='$var'");
$check_num_rows=mysql_num_rows($result);
while ($row = mysql_fetch_assoc($result))
{
$solution=$row['solution'];
}
?>
The thing is that check num rows can return a row of an integer 0-infinity. If there are more solutions in the database how can I assign them all a variable. The above code works fine for 1 solution, but what if there are more? Thanks.
You can't give each variable a different name, but you can put them all in an array ... if you don't know how this works I suggest looking at a basic tutorial such as http://www.w3schools.com/php/php_arrays.asp as well as my code.
A very simple way (obviously I haven't included mysql_num_rows etc):
$solutions = array()
while($row = mysql_fetch_assoc($result)) {
$solutions[] = $row['solution'];
}
If you have three in your result solutions will be:
$solutions[0] -> first result
$solutions[1] -> second
$solutions[2] -> third
<?php
$result=mysql_query("SELECT * FROM table WHERE var='$var'");
$solution = array();
$check_num_rows=mysql_num_rows($result);
while ($row = mysql_fetch_assoc($result))
{
$solution[]=$row['solution'];
}
?>

Categories