MySQL Data to JSON Array with inserting a string - php

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();

Related

How to show Level on each members on Recursive mysql php?

How to output the red color level on each member's name like the following screenshot :
Here is the demo webpage URL : http://client.bfm.expert/test_UnilevelBonus.php
Here is the code :
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
//Use the following function to get the data of downlines
function getChildren($parent) {
$servername = "11";
$username = "11";
$password = "11";
$dbname = "11";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$query = "SELECT user_id, first_name, sponsor_id FROM tbl_user_master WHERE sponsor_id = $parent";
$result = $conn->query($query);
$children = array();
$i = 0;
$result = $conn->query($query) or die($conn->error);
while($row = $result->fetch_assoc()) {
$children[$i] = array();
$children[$i]['name'] = $row['first_name'];
$children[$i]['children'] = getChildren($row['user_id']);
$i++;
}
return $children;
$conn->close();
}
//enter sponsor_id here, change 151 to 145 has a lot of downlines to test
$finalResult = getChildren(145);
//display all downlines of the sponsor
function printList($array = null) {
if (count($array)) {
echo "<ul>";
foreach ($array as $item) {
echo "<li>";
echo $item['name'];
echo " - level : ";
if (count($item['children'])) {
printList($item['children']);
}
echo "</li>";
}
echo "</ul>";
}
}
printList($finalResult);
?>
You need to pass level into 'printList' function and increment it after.
function printList($array = null, $level = 1) {
if (count($array)) {
echo "<ul>";
foreach ($array as $item) {
echo "<li>";
echo $item['name'];
echo " - level : " . $level;
if (count($item['children'])) {
printList($item['children'], $level+1);
}
echo "</li>";
}
echo "</ul>";
}
}
printList($finalResult, 1);

Retrieve all the data from JSON array

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);
}

Fatal error: Call to a member function fetch_assoc() on string

I tried to execute a query and iterate thru the result. The echo "<h1>" . $row["SummonerId"]. "</h1>"; works and it print it out at the page. But somehow this Error occurred after the printed result:
Fatal error: Call to a member function fetch_assoc() on string
I saw many errors similar to this. But those are on a non-object and not on string. What is that error?
Here is my code:
$servername = "localhost:3307";
$username = "root";
$password = "";
$dbname = "st-datacollector";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT * FROM summoner";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<h1>" . $row["SummonerId"]. "</h1>";
$summonerId = $row["SummonerId"];
$url = "https://euw.api.pvp.net/api/lol/euw/v1.3/game/by-summoner/" . $summonerId . "/recent?api_key=" . $api_key;
$result = file_get_contents($url);
$resultJSON = json_decode($result);
foreach($resultJSON_decoded->games as $game){
echo $game->gameMode." ".$game->gameType." ".$game->subType;
echo "<br>";
}
}
} else {
echo "0 results";
}
$conn->close();
$result variable is used to loop thru mysql query, you have to use different variable names inside your loop
$servername = "localhost:3307";
$username = "root";
$password = "";
$dbname = "st-datacollector";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT * FROM summoner";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<h1>" . $row["SummonerId"]. "</h1>";
$summonerId = $row["SummonerId"];
$url = "https://euw.api.pvp.net/api/lol/euw/v1.3/game/by-summoner/" . $summonerId . "/recent?api_key=" . $api_key;
$fcontents = file_get_contents($url);
$resultJSON = json_decode($fcontents);
foreach($resultJSON_decoded->games as $game){
echo $game->gameMode." ".$game->gameType." ".$game->subType;
echo "<br>";
}
}
} else {
echo "0 results";
}
$conn->close();
One more little thing I noticed.. $resultJSON and $resultJSON_decoded doesn't match inside the loop

Failing to recognize fetch_assoc method

