Query returning just one row - php

I'm running this MySQL query in PHP:
SELECT * FROM settings
This is the settings table:
id ------- name ------- value
_____________________________
1 --------- one --------- 1
2 --------- two --------- 2
For some reason, when I run my query I'm only given the first result (even when running a foreach loop).
I've taken a look around and can see that a workaround is to run a while loop. This to me looks a bit counter-active.
My question is, why is this occurring, and how can I fix it to run as a standard foreach loop?
Edit
The PHP code:
$query = #mysql_query("SELECT * FROM settings");
$result = mysql_fetch_assoc($query);
print_r($result);

you have to walk through you resultset with a loop:
$con=mysqli_connect("localhost","username","password","database");
$query = "SELECT * FROM settings";
$result = mysqli_query($con, $query);
echo "<pre>";
while ($row = mysqli_fetch_assoc($result)) {
print_r($row);
}
or if you want to use PDO (i.e. use a foreach):
try {
$db = new PDO("mysql:dbname=databasename;host=localhost", "username", "password" );
$sql = "SELECT * FROM settings";
foreach ($db->query($sql) as $row) {
print_r($row);
}
} catch(PDOException $e) {
echo $e->getMessage();
}

Related

PHP MySQLi to PDO?

I don't know why my code doesn't return true, the while loop works fine, but there's a problem.
$PDO_result = $db_PDO->prepare("SELECT * FROM nnm_anime INNER JOIN nnm_anime_info ON nnm_anime.a_id = nnm_anime_info.a_id WHERE a_name LIKE '?%' ");
$PDO_result->bindParam(1, $pismenka[$i]);
$PDO_result->execute();
Here when I var_dump() $PDO_result I get one item in array so the following while loop should work:
while($row = $PDO_result->fetch(PDO::FETCH_ASSOC))
but it doesn't.
Working MySQLi:
$result = mysqli_query($connect_to_db, "SELECT * FROM nnm_anime INNER JOIN nnm_anime_info ON nnm_anime.a_id = nnm_anime_info.a_id WHERE a_name LIKE '$pismenka[$i]%' ");
while($row = mysqli_fetch_array($result))
The most simple solution would be to change $pdo->fetch(PDO::FETCH_ASSOC) to $pdo->fetchAll(PDO::FETCH_ASSOC)
fetchAll returns ALL rows in the requested query, while fetch only gets 1 row (the first)
Example:
<?php
try {
$PDO_result = $db_PDO->prepare("SELECT * FROM nnm_anime INNER JOIN nnm_anime_info ON nnm_anime.a_id = nnm_anime_info.a_id WHERE a_name LIKE ?");
//Execute by inserting an array:
if (!$PDO_result->execute([$pismenka[$i] . "%" ])) { //Added ."%"
die('Error!');
}
//Fetch rows:
$rows = $PDO_result->fetchAll(PDO::FETCH_ASSOC);
//Go trough each row:
foreach ($rows as $row) {
//Do something
}
//Catch exceptions thrown by PDO
} catch (PDOException $ex) {
print_r($ex);
}

incorrect result display from database

I have a database table that has 4 records with a column _id that auto increments. When I run a query to get all records, it works but it doesn't echo out all the ids, it only points to the first rows and echos it four times. I am using PHP and MySQLi. Here is my code
Code for querying
$sql = "SELECT * FROM att_table";
$query = $conn->query($sql);
$result = $query->fetch_assoc();
Code for display
do{
echo result['_id'];
}while($query->fetch_assoc());
It outputs 1111 instead of 1234. Please what is wrong?
You're fetching each of the 4 results, so it loops the appropriate number of times; but you're only assigning the fetched result to $result once, so that's the only _id value that gets echoed
do{
echo $result['_id'];
}while($result = $query->fetch_assoc())
You also can use a foreach loop :
$sql = "SELECT * FROM att_table";
$query = $conn->query($sql);
$result = $query->fetch_assoc();
foreach($result as $data){
echo $data['_id'];
}

Select All MySQL Rows

