returning multiple rows from mysql in php - php

I'm trying to write a PHP-script that will fetch multiple rows from MySQL and return them as a JSONObject, the code works if I try to only fetch 1 row but if I try to get more than one at a time the return string is empty.
$i = mysql_query("select * from database where id = '$v1'", $con);
$temp = 2;
while($row = mysql_fetch_assoc($i)) {
$r[$temp] = $row;
//$temp = $temp +1;
}
If I write the code like this it returns what I expect it to, but if I remove the // from the second row in the while loop it will return nothing. Can anyone explain why this is and what I should do to solve it?

You are using an obsolete mysql_* library.
You are SQL injection prone.
Your code is silly and makes no sense.
If you really wan to stick to it, why simply not do:
while($row = mysql_fetch_assoc($i)) {
$r[] = $row;
}
echo json_encode($r);
And finally, an example using PDO:
$database = 'your_database';
$user = 'your_db_user';
$pass = 'your_db_pass';
$pdo = new \PDO('mysql:host=localhost;dbname='. $database, $user, $pass);
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
try
{
$stmt = $pdo->prepare("SELECT * FROM your_table WHERE id = :id");
$stmt->bindValue(':id', $id);
$stmt->execute();
$results = $stmt->fetchAll(\PDO::FETCH_ASSOC);
}
catch(\PDOException $e)
{
$results = ['error' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine());
}
echo json_encode($results);

You don't need the $temp variable. You can add an element to an array with:
$r[] = $row;

Related

Php pdo foreach