I'm trying to upload an excel file to my site and save the data in my database, however i'm failing to do so and getting: Fatal error: Call to undefined method mysqli::fetch_assoc() ... But i'm not sure how to handle it, and i haven't found a question related on SO, any help?
function getSchedule($filepath,$con,$filename){
require_once 'excel/PHPExcel/IOFactory.php';
$objPHPExcel = PHPExcel_IOFactory::load($filepath);
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
$worksheetTitle = $worksheet->getTitle();
$highestRow = $worksheet->getHighestRow(); // e.g. 10
$highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
list($location, $date) = explode('-', $filename, 2);
$LastChange = date('d/m/Y h:i:s');
$Status='Open';
$servername = "localhost";
$username = "root";
$password = "Js";
$dbname = "jr";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM Schedule";
$conn->query($sql);
// output data of each row
while($row = $conn->fetch_assoc()) {
$sql1="DELETE FROM `schedule` WHERE " . $row["Date"]. "='$date'";
$result = mysqli_query($conn,$sql1);
}
$conn->close();
for ($row = 3; $row <= $highestRow; ++ $row) {
$sql="INSERT INTO `schedule` (`Status`,`LastChange`, `Location`,`Date`,`AFNumber`,`Name`,`01-IN`, `01-OUT`, `02-IN`, `02-OUT`, `03-IN`, `03-OUT`, `04-IN`, `04-OUT`, `05-IN`, `05-OUT`, `06-IN`, `06-OUT`, `07-IN`, `07-OUT`, `08-IN`, `08-OUT`, `09-IN`, `09-OUT`, `10-IN`, `10-OUT`, `11-IN`, `11-OUT`, `12-IN`, `12-OUT`, `13-IN`, `13-OUT`, `14-IN`, `14-OUT`, `15-IN`, `15-OUT`, `16-IN`, `16-OUT`, `17-IN`, `17-OUT`, `18-IN`, `18-OUT`, `19-IN`, `19-OUT`, `20-IN`, `20-OUT`, `21-IN`, `21-OUT`, `22-IN`, `22-OUT`, `23-IN`, `23-OUT`, `24-IN`, `24-OUT`, `25-IN`, `25-OUT`, `26-IN`, `26-OUT`, `27-IN`, `27-OUT`, `28-IN`, `28-OUT`, `29-IN`, `29-OUT`, `30-IN`, `30-OUT`, `31-IN`, `31-OUT`) VALUES ('".$Status."', '".$LastChange."','".$location."','".$date."',";
for ($col = 0; $col < ($highestColumnIndex -1); ++ $col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val = $cell->getValue();
if($col==($highestColumnIndex -2)){
$sql.="'$val'";
}else{
$sql.="'$val', ";}
}
echo "Index:".$highestColumnIndex."<br>";
if($highestColumnIndex < 63){
$temp = 63 - $highestColumnIndex;
for($i = 1;$i <= $temp; $i++){
if($i == $temp){
$sql.=",''";
} else{
$sql.=", '',";
}
}
}
$sql .=")";
if ($con->query($sql) === TRUE) {
} else {
echo "<br><br>Error: " . $sql . "<br>" . $con->error;
}
}//End For Each Row
}//End For Each Worksheet
}//End getHours Function
From php.net:
array mysqli_result::fetch_assoc ( void )
This means that you should provide it with a result of a query, not a connection. Change your code to this and it should work
$results = $conn->query($sql); //assign query to a variable and get mysqli_result in return
while($row = $results->fetch_assoc()) { //use that in the while loop
You are overwriting the connection object $conn.Use
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
Try this:
$sql = "SELECT * FROM Schedule";
$result = $conn->query($sql);
// output data of each row
while($row = $result->fetch_assoc()) {

Getting two scripts to work together

I'm trying to use the following scripts so that the result of the first one determines the output of the second one.
<?
$db = mysql_connect('localhost','username','pass') or die("Database error");
mysql_select_db('dbname', $db);
$query = "SELECT pool FROM winners";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result))
if ( $row['pool'] % 2 )
{
echo "<h4>Result 1</h4>";
echo "<br />";
}
else
{
echo "<h4>Result 2</h4>";
echo "<br />";
}
?>
<?php
$db = mysql_connect('localhost','username','pass') or die("Database error");
mysql_select_db('dbnamesameasother', $db);
$query2 = "SELECT * FROM comments";
$result2 = mysql_query($query2);
while ($row2 = mysql_fetch_assoc($result2))
if ( $row2['commentid'] % 2 ==0 )
{
echo $row2['name'];
echo "<br />";
}
else
{
echo $row2['name'];
}
?>
So basically if the first script chooses Result 1 I only want to echo the names which associate with that result. The names are associated by commentid where an odd commentid would be result 2 and an even commentid would be result 1. Is there any way to do this without using a union statement?
It recommend that you to create a function and then call it.something like this :
<?php
$db = mysql_connect('localhost','username','pass') or die("Database error");
mysql_select_db('dbname', $db);
$query = "SELECT pool FROM winners";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result))
if ( $row['pool'] % 2 )
{
echo "<h4>Result 1</h4>";
$names = get_names(1);
foreach ($names as $name) {
echo $name . "<br/>";
}
}
else
{
echo "<h4>Result 2</h4>";
$names = get_names(0);
foreach ($names as $name) {
echo $name . "<br/>";
}
}
Function get_names($pool_result)
{
$name_array = array();
$db = mysql_connect('localhost','username','pass') or die("Database error");
mysql_select_db('dbnamesameasother', $db);
$query = "SELECT * FROM comments WHERE commentid % 2 = $pool_result";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result))
{
array_push($name_array , $row['name']);
}
return $name_array;
}
?>
}

Categories