I wrote the PHP code below to get multiple JSON objects from my database:
<?php
$connection = new mysqli("localhost","root","","Fubon");
$dateCheckSQLCommand = $connection->prepare("select * from clockindata where Month(date)= 11 ");
$dateCheckSQLCommand -> execute();
$result = $dateCheckSQLCommand->get_result();
$rowOfDate = $result->fetch_assoc();
echo json_encode($rowOfDate);
I expect to get two JSON objects when I run the PHP file like below because I have two month 11 data matching in My MySQL:
[{"account":"Fu","ssid":"Fu","date":"2019-11-14 00:00:00"},{"account":"Fu","ssid":"Fu","date":"2019-11-21 00:00:00"}]
But I only get one JSON object like below:
{"account":"Fu","ssid":"Fu","date":"2019-11-14 00:00:00"}
How to solve the problem?
You need to fetch each row in your result. You're only calling fetch_assoc() once in your code. You need to either loop until fetch_assoc() returns false, or use fetch_all() (which is supported only by the mysqlnd driver.)
$connection = new mysqli("localhost","root","","Fubon");
$dateCheckSQLCommand = $connection->prepare("select * from clockindata where Month(date)= 11 ");
$dateCheckSQLCommand -> execute();
$result = $dateCheckSQLCommand->get_result();
/*** either this ****/
while($row = $result->fetch_assoc()) {
$rowOfDate[] = $row;
}
/*** or this, if it's supported ***/
$rowOfDate = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($rowOfDate);
The best solution, though, will involve changing the database API you're using. Mysqli is not very user friendly, and was written as a low-level one-to-one mapping of MySQL's C API. Even using PDO, which is PHP's other built-in database API, will make your code much easier to work with. Here's how that would look, including a parameterized query for safety:
$month = 11;
$db = new PDO("mysql:host=localhost;dbname=Fubon", "root", "of course you have a password");
$stmt = $db->prepare("SELECT * FROM clockindata WHERE MONTH(`date`) = ?");
$stmt->execute([$month]);
$data = $stmt->fetchAll(\PDO::FETCH_ASSOC);
// if your script is outputting JSON, set the MIME type appropriately
header("Content-Type: application/json");
echo json_encode($data);
Especially when you're using parameters in your query (which you already are, of course, right?) PDO becomes far easier to use than Mysqli.
Related
I want to fetch data from my mySQL db row by row so that I can combine the first column with the second and so on in a list.
I've searched and found solutions but none of them are using PDO.
Here's the php code that I'm using now to give me the first value written to the console with AJAX.
$db = new PDO('mysql:host=XXXXX;dbname=XXXXX;charset=utf8', 'XXXXX',
'XXXXX');
$partyID = ($_POST['paramName']);
$stmt = $db->prepare("SELECT * FROM wapp_Wishes_db WHERE partyID = '$partyID'");
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rows[0]);
I've also tried using Fetch_assoc, but as you can see I'm probably using it completely wrong.
Why would you like to combine those rows? Encode them and use the variables in javascript:
$stmt = $db->prepare("SELECT *
FROM wapp_Wishes_db
WHERE partyID = :partyId");
$stmt->bindParam(':partyId', $_POST['paramName'], PDO::PARAM_STR, 12);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rows);
Maybe you can use implode like that :
$result = implode('&',$rows);
echo json_encode($result);
replace '&' by what you want.
More info here on php manual
I have a database that I am trying to query to get information to display to my user. I have used
fetch(PDO::FETCH_ASSOC)
before when retrieving a single row or
$row = mysql_fetch_array($result)
with good results. However, it is my understanding that it is better practice to use PDO so that is what I am trying to do.
The problem I am running into is that my results are only showing me the first row of the data I need. In this instance it is displaying the column header over and over and never giving me the data.
$stmt = $conn->prepare("SELECT ? FROM application");
$stmt->bindparam(1, $application_ID);
$stmt->execute();
$results = $stmt->fetchall(PDO::FETCH_ASSOC);
foreach($results as $row){
echo $row['application_ID'];
}
Here are the results
application_IDapplication_IDapplication_IDapplication_ID
It is good that you are aware that MySQL has been oficially deprecated and now we are supposed to used MySQLi or better yet, PDO.
Since you are not accepting any user input, there is no need of using a prepared statement.
Simply do this:
$stmt = $conn->query("SELECT * FROM application");
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($results as $row){
echo $row['application_ID'];
//output other rows here
}
As per the php documentation pdo::fetchAll
you have to use fetchAll, instead of fetchall.
I'm trying this code:
if ($result = $this->mysqli->prepare("SELECT * FROM `mytable` WHERE `rows1`=?"))
{
$result->bind_param("i",$id);
$result->execute();
while ($data = $result->fetch_assoc())
{
$statistic[] = $data;
}
echo "<pre>";
var_dump($statistic);
echo "</pre>";
}
but it's throwing the following error
[Fri Jun 15 12:13:11 2012] [error] [client 127.0.0.1] PHP Fatal error:
Call to undefined method mysqli_stmt::fetch_assoc() in [myfile.php]
And also I've tried:
if ($result = $this->mysqli->prepare("SELECT * FROM `mytable` WHERE `rows1`=?"))
{
$result->bind_param("i",$id);
$rows = $result->execute();
while ($data = $rows->fetch_assoc())
{
$statistic[] = $data;
}
echo "<pre>";
var_dump($statistic);
echo "</pre>";
}
that makes this:
[Fri Jun 15 12:22:59 2012] [error] [client 127.0.0.1] PHP Fatal error:
Call to a member function fetch_assoc() on a non-object in
[myfile.php]
What else I can do for getting result or what I doing wrong? I need the assoc array from DB looking like $data[0]["id"] = 1
In fact you can do this quite easily, you just can't do it with the mysqli_stmt object, you have to extract the underlying mysqli_result, you can do this by simply calling mysqli_stmt::get_result(). Note: this requires the mysqlnd (MySQL Native Driver) extension which may not always be available.
However, the point below about recommending PDO over MySQLi still stands, and this is a prime example of why: the MySQLi userland API makes no sense. It has taken me several years of intermittently working with MySQLi for me to discover the mechanism outlined above. Now, I'll admit that separating the statement and result-set concepts does make sense, but in that case why does a statement have a fetch() method? Food for thought (if you're still sitting on the fence between MySQLi and PDO).
For completeness, here's a code sample based (loosely) on the original code in the question:
// Create a statement
$query = "
SELECT *
FROM `mytable`
WHERE `rows1` = ?
";
$stmt = $this->mysqli->prepare($query);
// Bind params and execute
$stmt->bind_param("i", $id);
// Extract result set and loop rows
$result = $stmt->get_result();
while ($data = $result->fetch_assoc())
{
$statistic[] = $data;
}
// Proof that it's working
echo "<pre>";
var_dump($statistic);
echo "</pre>";
You can do:
$stmt = $this->mysqli->prepare("SELECT * FROM `mytable` WHERE `rows1`=?");
$stmt->bind_param("i",$id);
$stmt->execute();
$result = $stmt->get_result();
$statistic = $result->fetch_all(MYSQLI_ASSOC);
$statistic contains all the result in a 2-dimensional array.
*It should be noted that this mysqli_fetch_all() function only works with the mysqlnd package.
http://php.net/manual/en/mysqli-result.fetch-all.php
I don't like Mysqli, but you can do it like this on prepare.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli('hostAddress', 'username', 'password', 'databaseName');
$db->set_charset('utf8mb4');
$userID = 2;
$stmt = $db->prepare("SELECT * FROM users WHERE ID = ?");
$stmt->bind_param("i", $userID);
// because the variable is bound by reference you can assign the value after binding, too
//$userID = 2;
$stmt->execute();
if you want result;
$result = $stmt->get_result();
$user = $result->fetch_array(MYSQLI_ASSOC); //one row
or multiple row
$users = $result->fetch_all(MYSQLI_ASSOC);
With a prepared statement you don't need an array but you are free to use it.
Use the bind_result method of mysqli_stmt and you won't have any trouble.
In bind_result you defined the variables where the values of the columns should be stored in the same order as you request them from the database. You can use native variables or array keys to do so. see php docs mysqli_stmt::bind_result
You ask what's wrong with your code it is the misuse of $result->execute.
$result->execute() returns a boolean and not an instance mysqli_result as expected by you. see php docs mysqli_stmt::execute
Let's assume your database table `mytable` has the following columns: id (int), field1 (varchar), field2 (date)
Then the code would look like this:
// Initialize the array with some default values if you really want to use an array
$data = array('id'=>0,'field1'=>'','field2'=>'');
/* I recommend to explicitly define which columns you want to retrieve so you don't have to rely that the columns in the database are set in the desired order and on otherhand it doesn't matter if the database table has more columns that you want to retrieve, the code will still work as long as the columns with this names exist.*/
if ($result = $this->mysqli->prepare("SELECT `id`,`field1`,`field2` FROM `mytable` WHERE `rows1`=?"))
{
$result->bind_param("i",$id);
$result->bind_result("iss", $data['id'], $data['field1'], $data['field2']);
$result->execute();
while($result->fetch())
{
$statistic[] = $data;
}
echo "<pre>";
var_dump($statistic);
echo "</pre>";
}
I have a MySQL list with a few categories and a lot of rows of data. I want to simply output that in PHP/HTML. How would I do that?
<?php
$query = "SELECT * FROM TABLE";
$res = mysql_query($query,$connection);
while($row = mysql_fetch_array($res)) {
print_r($row);
}
?>
To expand on what was already said: http://www.anyexample.com/programming/php/php_mysql_example__display_table_as_html.xml
This will produce a nice html table out of a query.
Please note that the mysql_* functions, as offered by some answers to this question, have been deprecated for quite some time. It is recommended to use either the mysqli_* functions (MySql Improved, which uses a newer underlying library for accessing mysql), or the PDO (PHP Data Objects, an object-oriented interface for connecting to various databases).
For example:
// Create a new PDO connection to localhost.
$dbh = new PDO("mysql:localhost;dbname=testdb", $user, $password);
// Create a PDO Statement object based on a query.
// PDO::FETCH_ASSOC tells PDO to output the data as an associative array.
$stmt = $dbh->query("SELECT * FROM Table", PDO::FETCH_ASSOC);
// Iterate over the statement, using a simple foreach
foreach($stmt as $row) {
echo $row['column1'].' and '.$row['column2'];
}
Sample code:
$infoArray = array();
require_once("connectAndSelect.php");
// Connects to mysql and selects the appropriate database
$sql = "SOME SQL";
if($results = mysql_query($sql))
{
while($result = mysql_fetch_array($results, MYSQL_ASSOC))
{
$infoArray[] = $result;
}
}
else
{
// Handle error
}
echo("<pre>");
print_r($infoArray);
echo("</pre>");
In this sample code, I simply want to get the result of my query in $infoArray. Simple task, simple measures... not.
I would have enjoyed something like this:
$sql = "SOME SQL";
$infoArray = mysql_results($sql);
But no, as you can see, I have two extra variables and a while loop which I don't care for too much. They don't actually DO anything: I'll never use them again. Furthermore, I never know how to call them. Here I use $results and $result, which kind of represents what they are, but can also be quite confusing since they look so much alike. So here are my questions:
Is there any simpler method that I
don't know about for this kind of
task?
And if not, what names do you
give those one-use variables? Is
there any standard?
The while loop is really only necessary if you are expecting multiple rows to be returned. If you are just getting one row you can simply use mysql_fetch_array().
$query = "SOME SQL";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
For single line returns is the standard I use. Sure it is a little clunky to do this in PHP, but at least you have the process broken down into debug-able steps.
Use PDO:
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'username';
/*** mysql password ***/
$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=mysql", $username, $password);
$sql = "SELECT * FROM myTable";
$result = $dbh->query($sql)
//Do what you want with an actual dataset
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
Unless you are legacied into it by an existing codebase. DONT use the mysql extension. Use PDO or Mysqli. PDO being preferred out of the two.
Your example can be come a set of very consise statements with PDO:
// create a connection this could be done in your connection include
$db = new PDO('mysql:host=localhost;dbname=your_db_name', $user, $password);
// for the first or only result
$infoArray = $db->query('SOME SQL')->fetch(PDO::FETCH_ASSOC);
// if you have multiple results and want to get them all at once in an array
$infoArray = $db->query('SOME SQL')->fetchAll(PDO::FETCH_ASSOC);
// if you have multiple results and want to use buffering like you would with mysql_result
$stmt = $db->query('SOME SQL');
foreach($stmt as $result){
// use your result here
}
However you should only use the above when there are now variables in the query. If there are variables they need to be escaped... the easiest way to handle this is with a prepared statement:
$stmt = $db->prepare('SELECT * FROM some_table WHERE id = :id');
$stmt->execute(array(':id' => $id));
// get the first result
$infoArray = $stmt->fetch(PDO::FETCH_ASSOC);
// loop through the data as a buffered result set
while(false !== ($row = $stmt->fetch(PDO::FETCH_ASSOC))){
// do stuff with $row data
}