I already create an apps that contain ListView. I uses PHP to connect between android and database. FOr now, I use MySQLi and it works. But when I convert to PDO, the data not displayed. I uses 'Log.d' to trace what the data got. Below is the result:
MySQLi (No error) - {"data":[{"report_id":19,"task_name":"ngantuk","badgeid":"12345","report_date":"04 Dec 2019",.......
PDO (not log show data)
Now, below is current code for MySQLi and PDO
MySQLi
<?php
require_once 'config.php';
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}
$badgeid = $_GET["badgeid"] ?? "";
$stmt = $conn->prepare("SELECT report_id, task_name, badgeid, report_date, photo_before, photo_after, report_status FROM report WHERE badgeid = '$badgeid' AND report_status = 'Pending';");
$stmt->execute();
$stmt->bind_result($report_id, $task_name, $badgeid, $report_date, $photo_before, $photo_after, $report_status);
$task = array();
while($stmt->fetch()){
$temp = array();
$temp['report_id'] = $report_id;
$temp['task_name'] = $task_name;
$temp['badgeid'] = $badgeid;
$booked = strtotime($report_date);
$report_date = date("d M Y", $booked);
$temp['report_date'] = $report_date;
$temp['photo_before'] = $photo_before;
$temp['photo_after'] = $photo_after;
$temp['report_status'] = $report_status;
array_push($task, $temp);
}
$response = array();
$response["data"] = $task;
echo json_encode($response);
?>
PDO
require_once 'configPDO.php';
$badgeid = $_GET["badgeid"] ?? "";
$stmt = $conn->prepare("SELECT report_id, task_name, badgeid, report_date, photo_before, photo_after, report_status FROM report WHERE badgeid = :badgeid AND report_status = 'Pending'");
$stmt->bindParam(':badgeid',$badgeid,PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$task = array();
while ($result) {
$temp = array();
$temp["data"] = $task;
array_push($task, $temp);
}
$response = array();
$response["data"] = $result;
echo json_encode($response);
?>
Does anyone know what is problem with my PDO code?
The mysqli code and PDO code are not the same. I copied the code from the mysqli version to the PDO version.
PDOStatement::fetch() gets one row at a time. When you take the results from fetch and put it into the condition of a while loop, you are creating an infinite loop which will eventually run out of memory.
require_once 'configPDO.php';
$badgeid = $_GET["badgeid"] ?? "";
$stmt = $conn->prepare("SELECT report_id, task_name, badgeid, report_date, photo_before, photo_after, report_status FROM report WHERE badgeid = :badgeid AND report_status = 'Pending'");
$stmt->bindParam(':badgeid',$badgeid,PDO::PARAM_STR);
$stmt->execute();
$task = [];
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
$temp = [];
$temp['report_id'] = $result['report_id'];
$temp['task_name'] = $result['task_name'];
$temp['badgeid'] = $result['badgeid'];
$booked = strtotime($result['report_date']);
$report_date = date("d M Y", $booked);
$temp['report_date'] = $result['report_date'];
$temp['photo_before'] = $result['photo_before'];
$temp['photo_after'] = $result['photo_after'];
$temp['report_status'] = $result['report_status'];
$task[] = $temp;
}
$response = [];
$response["data"] = $task;
echo json_encode($response);
Related
I am trying to display a nested json as seen in this picture
JSON Ouput
However it only gets the last data. I am sure that the 1st id has a data. Please see the code below
<?php
include 'conn2.php';
$pdo = new PDO($dsn, $user, $passwd);
$stmt = $pdo->prepare("CALL sp_foods_display();");
$stmt->execute();
$stmt->bindColumn('bar_name',$bar_name);
$stmt->bindColumn('address',$address);
$stmt->bindColumn('id',$post_id);
$response = array();
$result = array();
while ($row = $stmt->fetch(PDO::FETCH_BOUND)) {
$temp["bar_name"] = $bar_name;
$temp["address"] = $address;
$temp["item_details"] = getItem($post_id);
array_push($result, $temp);
}
$response["result"] = $result;
echo "<pre>" . json_encode($response,JSON_PRETTY_PRINT) . "</pre>";
function getItem($id) {
global $pdo;
$stmt = $pdo->prepare("SELECT * FROM fct_menu_foods WHERE post_id = :cur_post_id ORDER BY id ASC");
$stmt->bindParam(":cur_post_id",$id,PDO::PARAM_INT);
$stmt->execute();
$food_details = array();
$stmt->bindColumn('food_name',$food_name);
$stmt->bindColumn('price',$price);
$stmt->bindColumn('img_name',$img_name);
while ($row = $stmt->fetch(PDO::FETCH_BOUND)) {
$temp = array();
$temp["food_name"] = $food_name;
$temp["price"] = $price;
$temp["img_name"] = $img_name;
array_push($food_details, $temp);
}
return $food_details;
}
?>
my target output is to display all data in nested.
I found a solution. My bad. You have to closeCursor(); for every query and use fetchAll for getting the data.
I'm trying to get the registry id inserted in the database using MySQLi insert_id but it is giving error.
I already researched the web but found nothing that solved this problem.
Where am I going wrong?
<?php
date_default_timezone_set('America/Sao_Paulo');
$data = date('d-m-Y');
$hora = date('H:i:s');
$id_motorista = $_POST["id_motorista"];
$km = $_POST["km"];
$valor = $_POST["valor"];
$placa = $_POST["placa"];
$posto = $_POST["posto"];
$litros = $_POST["litros"];
$photo_user_origem = $_FILES["photo_user"]["tmp_name"];
$photo_user_destino = "photos/".md5(time()).".png";
$conn = new mysqli("localhost", "root", "", "banco");
$sql = "INSERT INTO abastecimentos (dia, km, posto, litros, placa, valor, id_motorista) VALUES ('$data','$km','$posto','$litros','$placa','$valor','$id_motorista')";
$stm = $conn->prepare($sql);
//ERROR SHOULD BE THERE STARTED HERE
if ($stm->execute()){
$id_bastecimento = $conn->insert_id;
$stm->close();
if (move_uploaded_file($photo_user_origem, $photo_user_destino)){
$sql_update_photo = 'UPDATE abastecimentos SET photo_usuario = ? WHERE id_bastecimento = ?';
$stm = $conn->prepare($sql_update_photo);
$stm->bind_param("si", $photo_user_destino, $id_bastecimento);
$stm->execute();
}
$retorno = array("retorno" => "YES");
} else {
$retorno = array("retorno" => "NO");
}
echo json_encode($retorno);
$stm->close();
$conn->close();
?>
<?php
include 'dbh.php';
session_start();
if (isset($_GET['gmail'])) {
$gname = $_GET['gmail'];
}
$gname = mysqli_real_escape_string($connect, $gname);
$_SESSION['myusername'] = $gname;
$today = date("d.m.y");
$k=0;
$sql = "SELECT cart_fext FROM cart WHERE cart_sess = '$sess'";
$result=mysqli_query($connect, $sql);
$kode[$k] = array();
$kame[$k] = array();
$kesc[$k] = array();
$kail[$k] = array();
$kid[$k] = array();
$kate[$k] = array();
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
extract($row);
$k = $k + 1;
$cname=$row['cart_item_name'];
$csize=$row['item_size'];
$cdesc=$row['cart_desc'];
$cfpath=$row['cart_fpath'];
$cfext=$row['cart_fext'];
$ccode=$row['cart_itemcode'];
$cuserid=$row['cart_usrid'];
$kode[$k] = $ccode;
$kame[$k] = $cname;
$kesc[$k] = $cdesc;
$kail[$k] = $gname;
$kid[$k] = $cuserid;
$kate[$k] = $today;
}
for($i=1; $i<=$k; $i++) {
$sqlsal = "INSERT INTO sales (s_code, s_name, s_desc, s_mail, s_userid, s_date) VALUES ('$kode[$i]', '$kame[$i]', '$kesc[$i]', '$kail[$i]', '$kid[$i]' ,'$kate[$i]')";
$result=mysqli_query($connect, $sqlsal);
}
header("location:makedir.php");
?>
my table sales is just not accepting data, dbh.php is to connect to the database
I don't understand what is wrong with this script?
please help?
I have checked your insert query it is running fine but I think the problem is with your SELECT query
SELECT cart_fext FROM cart WHERE cart_sess = '$sess'
please print the result of the query. I think that it may not be giving any result.
Hi I wanted to show port_name instead of port ID ($row['port_name']) so I made this query.
$stmt = $db->prepare("SELECT * FROM reservations
INNER JOIN ports ON reservations.port=ports.id WHERE NOT
((end <= :start) OR (start >= :end))");
$stmt->bindParam(':start', $_POST['start']);
$stmt->bindParam(':end', $_POST['end']);
$stmt->execute();
$result = $stmt->fetchAll();
class Event {}
$events = array();
date_default_timezone_set("UTC");
$now = new DateTime("now");
$today = $now->setTime(0, 0, 0);
foreach($result as $row) {
$e = new Event();
$e->id = $row['id'];
$e->service_id = $row['service_id'].'<br/>';
$e->service_classification = $row['service_classification'].'<br/>';
$e->text = $row['port_name'].'<br/>';
$e->start = $row['start'];
$e->end = $row['end'];
$e->resource = $row['room_id'];
$e->customer = $row['customer'];
$events[] = $e;
}
header('Content-Type: application/json');
echo json_encode($events);
?>
It is working and showing me port names like it should, but when I want to move with event or resize my event (I have calendar of "events") and then I refresh page events stay on previous positions. When I delete JOIN and leave there port_id (reservations.port) everything is working!
resize.php:
class Result {}
$stmt = $db->prepare("UPDATE reservations SET start = :start, end = :end WHERE id = :id");
$stmt->bindParam(':id', $_POST['id']);
$stmt->bindParam(':start', $_POST['newStart']);
$stmt->bindParam(':end', $_POST['newEnd']);
$stmt->execute();
$response = new Result();
$response->result = 'OK';
$response->message = 'Update successful';
header('Content-Type: application/json');
echo json_encode($response);
I don't get it, because I only update new start and end date. Any ideas? Thanks
I try to query a SQL database and save data into a custom array, but the array always repeats last row*num rows on database.
php:
class Cst
{
public $ParagemID;
public $Designacao;
public $DecimalDeGrauY;
public $DecimalDeGrauX;
}
require 'config.php';
$dsn = array( "Database"=>"$database", "UID"=>"$username", "PWD"=>"$password", "LoginTimeout"=> 60);
$db = sqlsrv_connect($server, $dsn);
$sql = "SELECT ParagemID, Designacao, DecimalDeGrauY, DecimalDeGrauX FROM adoParagens WHERE ParagemID >= 20000";
$stmt = sqlsrv_query($db, $sql);
$locations = new Cst();
$location=array();
$i=0;
while( $row = sqlsrv_fetch_object($stmt))
{
$locations->ParagemID = $row->ParagemID;
$locations->Designacao = $row->Designacao;
$locations->DecimalDeGrauY = $row->DecimalDeGrauY;
$locations->DecimalDeGrauX = $row->DecimalDeGrauX;
//echo json_encode($locations);
$location[$i]= $locations;
$i++;
}
echo json_encode($location);
It looks like you're always working with same instance of that object. Updating it for each row will also update all copies of it, as they are in fact the same object.
Try this instead.
...
$location = array();
while( $row = sqlsrv_fetch_object($stmt) )
{
$data = array();
$data['ParagemID'] = $row->ParagemID;
$data['Designacao'] = $row->Designacao;
$data['DecimalDeGrauY'] = $row->DecimalDeGrauY;
$data['DecimalDeGrauX'] = $row->DecimalDeGrauX;
$location[]= $data;
}
...
try using a 2 dimensional array.
$i=0;
while( $row = sqlsrv_fetch_object($stmt))
{
$location[$i][$locations->ParagemID/*put your val*/] = $row->ParagemID;
$location[$i][$locations->Designacao/*put your val*/] = $row->Designacao;
$location[$i][$locations->DecimalDeGrauY/*put your val*/] = $row->DecimalDeGrauY;
$location[$i][$locations->DecimalDeGrauX/*put your val*/] = $row->DecimalDeGrauX;
//echo json_encode($locations);
$i++;
}