Retrieve all the data from JSON array - php

I want to retrieve all the events that a student has attended by using this student ID number. So this is my PHP code, this code is working but it can only retrieve 1 event while this student has attended several events already.
<?php
$host='localhost';
$username='tan';
$password='1234567';
$db='feedback01';
$conn=mysqli_connect($host,$username,$password,$db);
if (!$conn)
{
die('Could not connect: ' . mysqli_connect_error());
}
$studentID=$_POST['StudentID'];
$studentID=mysqli_real_escape_string($conn,$studentID);
$query="SELECT * From PassportData WHERE StudentID='$studentID'";
$result=mysqli_query($conn,$query);
$response = array();
if(mysqli_num_rows($result)>0)
{
$row = mysqli_fetch_assoc($result);
$event = $row["Events"];
$date = $row["Date"];
$code = "login_success";
array_push($response, array("code"=>$code, "Events"=>$event, "Date"=>$date));
echo json_encode($response);
}
else{
$code = "login_failed";
$message = "not found!";
array_push($response, array("code"=>$code, "messsage"=>$message));
echo json_encode($response);
}
mysqli_close($conn);
?>

I don't know your table structure, but I think you have to change your code in something like this:
if(mysqli_num_rows($result)>0) {
$response = [];
while($row = mysqli_fetch_assoc($result)) {
$response[] = $row;
}
echo json_encode($response);
} else{
$code = "login_failed";
$message = "not found!";
array_push($response, array("code"=>$code, "messsage"=>$message));
echo json_encode($response);
}
mysqli_close($conn);
?>

Your code should be. Try while loop with result array.
if(mysqli_num_rows($result)>0)
{
while($row = mysqli_fetch_assoc($result)){
$event = $row["Events"];
$date = $row["Date"];
$code = "login_success";
array_push($response, array("code"=>$code, "Events"=>$event, "Date"=>$date));
}
echo json_encode($response);
}

Related

Mysql delete a row php

I have a MySQL table and i would like to delete a row in my table and after deleting the row the result must show all data left in my table .
<?php
include 'Connection.php';
// Create connection
$con= mysqli_connect($host,$user,$pass,$db);
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
$sql = "SELECT * FROM productos";
$result = $con->query($sql);
if ($result->num_rows >0) {
while($row[] = $result->fetch_assoc())
{
$tem = $row;
$json = json_encode(array("productos"=>$tem));
}
} else {
echo "No Results Found.";
}
echo $json;
$con->close();
?>
This is my select code... now i don't know how create the delete function..
Any help please.
You are overwritting, make array of rows and then echo json_encode at last
$items = array();
if ($result->num_rows >0) {
while($row = $result->fetch_assoc())
{
$items[] = $row;
}
} else {
echo "No Results Found.";
}
echo json_encode(array("productos"=>$items));
$con->close();

Conditional Logic on MySQL Query with PHP

I am doinga MySQL query to retreive data using PHP. I need to have a logic that if the data set returned is empty it shows a warning message else it displays the results:
$searchQuery = mysql_escape_string($_POST['searchQuery']);
$sql="SELECT * FROM db.tblname WHERE column1 = '".$searchQuery."'";
$result = mysqli_query($conn,$sql);
while($row = mysqli_fetch_array($result)){
echo $row["column1"];
}
mysqli_close($conn);
You need num_rows on the object
$result = mysqli_query($conn,$sql);
if ($result->num_rows == 0) {
echo 'result empty';
} else {
while($row = mysqli_fetch_array($result)){
echo $row["column1"];
}
}
http://php.net/manual/en/mysqli-result.num-rows.php
Change mysql_escape_string to mysqli_escape_string here
$where = "";
if(isset($_POST['searchQuery']) && trim($_POST['searchQuery'])){
$searchQuery = mysqli_escape_string($conn,$_POST['searchQuery']);
$where =" WHERE column1 = '".$searchQuery."'";
}
$sql="SELECT * FROM db.tblname ".$where;
It's as simple as this:
if ($result) {
//Your code
} else {
echo "Error: ".mysqli_error($conn);
}
First check with mysqli_num_rows(). Here is how to
$searchQuery = mysql_escape_string($_POST['searchQuery']);
$sql="SELECT * FROM db.tblname WHERE column1 = '".$searchQuery."'";
$result = mysqli_query($conn,$sql);
if(mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)){
echo $row["column1"];
}
}
else {
echo "No records found";
}
mysqli_close($conn);
$searchQuery = mysql_escape_string($_POST['searchQuery']);
$sql="SELECT * FROM db.tblname WHERE column1 = '".$searchQuery."'";
$result = mysqli_query($conn,$sql);
if(mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)){
echo $row["column1"];
}
} else {
echo "No results found";
}
mysqli_close($conn);