Here I have php pdo function to get json from database
try {
$conn = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result = $conn->prepare("SELECT id_tabele,naziv FROM track_aktivnosti WHERE prvi=:prvi AND id_akt=:id_akt AND tabela=:tabela");
$result->execute(array(':prvi' => $_POST['prvi'], ':id_akt' => $_POST['id_akt'], ':tabela' => $_POST['tabela']));
$result = $result->fetchAll();
foreach($result as $r) {
$temp = array();
$temp[] = array('id' => (int) $r['id_tabele'], 'ime_prezime' => (string) $r['naziv']);
}
$table = $temp;
$jsonTable = json_encode($table);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
echo $jsonTable;
but I get just one result, one element in json etc.
[{"id":1,"ime_prezime":"Pera Peric"}]
other element I can't get. WHY?
I must get json like this:
[{"id":1,"ime_prezime":"Pera Peric"},[{"id":2,"ime_prezime":"Laza Lazic"}] ]
but I get only 1.st element and other not ...
You are overwriting the array inside the foreach on each iteration. This essentially means that the array is emptied on each iteration. The array will only contain the values from the last iteration. Move the $temp = array(); declaration outside the loop to fix this:
$temp = array(); // intialize the array
foreach($result as $r) {
$temp[] = array(
'id' => (int) $r['id_tabele'],
'ime_prezime' => (string) $r['naziv']
);
}
The above fix will make your code work, but I recommend using the approach using SQL aliases as shown in #YourCommonSense's answer below.
You are doing a whole lot of useless operations. It's no wonder why you got lost.
$conn = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
$sql = "SELECT id_tabele id, naziv ime_prezime FROM track_aktivnosti
WHERE prvi=? AND id_akt=? AND tabela=?";
$stmt = $conn->prepare($sql);
$stmt->execute(array($_POST['prvi'], $_POST['id_akt'], $_POST['tabela']));
echo json_encode($result->fetchAll());
declare
$temp = array();
out side the loop since you have this inside the loop and on each iteration its declared as new array and previous entries are wiped.
i.e.
$temp = array();
foreach($result as $r) {
$temp[] = array('id' => (int) $r['id_tabele'], 'ime_prezime' => (string) $r['naziv']);
}

Using PHP to query a MDB file, and return JSON

I have a Microsoft Access Database, and I am trying to query the table using PHP, and output valid JSON. I have an equivalent code for a MSSQL database, am I am trying to make my code do the same thing, but just for the Access database.
Here is the MSSQL code
$myServer = "server";
$myDB = "db";
$conn = sqlsrv_connect ($myServer, array('Database'=>$myDB));
$sql = "SELECT *
FROM db.dbo.table";
$data = sqlsrv_query ($conn, $sql);
$result = array();
do {
while ($row = sqlsrv_fetch_array ($data, SQLSRV_FETCH_ASSOC)) {
$result[] = $row;
}
} while (sqlsrv_next_result($data));
$json = json_encode ($result);
sqlsrv_free_stmt ($data);
sqlsrv_close ($conn);
Here is what I tried for the MDB file
$dbName = "/filename.mdb";
if (!file_exists($dbName)) {
die("Could not find database file.");
}
$db = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$dbName", $user, $password);
$sql = "SELECT *
FROM cemetery";
$data = $db->query($sql); // I'm getting an error here
$result = array();
// Not sure what do do for this part...
do {
while ($row = fetch($data, SQLSRV_FETCH_ASSOC)) {
$result[] = $row;
}
} while (sqlsrv_next_result($data));
$json = json_encode ($result);
I kind of followed this to try to connect to the database: http://phpmaster.com/using-an-access-database-with-php/
Currently this is giving me a 500 Internal Server Error. I'm expecting a string such as this to be saved in the variable $json
[
{
"col1":"col value",
"col2":"col value",
"col3":"col value",
},
{
"col1":"col value",
"col2":"col value",
"col3":"col value",
},
{
etc...
}
]
Can someone help me port the MSSQL code I have above so I can use it with an MDB database? Thanks for the help!
EDIT: I'm commenting out the lines one by one, and it throws me the 500 error at the line $data = $db->query($sql);. I looked in the error log, and I'm getting the error Call to a member function query() on a non-object. I already have the line extension=php_pdo_odbc.dll uncommented in my php.ini file. Anyone know what the problem could be?
You only need 1 loop,
fetchAll is your iterable friend:
while ($row = $data->fetchAll(SQLSRV_FETCH_ASSOC)) {
$result[] = $row;
}
odbc_connect doesn't return an object, it returns a resource. see (http://php.net/manual/en/function.odbc-connect.php) so you would need to do something like this.
$db = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$dbName", $user, $password);
$oexec = obdc_exec($db,$sql);
$result[] = odbc_fetch_array($oexec);
and then you can iterate over results..
see also:
http://www.php.net/manual/en/function.odbc-fetch-array.php
http://www.php.net/manual/en/function.odbc-exec.php
I finally figured it out.
<?php
// Location of database. For some reason I could only get it to work in
// the same location as the site. It's probably an easy fix though
$dbName = "dbName.mdb";
$tName = "table";
// Throws an error if the database cannot be found
if (!file_exists($dbName)) {
die("Could not find database file.");
}
// Connects to the database
// Assumes there is no username or password
$conn = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$dbName", '', '');
// This is the query
// You have to have each column you select in the format tableName.[ColumnName]
$sql = "SELECT $tName.[ColumnOne], $tName.[ColumnTwo], etc...
FROM $dbName.$tName";
// Runs the query above in the table
$rs = odbc_exec($conn, $sql);
// This message is displayed if the query has an error in it
if (!$rs) {
exit("There is an error in the SQL!");
}
$data = array();
$i = 0;
// Grabs all the rows, saves it in $data
while( $row = odbc_fetch_array($rs) ) {
$data[$i] = $row;
$i++;
}
odbc_close($conn); // Closes the connection
$json = json_encode($data); // Generates the JSON, saves it in a variable
?>
I use this code to get results from an ODBC query into a JSON array:
$response = null;
$conn = null;
try {
$odbc_name = 'myODBC'; //<-ODBC connectyion name as is in the Windows "Data Sources (ODBC) administrator"
$sql_query = "SELECT * FROM table;";
$conn = odbc_connect($odbc_name, 'user', 'pass');
$result = odbc_exec($conn, $sql_query);
//this will show all results:
//echo odbc_result_all($result);
//this will fetch row by row and allows to change column name, format, etc:
while( $row = odbc_fetch_array($result) ) {
$json['cod_sistema'] = $row['cod_sistema'];
$json['sistema'] = $row['sistema'];
$json['cod_subsistema'] = $row['cod_subsistema'];
$json['sub_sistema'] = $row['sub_sistema'];
$json['cod_funcion'] = $row['cod_funcion'];
$json['funcion'] = $row['funcion'];
$json['func_desc_abrev'] = $row['desc_abreviada'];
$json['cod_tipo_funcion'] = $row['cod_tipo_funcion'];
$response[] = array('funcionalidad' => $json);
}
odbc_free_result($result); //<- Release used resources
} catch (Exception $e) {
$response = array('resultado' => 'err', 'detalle' => $e->getMessage());
echo 'ERROR: ', $e->getMessage(), "\n";
}
odbc_close($conn);
return $response;
And finnally encoding the response in JSON format:
echo json_encode($response);

Run a call from a function PHP

i'm building an website using php and html, im used to receiving data from a database, aka Dynamic Website, i've build an CMS for my own use.
Im trying to "simplify" the receiving process using php and functions.
My Functions.php looks like this:
function get_db($row){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$row = $stmt->fetchAll();
foreach ($row as $row) {
echo $row['session_id'] . ", ";
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
}
Where i will get the rows content like this: $row['row'];
I'm trying to call it like this:
the snippet below is from the index.php
echo get_db($row['session_id']); // Line 22
just to show whats in all the rows.
When i run that code snippet i get the error:
Notice: Undefined variable: row in C:\wamp\www\Wordpress ish\index.php
on line 22
I'm also using PDO just so you would know :)
Any help is much appreciated!
Regards
Stian
EDIT: Updated functions.php
function get_db(){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
echo $row['session_id'] . ", ";
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
}
Instead of echoing the values from the DB, the function should return them as a string.
function get_db(){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
$result = '';
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
$result .= $row['session_id'] . ", ";
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
return $result;
}
Then call it as:
echo get_db();
Another option would be for the function to return the session IDs as an array:
function get_db(){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
$result = array();
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
$result[] = $row['session_id'];
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
return $result;
}
Then you would use it as:
$sessions = get_db(); // $sessions is an array
and the caller can then make use of the values in the array, perhaps using them as the key in some other calls instead of just printing them.
As antoox said, but a complete changeset; change row to rows in two places:
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
echo $row['session_id'] . ", ";
}
Putting this at the start of the script after <?php line will output interesting warnings:
error_reporting(E_ALL|E_NOTICE);
To output only one row, suppose the database table has a field named id and you want to fetch row with id=1234:
$stmt = $pdo->prepare("SELECT * FROM lp_sessions WHERE id=?");
$stmt->bindValue(1, "1234", PDO::PARAM_STR);
I chose PDO::PARAM_STR because it will work with both strings and integers.

Getting multiple rows with prepared statement [duplicate]

This question already has answers here:
Call to undefined method mysqli_stmt::get_result
(10 answers)
Closed 11 months ago.
I'm quite new to prepared statements and am not sure I am doing this right.
Here is what I try:
$currgame = 310791;
$sql = "SELECT fk_player_id, player_tiles, player_draws, player_turn, player_passes, swapped FROM ".$prefix."_gameplayer WHERE fk_game_id = ?";
$stmt = $mysqli->stmt_init();
$data = array();
if($stmt->prepare($sql)){
$stmt->bind_param('i', $currgame);
$stmt->execute();
$fk_player_id = null; $player_tiles = null; $player_draws = null; $player_turn = null; $player_passes = null; $swapped = null;
$stmt->bind_result($fk_player_id, $player_tiles, $player_draws, $player_turn, $player_passes, $swapped);
$res = $stmt->get_result();
while ($row = $res->fetch_assoc()){
$data[] = $row;
}
$stmt->close();
}
// to display own games
foreach ($data as $row) {
if ($row['fk_player_id'] == $playerid) {
$udraws = $row['player_draws']+1;
$upass = $row['player_passes'];
$uswaps = $row['swapped'];
echo 'uDraws: '.$udraws.'<br>';
echo 'uPass: '.$upass.'<br>';
echo 'uSwaps: '.$uswaps.'<br><br>';
}
}
// to display other games
foreach ($data as $row) {
if ($row['fk_player_id'] != $playerid) {
$opponent = $row['fk_player_id'];
$oppTiles = $row['player_tiles'];
$odraws = $row['player_draws']+1;
$opass = $row['player_passes'];
$oswaps = $row['swapped'];
echo 'oID: '.$opponent.'<br>';
echo 'oTiles: '.$oppTiles.'<br>';
echo 'oDraws: '.$odraws.'<br>';
echo 'oPass: '.$opass.'<br>';
echo 'oSwaps: '.$oswaps.'<br><br>';
}
}
I get an "ServerError" when trying to run this: It is the $res = $stmt->get_result(); that makes the error, but not sure why.
PHP Fatal error: Call to undefined method mysqli_stmt::get_result() in /home/mypage/public_html/TEST/preparedstatement.php on line 61
Depending on your PHP/MySQL setup you may not be able to use get_result().
The way to get around this is to bind the results.
For example:
$stmt->execute();
$fk_player_id = null; $player_tiles = null; $player_draws = null; $player_turn = null; $player_passes = null; $swapped = null;
$stmt->bind_result($fk_player_id, $player_tiles, $player_draws, $player_turn, $player_passes, $swapped);
while ($stmt->fetch()) { // For each row
/* You can then use the variables declared above, which will have the
new values from the query every time $stmt->execute() is ran.*/
}
For more information click here
Since I don't see it in your code, make sure you're instantiating the mysqli object before trying to query on it:
$mysqli = new mysqli("127.0.0.1", "user", "password", "mydb");
if($mysqli->connect_error){
die("$mysqli->connect_errno: $mysqli->connect_error");
}
Also, a ServerError would certainly show up in your logs and point you in the right direction.
while (mysqli_stmt_fetch($stmt)) {
printf ("%s (%s)\n", $name, $code);
}
This might help you:
http://php.net/manual/en/mysqli-stmt.fetch.php

mysql_fetch_array within while loop is working in localhost but not working in host server

$result = mysql_query('SELECT * FROM phpfox_education_question where subject_id = 2 and ques_id =1');
var_dump($result);
//var_dump result is :- "resource(64) of type (mysql result)" in localhost and web host,but
while($row = mysql_fetch_array($result))
{
var_dump($row); //**NOTHING DISPLAYED in web host server but in localhost**
}
Give this a try:
$query = "SELECT * FROM phpfox_education_question WHERE subject_id = '2' AND ques_id = '1'";
$result = mysql_query($query) or die(mysql_error()); // <--- added this
echo "Results: ".mysql_num_rows($result)."<br />"; // <--- added this to output result count
while($row = mysql_fetch_array($result))
{
print_r($row); //**NOTHING DISPLAYED in web host server but in localhost**
}
This is used depreciated code btw
Try adding this:
var_dump(mysql_num_rows($result));
To see if there are any rows to be fetched, if not, that's your answer.BTW, in PDO this code looks like this:
$db = new PDO('mysql:dbname=default_db_name;host=127.0.0.1',$user,$pass);
//use prepared statmenets
$stmt = $db->prepare('SELECT * FROM your_db.phpfox_education_question WHERE subject_id = :subject_id AND ques_id = :ques_id');
//pass binds when executing the stmt
$stmt->execute(array(':subject_id' => 2, ':ques_id' => 1));
//number of rows found:
var_dump($stmt->rowCount());
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{//fetch rows as assoc array
var_dump($row);
}
Note that this is a basic example, there's a lot more you can do with PDO
Update:
To get more debugging info, try this:
try
{
$db = new PDO();//connect, pass correct data here
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);//cause PDO to throw PDOExceptions on error
$stmt = $db->prepare('SELECT * FROM your_db.phpfox_education_question WHERE subject_id = :subject_id AND ques_id = :ques_id');
$stmt->execute(array(':subject_id' => 1, ':ques_id' => 2));
var_dump($stmt->rowCount());
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
var_dump($row);
}
}
catch(PDOException $e)
{
echo $e->getMessage();
$db = null;
return;
}
echo 'No problems with query<br/>';
$db = null;//disconnecto
Make sure no errors are being thrown, if there are, check the messages, find out what is going wrong and fix it. If you can't find a way to fix them, we're here to help, of course.

Categories