I have the following code which choose all rows in MYSQL but it show the last row only
$query = mysql_query("SELECT * FROM `users`") or die(mysql_error());
while ( $row = mysql_fetch_assoc($query) )
{
$token = $row['instagram_access_token'];
}
echo "$token";
Your code echo last row because, within while loop every time you overwrites $token value with new value. Try to connect using PDO & assign variable to array like this.
$token=[];
$user='your_user_name';
$pass='your_password';
$conn= new PDO('mysql:host=your_host_name;dbname=your_db_name', $user, $pass);
$query = $conn->prepare('SELECT * FROM `users`');
$query->execute();
// alternatively you could use PDOStatement::fetchAll() and get rid of the loop
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$token[] = $row['instagram_access_token']; // see this line with []
}
echo '<pre>';
print_r($token);
echo '</pre>';
Note: Don't use mysql_* see more here Why shouldn't I use mysql_* functions in PHP?
Change your code to this:
$query = mysql_query("SELECT * FROM `users` ORDER BY RAND()") or
die(mysql_error());
while ( $row = mysql_fetch_assoc($query) )
{
$m = $row['instagram_access_token'];
echo "$m";
}

php echo data from certain id

EDIT: I'm sorry I was unclear, I try to explain it right this time.
I have this data in a database table called tMenu:
id page_nl text
1 index_1 index1_text
2 index_2 index2_text
3 index_3 index3_text
These are 3 pages on my website called (in this case) index_1, index_2 and index_3. I have programmed it is such a way that each page shows there index1_text.
What I want now is to show page_nl in a menu. The code I have now is:
$qh = mysql_query('SELECT id, page_nl FROM tMenu ORDER BY id');
$row = mysql_fetch_array($qh);
$id = 'id';
<? echo $row['page_nl']; $id=="1" ;?>
<? echo $row['page_nl']; $id=="2" ;?>
<? echo $row['page_nl'];?>
In the way it is now it shows only page_nl from id 1, but I want that the next link shows page_nl from id 2. I hope my question is more clear now.
Your question isn't very clear - are you asking for something like this
$sql = "select * from yourtable where id = 1";
$result = mysql_query($sql);
//I am assuming there are more than 1 rows for ID 1
while($row = mysql_fetch_assoc($result)) {
echo $row['page_nl'];
}
OR ============================
$sql = "select * from yourtable"; //Select All
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)) {
if($row['id'] == 1)
{
echo $row['page_nl'];
}
}
Presuming you mean database table, you need a routine to connect to the database then fetch the info:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "databasename"); // database name
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * FROM table_name"; // put table name here
$result = $mysqli->query($query);
/* numeric array */
/* associative array */
$row = $result->fetch_array(MYSQLI_ASSOC);
printf ("%s (%s)\n", $row["id"], $row["page_nl"]);
/* free result set */
$result->free();
/* close connection */
$mysqli->close();
?>
You need to use a foreach($var as $key =>$value) loop

Php mysql query array stores 2 fields in each array index

When I try to mysql_fetch_row the array that is created contains 2 fields from my selection at each index. I would like to ask why is this happening?
<?php
$categoryid = $_GET['id'];
include('connect.php');
$query = "SELECT
Categories_SubCategories.IdCategory,Categories_SubCategories.idSub_Category,
Categories.Name, Sub_Categories.Name from Categories_SubCategories JOIN
Categories on Categories.idCategory = Categories_SubCategories.idCategory
JOIN Sub_Categories on Categories_SubCategories.idSub_Category =
Sub_Categories.idSub_Category
WHERE Categories_SubCategories.IdCategory = $categoryid";
$result = mysql_query($query);
$rows = mysql_num_rows($result);
for($i=0; $i<$rows; $i++){
$display = mysql_fetch_row($result);
echo "$display[3]";
}
?>
most PHP programmers use while() loop when they want to work with mysql_fetch_array().
Take a look at this sample code:
$query = mysql_query("SELECT id,name FROM tbl_members");
if (mysql_num_rows($query)) {
while ($result = mysql_fetch_array($query)) {
echo('User #'.$result['id'].' is: '.$result['name'].'<br />');
}
}
// Output can be something like this:
// User #1 is: John
// User #2 is: Sarah
replace mysql_num_rows with mysql_fetch_array or mysql_fetch_assoc

Categories