Reading only one row from mysql when there are two - php

I need the script to output both rows. However, I can only get it to output the first one. Help please!
Here is my code:
<?php
$server = ""; // assume server name
$connect = mysqli_connect($server,,,) //assume password etc.
or die ("Couldn't connect to server"); //connect to admin database
$query = "SELECT mt FROM Content";
$result = mysqli_query($connect, $query)
or die ('Could not execute query.');
$nrows = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);
$i = 0;
while ($i <= 30)
{
echo $row[$i];
$i++;
}
?>

You need to fetch into a row in a loop:
while ($row = mysqli_fetch_array($result)) { ...

Try to type:
while( $row = mysqli_fetch_array($result) )
{
echo $row[$i];
$i++;
}

You only fetch the first row.
You should do a while loop on your mysqli_fetch_array() to get both rows.
while ($row = mysqli_fetch_array($result)) {
for ($i = 0; $i < 30; $i++) {
echo $row[$i];
}
}
That should do it (like some of the other posted while I was writing but they forgot parts of the answer :-)
But I think that you should use the OO way of using mysqli.

You could use mysqli_fetch_all() to fetch all of the records.

Related

How do I display content with PDO based on num_rows?

Apparently, the num_rows property does not work in PDO as it would with mysqli.
Normally, with mysqli, my code would look like this:
<?php
$conn = new mysqli('127.0.0.1','root','mypassword','mydbname');
if($conn->connect_errno){
die("Sorry, could not connect.");
}
$id = 1;
$qry = "SELECT * FROM customers WHERE id = ?";
$getCustomers = $conn->prepare($qry);
$getCustomers->bind_param("i",$id);
$getCustomers->execute();
$result = $getCustomers->get_result();
$count = $result->num_rows;
if($count == 0){
echo "Sorry, there are no results";
}else{
while($row = $result->fetch_object()){
echo $row->id;
echo $row->fname;
echo $row->lname;
echo $row->entry_date;
}
}
?>
How do I create the equivalent with PDO? Here is what I have tried so far:
<?php
try{
$conn = new PDO('mysql:host=127.0.0.1;dbname=mydbname','root','mypassword');
}catch(PDOException $e){
echo $e;
}
$id = 1;
$qry = $conn->prepare("SELECT * FROM customers WHERE id = :id");
$qry->execute([':id'=>$id]);
$rows = $qry->fetchAll(PDO::FETCH_OBJ);
$count = count($rows);
if($count == 0){
echo "Sorry, there are no results for your criteria";
}else{
for($i = 0; $i < $count; $i++){
echo $rows->fname;
}
}
?>
Yeah isn't PDO great ;p no need to count rows when you have already got them.
To loop over your result as you have an array.
Change:
for ($i = 0; $i < $count; $i++){
echo $rows->fname;
}
To:
for ($i = 0; $i < $count; $i++){
echo $rows[$i]->fname;
}
Or better just use a foreach.
foreach ($rows as $row) {
echo $row->fname;
}
The statement
fetchAll(PDO::FETCH_OBJ) returns an array containing all of the result set rows as described here. To get the size of the array use sizeof($count). That should give you the size of the array.
To answer your question specifically. You can use rowCount() to retrieve the number of rows in a result:
$qry = $conn->prepare("SELECT * FROM customers WHERE id = :id");
$qry->execute([':id'=>$id]);
$count = $qry->rowCount();
$rows = $qry->fetchAll(PDO::FETCH_ASSOC); //my personal preference
for($i=0; $i < $count; $i++) {
echo $rows[$i]['fname'];
}
To more closely replicate your mysqli code:
while($row = $qry->fetch(PDO::FETCH_OBJ) {
echo $row->fname;
}
Of course, you should always check $conn->errorCode() after each database execution to ensure something go sideways on you.
UPDATE:
As Lawrence points out, rowCount() does not work with MS SQL Server. An alternative in that case is to use fetchAll() and count().

php and mysql issue with query return

I have this code working but only halfway, it is able to return all of the information that I need however on the return, one of the JSON array is returned twice, why is this? I can't seem to figure out why.
Here is my code:
$rows = mysql_num_rows($res);
$array = array();
$i = 0;
while($row = mysql_fetch_array($res, MYSQL_NUM)) {
$array[$i] = (int)$row[0] . "\n";
$i++;
if ($i > $rows){
break;
}
}
$JsonArray = array();
for($i = 0; $i < $rows; $i++){
$q = "SELECT firstName, lastName, email from $mysql_database.$UsersTable WHERE idUser = $array[$i]";
$res = mysql_query($q, $connect) or die(mysql_error());
while($row = mysql_fetch_assoc($res)){
$new_array[] = $row; // Inside while loop
}
$JsonArray[$i] = $new_array;
}
echo json_encode($JsonArray);
This is the result:
All I need is the second and third but somehow I don't know why it is outputting the first twice.
Also, how can I format the result better in the JsonArray?
From what I see you are trying to do, you are trying to fetch your result set from the database for the query.
You need not make use of all those loops. All you have to do is:
$q = "SELECT firstName,lastName,email from $mysql_database.$UsersTable WHERE idUser=$array[$i]";
$res = mysql_query($q,$connect) or die(mysql_error());
$new_array = mysqli_fetch_assoc($res);
mysqli_free_result($res);
You do not need that while loop for each row.

Get Column All Values in One Array Using php [duplicate]

This question already has answers here:
How to get one column of mysql_query results into an array?
(4 answers)
Closed 1 year ago.
I have a table my_entity_data in that i have a column parentproduct_id
I want to get all values of that column in side one array
<?php
$result = mysql_query("SELECT parentproduct_id FROM my_entity_data");
$storeArray = Array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$storeArray[] = $row['parentproduct_id'];
}
for ($i=0; $i < 10; $i++) {
echo $storeArray[i];
}
?>
But no use Any thing wrong i did here ?
And i am running this code in Magento CE 1.7
Any ideas ?
I
Thanks to every one finally i got it
<?php
// 1. Enter Database details
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$dbname = 'DB Name';
$connection = mysql_connect($dbhost,$dbuser,$dbpass);
// Check connection
if (!$connection) {
die("Database connection failed: " . mysql_error());
}
$db_select = mysql_select_db($dbname,$connection);
$result = mysql_query("SELECT parentproduct_id FROM my_entity_data");
$storeArray = array();
while ($row = mysql_fetch_array($result)) {
array_push($storeArray,$row['parentproduct_id']);
}
for ($i=0; $i < 10; $i++) {
echo $storeArray[i];
}
//echo sizeof($storeArray);
print_r($storeArray); //to see array data
?>
you can use
Try mysql_fetch_assoc($result);
Below note from: php.net
while ($row = mysql_fetch_assoc($result)) {
foreach ($row as $key => $value) {
$storeArray[$i][$key] = $value;
}
$i++;
}
for ($i=0; $i < 10; $i++) {
echo $storeArray[i];
}
hope this will sure work for you.
Try this
<?php
$result = mysql_query("SELECT parentproduct_id FROM my_entity_data");
$storeArray = array();
while ($row = mysql_fetch_array($result)) {
array_push($storeArray,$row['parentproduct_id']);
}
print_r($storeArray); //to see array data
?>

Create a Json array in a for loop - php

<?php
include '../connection.php';
$sql="SELECT userid,name,batch FROM dbusers";
$results=mysql_query($sql) or die("Cannot execute query");
$count=mysql_num_rows($results);
$arr=array();
for($i=0; $i < $count; $i++){
$rows=mysql_fetch_array($results);
//What to put here ?
}
json_encode($arr);
?>
This is my php code. I want to ask what to put inside the for loop so that I can create a an array of array in php. The inner array will have userid, name and batch as its elements .
What to put here ?
$arr[] = $rows;
Full code
<?php
include '../connection.php';
$sql="SELECT userid,name,batch FROM dbusers";
$results=mysql_query($sql) or die("Cannot execute query");
$count=mysql_num_rows($results);
$arr=array();
for($i=0; $i < $count; $i++){
$rows=mysql_fetch_array($results, MYSQL_ASSOC);//use MYSQL_ASSOC so you wouldn't have duplicate data
$arr[] = $rows;
}
$json = json_encode($arr);
?>
<?php
include '../connection.php';
$sql = "SELECT userid,name,batch FROM dbusers";
$results = mysql_query($sql) or die("Cannot execute query");
$arr = array();
while($rows = mysql_fetch_assoc($results)){
$arr[] = $row;
}
echo json_encode($arr);
?>
try this.

MySQLi not returning rows in order

This is probably not a very difficult question to answer. I'm having trouble with this PHP function I wrote... it returns the rows line by line, but it's returning them incremented by 4 each time. So the the 1st row will output, then the 5th, then the 9th...
function showDatabases() {
# $_GET variables from the URL.
$database = mysql_real_escape_string($_GET['database']);
$table = mysql_real_escape_string($_GET['table']);
$mysqli = new mysqli('127.0.0.1', 'root', '', $database);
$query_one = $mysqli->query("SELECT * from $table");
$num_rows = mysqli_num_rows($query_one);
$num_fields = mysqli_num_fields($query_one);
for ($x = 0; $x < $num_rows; $x++) {
for ($c = 0; $c < $num_fields; $c++) {
$row = mysqli_fetch_row($query_one);
echo($row[$c]." ");
}
echo("<br/>");
}
}
Thanks!
mysqli_fetch_row fetched an entire row and moves the pointer to the following row. You should call it only once per each row; now you are calling it once per column.
That is,
for ($x = 0; $x < $num_rows; $x++) {
$row = mysqli_fetch_row($query_one);
for ($c = 0; $c < $num_fields; $c++) {
echo($row[$c]." ");
}
echo("<br/>");
}
you are complicating things
you can do it with just one loop
$query = "SELECT * from $table";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
echo $row['fieldname']." ";
}
}
I advice you to add order by some time the default order is not the id order.

Categories