MySQL Data to JSON Array with inserting a string

This is my Code for now but it only works until the for loop in the mySQLResultsetToJSON().
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "123456";
$table = "ticketing";
$link = new mysqli($servername, $username, $password, $table);
if ($link->connect_error) {
die("Connection failed: " . $link->connect_error);
}
echo "Connected successfully";
$result = $link->query("SELECT * from Ticket");
print_r($result);
$final_result = mySQLResultsetToJSON($result);
print_r($final_result);
$link->close();
function mySQLResultsetToJSON($resultSet)
{
for($i = 0; sizeof($resultSet); $i++)
{
$rows = array();
while($r = mysqli_fetch_assoc($resultSet[$i])) {
$rows[] = $r;
}
$jsonResult[$i] = json_encode(array('Results' => $rows));
}
print_r($jsonResult);
return $jsonResult;
}
?>
Thank you!
Thomas
echo "mysql data<br />";
$result = $link->query("SELECT * from users");
print_r($result->fetch_object());
echo "<br />";
echo "in json<br />";
$res = ['Results' => $result->fetch_object() ];
echo json_encode($res);
$link->close();
User like
$result = $link->query("SELECT * from Ticket");
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
print "<pre>";
print_r(json_encode(array('Results' =>$rows)));
$link->close();

Duplicating result due to loop

So my code get a value from previous page, compare it with a table field in the database and display success or failure. Here is the original code:
<?php
if ($_GET['q'] !='')
{
include('config.inc');
$foo = $_GET['q'];
$query= "INSERT INTO register(name) VALUES('$foo')";
$result = mysql_query("SELECT * FROM user_student");
while($row = mysql_fetch_array($result))
{
$id= $row['sid'];
if($id==$foo)
{
$res = mysql_query($query);
if ($res)
{
echo 'Insertion ok';
}
else
{
echo " ";
echo "Attendance already taken for $foo";
}
}
else
{
echo " ";
echo "Student $foo does not exist!!";
}
}
}
else echo "Invalid Command";
?>
Am having duplicating result e.g Student 1124 does not exist!! 10times. I've modify the code to:
while($row = mysql_fetch_array($result))
{
$id= $row['sid'];
if($id==$foo)
{
$res = mysql_query($query);
}
else
{
echo " ";
echo "Student $foo does not exist!!";
}
}
if ($res)
{
echo 'Insertion ok';
}
else
{
echo " ";
echo "Attendance already taken for $foo";
}
So i've placed the $res outside the loop to avoid duplication result but now it says: variable cannot be resolved Any suggestions?
A bit of changed version of CaldasGSM:
<?php
if (!empty($_GET['q']))
{
include('config.inc');
$foo = mysql_real_escape_string($_GET['q']);
$result = mysql_query("SELECT * FROM user_student WHERE sid = '{$foo}'");
$num_rows = mysql_num_rows($result);
if($num_rows > 0)
{
$res = mysql_query("INSERT INTO register(name) VALUES('$foo')");
if ($res)
{
echo 'Insertion ok';
}
else
{
echo " ";
echo "Attendance already taken for $foo";
}
}
else
{
echo " ";
echo "Student $foo does not exist!!";
}
}
else
{
echo "Invalid Command";
}
?>
maybe something like
<?php
if ($_GET['q'] !='')
{
include('config.inc');
$foo = $_GET['q'];
$result = mysql_query("SELECT * FROM user_student");
$bRecordExists = false;
while($row = mysql_fetch_array($result))
{
$id= $row['sid'];
if($id==$foo)
{
$bRecordExists = true;
break;
}
}
if($bRecordExists)
{
$res = mysql_query("INSERT INTO register(name) VALUES('$foo')");
if ($res)
{
echo 'Insertion ok';
}
else
{
echo " ";
echo "Attendance already taken for $foo";
}
}
else
{
echo " ";
echo "Student $foo does not exist!!";
}
}
else
{
echo "Invalid Command";
}
?>

Error when using mysql_fetch_array();

table data(id, name)
function getData() {
$data = array();
$sql = 'Select * From data';
$query = mysql_query($sql);
if(!$query) {
echo "Error: " . mysql_error();
exit;
}
while($row = mysql_fetch_array($query)) {
$data[] = $row;
}
return $data;
}
$data = $this->getData();
foreach($data as $dt) {
echo $dt->name;
}
I get an error when I echo $dt->name;, the output is null, How do I fix it ?
$dt is not an object but a array. $dt->name should be $dt['name'].
Try:
var_dump($data);
//if its not a class then simply do
$data = getData();

Categories