MySQL SELECT Command does find one entry less - php

here is my problem.
function getSent($id) {
include 'dbh.php';
$data = array();
$sql = "SELECT * from message WHERE senderid='$id'";
$result = $con->query($sql);
$row = $result->fetch_assoc();
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
return $data;
}
In the theory this method is picking all messages (in this case), but it always find one message less than in the db => If I drop the whole table, I will get an array with the size of 0.
How could I fix this?

Remove the first $row = $result->fetch_assoc();. You are fetching one row, then looping to fetch the rest of the data and you don't store the first fetch.
`

Related

echoing a result from the database with php only returns 1 result

I'm trying to get results from a database and return the data to my page.
I have 2 files, findtask, and functions.
In functions I have some code that grabs all my data from the table.
I then used a while loop to grab the stuff if I echo the results from the functions script it returns as it should id 1 2 and 3, my issue starts when trying to get the result from findtask script that only gets last result.
<?php
public function ShowOpenTasks ()
{
//i leave usersemail blank, because i only want tasks to show on this page if there not assigned.
$query = "SELECT * FROM `tasks` WHERE `usersemail` = ''";
if(!$result = mysqli_query($this->db, $query)) {
exit(mysqli_error($this->db));
}
$data = [];
if(mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$data = $row;
echo $data['id'];
}
}
return $data;
}
?>
My findtask page is
require __DIR__ . '/lib/functions.php';
$app = new FunctionClass();
$task = $app->ShowOpenTasks();
echo $task['id'] //id being the name of the id table of the task.
This one will only turn the last id for some reason.
What is wrong and how can this be fixed?
It will only return last id since you are setting data to equal row
$data = $row;
So each row you replace it with the last one.
I guess you want an array instead, so you could do:
$data[] = $row;
then to print out all tasks:
$task = $app->ShowOpenTasks();
print_r($task);
This would give you an array of results.

Half of data lost on JSON conversion?

I have a mysql database of countries, 250 in total, which in want to give over to an Android app. I know i have to use php in between to parse the result into JSON. This is it:
<?php
require_once('connection.php');
$response = array();
$resultarray = array();
$result = mysqli_query($con, "SELECT * FROM countries");
if (!empty($result)) {
// check for empty result
while ($row=mysqli_fetch_assoc($result)) {
print $row;
$resultarray = mysqli_fetch_array($result);
$Laender = array();
$Countries[de] = $resultarray["de"];
$response["Countries"] = array();
array_push($response["Countries"], $Countries);
echo json_encode($response);
}
}
?>
I ran the script in my browser and it displays correctly, except that half the countries are missing. There are only 125 countries displayed. Where have they vanished to?
Both functions mysqli_fetch_assoc and mysqli_fetch_array do the same - they fetch next record.
So, in your while you fetch first record with mysqli_fetch_assoc and then immediately fetch second record with mysqli_fetch_array. So, the first record is lost. And this happens on every iteration, so half of your records are lost.
Get rid of mysqli_fetch_array call:
$response["Countries"] = array();
while ($row = mysqli_fetch_assoc($result)) {
array_push($response["Countries"], $row["de"]);
}
echo json_encode($response);

how to get db all data using array in php

I create as the following function. how to get all data using this array. when run this function will appear only the first record. but, i want it to appear all the records. what is the error in this code.
public function get_All_Se($stId){
$query = "SELECT * FROM session WHERE stId = '$stId'";
$result = $this->db->query($query) or die($this->db->error);
$data = $result->fetch_array(MYSQLI_ASSOC);
return $data;
}
public function get_All_Se($stId){
$rows=array();
$query = "SELECT * FROM session WHERE stId = '$stId'";
$result = $this->db->query($query) or die($this->db->error);
while($data= $result->fetch_assoc()){
$rows[]=$data;
}
return $rows;
}
Run loop over all results and add to some return array.
$rows = array();
while(($row = $result->fetch_array($result))) {
$rows[] = $row;
}
As the documentation of mysqli::fetch_array() explains, it returns only one row (and not an array containing all the rows as you might think).
The function you are looking for is mysqli::fetch_all(). It returns all the rows in an array.
public function get_All_Se($stId)
{
$query = "SELECT * FROM session WHERE stId = '$stId'";
$result = $this->db->query($query) or die($this->db->error);
return $result->fetch_all(MYSQLI_ASSOC);
}
The code above still has two big issues:
It is open to SQL injection. Use prepared statements to avoid it.
or die() is not the proper way to handle the errors. It looks nice in a tutorial but in production code it is a sign you don't care about how your code works and, by extension, what value it provides to their users. Throw an exception, catch it and handle it (log the error, put some message on screen etc) in the main program.
Try this way...
<?php
// run query
$query = mysql_query("SELECT * FROM <tableName>");
// set array
$array = array();
// look through query
while($row = mysql_fetch_assoc($query)){
// add each row returned into an array
$array[] = $row;
// OR just echo the data:
echo $row['<fieldName>']; // etc
}
// debug:
print_r($array); // show all array data
echo $array[0]['<fieldName>'];
?>

mysqli - How to fetch a row without modifying the result set?

Is it possible to extract a value from mysqli_result without fetching a row i.e. without modifying the result set as I need it in full later in my code?
You can also point the iterator back to the beginning. ie..
$result = $mysqli->query($query);
while($row = $result->fetch_assoc())
{
//do stuff with the result
}
//back to the start
mysqli_data_seek($result,0);
now the pointer is returned to the beginning. mysqli_data_seek
You can get all and store in an array…
$results = [];
$sql = mysqli_query($con,"SELECT * FROM WHATEVER");
while ($row = mysqli_fetch_array($sql)) {
array_push($results, $row);
}
//Now $results is fully populated

PHP Create new array per row of MYSQL Info, and store the arrays in a array

Don't ask me why I need it, I've tried to find it on the web and have failed.
I need it to find rows of info on my database and per row it creates a array with one row and stores that array in an array and carries on with the rest of the rows.
I will then generate a new word doc per array found in the array of arrays( I can do this myself.)
I'm sorry I don't make much sense, I don't really know how to explain this...
Do you mean:
$sql = "SELECT * FROM tbl";
$query = mysql_query($query, $connection);
$rows = array();
while ($row = mysql_fetch_array($query)) {
$rows[] = $row;
}
// You now have an array of your DB rows in $rows
foreach ($rows as $row) {
createWordDoc($row);
}
If you don't actually need to cache the rows you could do this directly in your first loop of course:
$rows = array();
while ($row = mysql_fetch_array($query)) {
createWordDoc($row);
}

Categories