SQL only retrieve first item in the database - php

$search = mysql_query("SELECT subject FROM book WHERE useid = $userid") or die(mysql_error());
$sub = mysql_fetch_array($search, MYSQL_ASSOC);
print_r($sub);
There's a lot of subject in the book table with same user id, but it only retrieve first of it, why is that so?

mysql_fetch_array returns array representation of current row only:
Fetch a result row as an associative array, a numeric array, or both
You have to use loop to iterate over all returned rows:
$search = mysql_query("SELECT subject FROM book WHERE useid = $userid") or die(mysql_error());
while($sub = mysql_fetch_array($search, MYSQL_ASSOC)) {
print_r($sub);
}

You have to parse result of this
while($sub = mysql_fetch_array($search, MYSQL_ASSOC)){
print_r($sub);
}
Reason for this
mysql_fetch_array function returns an associative array, but it also returns FALSE if there are no more rows to return! Using a PHP While Loop we can use this information to our advantage.
If we place the statement "$row = mysql_fetch_array()" as our while loop's conditional statement we will accomplish two things:
We will get a new row of MySQL information that we can print out each time the while loop checks its conditional statement.
When there are no more rows the function will return FALSE causing the while loop to stop!
Hence it will continue to print data until the function returns false

As mysql* are officially depreciated you should be using mysqli* or prepared statements
//$Conn = new mysqli(host, username, pass, db);
$sqlquery = "SELECT subject FROM book WHERE useid = $userid";
//Execute the query reurns data into a $result
$result = $Conn->query($sqlquery);
//results into a associative array
$resultArray = $result->fetch_all(MYSQLI_ASSOC);
print_r($resultArray);
OR PDOStatement::fetchAll
<?php
$sth = $dbh->prepare("your query");
$sth->execute();
/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll();
print_r($result);
?>

Related

SELECT * FROM `users` returns only first user

I have a php script:
$sql = $db->query("SELECT * FROM `users`");
$row = $sql->fetch();
foreach($row as $value){
echo $value . "<br>";
}
Database 'users' contains 29 records, but I'm getting this:
This is because you're only fetching one record.
Try your code like this:
$sql = $db->query("SELECT * FROM `users`");
$row = $sql->fetchAll();
foreach($row as $value){
print_r($value);
echo "<br>";
}
this way you'll get an array of results, so you loop over the array instead of over the properties.
fetch() returns single elements. Instead try with fetchAll
$row = $sql->fetchAll();
fetchAll — Returns an array containing all of the result set rows
it will return an array hence, remove echo $value and use print_r($value)
fetch — Fetches the next row from a result set only 1 row
mysql fetch() function fetches the next row from a result set only 1 row, whereas mysql fetchAll() function returns an array containing all of the result set rows.
So use fetchAll() to get all the records from resultset, replace this line
$row = $sql->fetch();
with
$row = $sql->fetchAll();

why select * from return only the first field?

