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>'];
?>
Related
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.
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.
`
I am developing a web service using PHP. I am having some trouble while executing the select query. This is the code I'm using.
DB_Functions.php
public function getCompanies() {
$result = mysql_query("SELECT * FROM company");
// check for successful store
if ($result) {
return mysql_fetch_array($result,true);
} else {
return false;
}
}
GetCompanies.php
<?php
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
$companies = array();
//$rows = $db->getCompanies();
while ($row = $db->getCompanies()) {
echo $row['companyName'];
$rowArr = array();
$rowArr['CompanyName'] = $row['companyName'];
$rowArr['CompanyID'] = $row['companyId'];
//array_push($companies, $rowArr);
$companies[] = $rowArr;
}
header('Content-Type: application/json');
$response=array("Companies"=>$companies);
$json = json_encode($response);
echo $json
?>
But the problem is in GetCompanies.php file the while loop is runs endless. The code appears to be ok. Any help would be appreciated.
When you do while ($row = $db->getCompanies()) { you are running the entire query over again and returning the 1st row each time. mysql_fetch_array returns one row.
What you need to do is have getCompanies() loop over all the rows and return an array.
public function getCompanies() {
$result = mysql_query("SELECT * FROM company");
// check for successful store
if ($result) {
$ret = array();
while($row = mysql_fetch_assoc($result)){
$ret[] = $row;
}
return $ret;
} else {
return false;
}
}
Now, getCompanies() will return you an array that you can just foreach over:
$rows = $db->getCompanies();
foreach($rows as $row){
// ...
}
Change your while loop declaration to something like
foreach($rows as $row) {}
And as Pavlin said, move the function call to getCompanies() outside the loop.
Also, how about modifying the query to select a particular set of fields from the database and directly sending them as the response without doing any additional processing?
Since you are implementing Select query without any condition(where clause). And since the company table has data it would always return true in the while loop this makes the while loop an infinite loop. For while to work properly the condition should become false to exit the loop.
Its not a programming flaw its a logical one.
The php docs have all the information you need. You're using the wrong function:
mysqli_fetch_array — Fetch a result row as an associative, a numeric
array, or both
vs
mysqli_fetch_all — Fetches all result rows as an associative array, a
numeric array, or both
Just change your return statement to
return mysqli_fetch_all($result);
or
return mysqli_fetch_all($result, MYSQLI_ASSOC);
to get an associative array.
And of course, you need to move your getCompanies call outside of the loop.
NOTE
php mysql_* functions have been depricated since version 5.5.* and are going to be removed from the language soon. You should look into mysqli_* or PDO.
I am having a problem. The following code works fine in my local, but on the live server, it's not working properly..I was supposed to get two rows, but on the live server I am getting only 1 result.
$query = mysql_query('SELECT * FROM `wspm_t_colors`');
$result = mysql_fetch_object($query);
print json_encode($result);
What could possibly be the error ?...
I can't believe you get two rows with this, to get all rows you have to do like this:
$query = mysql_query('SELECT * FROM `wspm_t_colors`');
while($result = mysql_fetch_object($query))
{
print json_encode($result);
}
mysql_fetch_object/array/row always returns only one row and moves the pointer to the next row, if there is no next row it returns false.
Your code is only getting one row. The mysql_fetch_object() function only returns one row. You need to try something like this:
$query = mysql_query('SELECT * FROM `wspm_t_colors`');
$json = array();
while ($result = mysql_fetch_object($query))
$json[] = $result;
print json_encode($json);
I think this is because mysql_fetch_object only returns a single row result. You need something like this:
$query = mysql_query('SELECT * FROM `wspm_t_colors`');
while($row = mysql_fetch_array($query))
{
\\access each result here
}
I can't see how you can have two rows in local
$array = array();
$query = mysql_query('SELECT * FROM `wspm_t_colors`');
while($result = mysql_fetch_object($query))
{
$array[] = $result;
}
print json_encode($array);
I want to make a simple function that I can call on to query my database. I pass the "where" part of the query to it and in the code below, my $q variable is correct. However, what should I then do to be able to use the data? I'm so confused at how to do something I'm sure is extremely easy. Any help is greatly appreciated!
function getListings($where_clause)
{
$q = "SELECT * FROM `listings` $where_clause";
$result = mysql_query($q,$dbh);
foreach (mysql_fetch_array($result) as $row) {
$listingdata[] = $row;
}
return $listingdata;
}
Your function should be like this:
function getListings($where_clause, $dbh)
{
$q = "SELECT * FROM `listings` $where_clause";
$result = mysql_query($q, $dbh);
$listingdata = array();
while($row = mysql_fetch_array($result))
$listingdata[] = $row;
return $listingdata;
}
Improvements over your function:
Adds MySQL link $dbh in function arguments. Passit, otherwise query will not work.
Use while loop instead of foreach. Read more here.
Initialize listingdata array so that when there is no rows returned, you still get an empty array instead of nothing.
Do you have a valid db connection? You'll need to create the connection (apparently named $dbh) within the function, pass it in as an argument, or load it into the function's scope as a global in order for $result = mysql_query($q,$dbh); to work.
You need to use while, not foreach, with mysql_fetch_array, or else only the first row will be fetched and you'll be iterating over the columns in that row.
$q = "SELECT * FROM `listings` $where_clause";
$result = mysql_query($q,$dbh);
while (($row = mysql_fetch_array($result)) != false)
{
$listingdata[] = $row;
}
Always add error handling in your code. That way you'll see what is going wrong.
$result = mysql_query($q,$dbh);
if (!$result) {
trigger_error('Invalid query: ' . mysql_error()." in ".$q);
}
Here is a function which will save you some time. First Argument tablename, then condition(where), fields and the order. A simple query will look like this : query_db('tablename');
function query_db($tbl_name,$condition = "`ID` > 0",$fields = "*",$order="`ID` DESC"){
$query="SELECT ".$fields." FROM `".$tbl_name."` WHERE ".$condition." ORDER BY".$order;
$query=$con->query($query);
$row_data=array();
while($rows = $query->fetch_array()){
$row_data[] = $rows;
}
return $row_data;
}