I'm making the next query to the db
$result = $con->query ( 'select * from table');
$datos = $result->fetch_assoc();
echo "Cantidad de datos: ".count($datos).",";
print_r($datos);
Should show an array with all the entries, but only show the first entry. Why?
PS: i saw other posts but i haven't limit or joins.
fetch_assoc fetches a result row as an associative array
So you could go through all the rows with a while cycle that fetches another row if possible.
$count = 0;
while( $row = $result->fetch_assoc() ){
// You can access data like this -->> $row['data'];
$count++;
}
echo $count;
and after you are done, you should free your memory associated with the result
$result->free();
But if you'd like to get count only, you could use mysql_num_rows that returns number of rows from result set.
$count = mysql_num_rows($result);
echo $count;
fetch_assoc returns only one row when you are doing$datos = $result->fetch_assoc(); You can fetch the entire array in both PDO and mysqli, Here is a example to fetch all rows using the mysqli->fetch_all function, hope this helps!
//Database Connection
$sqlConn = new mysqli($hostname, $username, $password, $database);
//Build SQL String
$sqlString = "SELECT * FROM my_table";
//Execute the query and put data into a result
$result = $this->sqlConn->query($sqlString);
//Copy result into a associative array
$resultArray = $result->fetch_all(MYSQLI_ASSOC);
//Copy result into a numeric array
$resultArray = $result->fetch_all(MYSQLI_NUM);
//Copy result into both a associative and numeric array
$resultArray = $result->fetch_all(MYSQLI_BOTH);
Please always refer to the manual of the framework you are using. fetch_assoc();Fetches a result row as an associative array. If you want to fetch all the rows, use a while statement like so:
$result = $c->query('SELECT user,host FROM mysql.user');
while ($row = $result->fetch_assoc()) {
printf("'%s'#'%s'\n", $row['user'], $row['host']);

How can I get all id's from a database column into one single array?

How can I fetch all the values from columns (like an id column) and put them into an array?
I'm using PDO API and I tried with other code, but it's not working for me.
$STH = $DBH->query('SELECT Tid from Playlist ');
$STH->setFetchMode(PDO::FETCH_OBJ);
$result = $STH->fetch();
while($result = mysql_fetch_array($result)) {
$ids_array[] = $result['Tid'];
}
You can directly return an id array by specifying the PDO::FETCH_COLUMN.
$stmt = $DBH->query("SELECT Tid from Playlist");
$ids_array = $stmt->fetchAll(PDO::FETCH_COLUMN);
You are mixing mysql_* and PDO, which is obviously not going to work.
Just fetchAll() your results and then just merge all rows into one array by simply looping through all rows with array_map() and returning the id, e.g.
$stmt = $DBH->query("SELECT Tid from Playlist");
$result = $stmt->fetchAll(PDO::FETCH_OBJ);
$ids = array_map(function($v){
return $v->Tid;
}, $result);
print_r($ids);

PHP Zend - Execute to get a rowset and total number of records

I encounter some problem where i want to execute a SQL statement and get the total number of records + all the records.
$strSQL = "SELECT * FROM table WHERE ProjectID = 1 ";
$stmt = $db->query($strSQL);
$total = count($stmt->fetchAll());
while ($row = $stmt->fetch()){
..No More Record Shown here..
}
but there is no more record in the while loop after i execute fetchAll, i believe I need to get back to the first row or something, anyone know how to fix this?
You've already fetched all the records with fetchAll(). So when you call fetch(), there are no more records to read. Try storing the return value of fetchAll() in a variable and iterating through that. Something like this:
$strSQL = "SELECT * FROM table WHERE ProjectID = 1";
$stmt = $db->query($strSQL);
$allRows = $stmt->fetchAll();
$total = count($allRows);
foreach ($allRows as $row){
// process each $row
}

PHP - Select a unique mysql line without while [duplicate]

This question already has answers here:
Single result from database using mysqli
(6 answers)
Closed 6 months ago.
I want to select only unique values with php/mysql.
I can do it with many line, but I forget how to do it without while... :)
Thanks a lot.
Here is the code that I want to do without while.
$request_1m = "SELECT date1, date2 from mytable";
$result_1m = mysql_query($request_1m,$db);
while($row = mysql_fetch_array($result_1m))
{
/* Get the data from the query result */
$date1_1m = $row["date1"];
$date2_1m = $row["date2"];
}
mysql_fetch_assoc + SELECT with DISTINCT
I'm not sure I understand your question, but here's what I think you want to do :
$request_1m = "SELECT date1, date2 from mytable";
$result_1m = mysql_query($request_1m,$db);
list($date1_1m, $date2_1m) = mysql_fetch_row($result_1m);
Note that this will only get the first row from the result set (just as if you LIMIT 1)
like this?
$dbresult = mysql_query("SELECT DISTINCT field FROM table");
$result = array();
while ($row = mysql_fetch_assoc($dbresult))
{
$result[] = $row;
}
This gets you all unique values from "field" in table "table".
If you really wish to avoid the while loop, you can use the PHP PDO objects, and in particular call the PDO fetchAll() method to retrieve the complete results array in one go. PDO fetchAll() documentation
$db = new PDO('dblib:host=your_hostname;otherparams...');
$db->query("SELECT DISTINCT col FROM table");
$results = $db->fetchAll();
// All your result rows are now in $results
Heres how I do it and Json encode after. This will ensure it will encode only UNIQUE json Values (Without duplicates) as an example
$tbl_nm = "POS_P";
$prod_cat = "prod_cat";
//Select from the POS_P Table the Unique Product Categories using the DISTINCT syntax
$sql = "SELECT DISTINCT $prod_cat FROM $tbl_nm";
//Store the SQL query into the products variable below.
$products = mysql_query($sql);
if ($products){
// Create an array
$rows = array();
// Fetch and populate array
while($row = mysql_fetch_assoc($products)) {
$rows[]=$row;
}
// Convert array to json format
$json = json_encode(array('Categories'=>$rows));
echo $json;
}
//Close db connection when done
mysql_close($con);
?>
That is very easy, take out the while, like below
$row = mysqli_fetch_assoc($result);
$date1_1m = $row["date1"];

Categories