How to explode json data already present in mysql database using php? - php

I have a database table which previously had a coloumn data having a json data in it
| data | - `"{"display":{"pageName":"TEBT Home","Name":"rtryrtyrty rtyrtyrtyrty",
"Email":"trupti.gjklhjkgv#gmail.com","state":"WB","city":"CTY_ARAM",
"dob":"09/12/1964"}}"`
now I want to restructure my data_table and add different coloumns for pageName , Name, Email, state, city, dob and want to exlpode the json data already present in 'data' coloumn.
this is the logic I am trying to Implement , but it doesn't work .
<?php
$dataString = "SELECT data FROM data_table";
$result = mysqli_query($conn, $dataString);
$data =array();
while($row=mysqli_fetch_assoc($result)){
$data[] = $row['data'];
}
$iterations = ceil(count($data));
for ($x = 0; $x <$iterations; $x++) {
echo "The number is: ".$x." <br>";
if (!empty($data)) {
$json = json_decode($data, true);
$page = $json['display']['pageName'];
$name = $json['display']['Name'];
$email =$json['display']['Email'];
$mob =$json['display']['mobno'];
$state =$json['display']['state'];
$city =$json['display']['city'];
$dob =$json['display']['dob'];
echo $page;
$sql = "UPDATE data_table SET page = '".$page."' WHERE data ='".$data."' ";
mysqli_query($conn, $sql);
}
else
{
echo "done";
}
}
?>

use this code to see db error if any :
$dataString = "SELECT data FROM data_table";
$result = mysqli_query($conn, $dataString);
$data =array();
while($row=mysqli_fetch_assoc($result)){
$data[] = $row['data'];
}
$iterations = ceil(count($data));
for ($x = 0; $x <$iterations; $x++) {
echo "The number is: ".$x." <br>";
if (!empty($data)) {
$json = json_decode($data, true);
$page = $json['display']['pageName'];
$name = $json['display']['Name'];
$email =$json['display']['Email'];
$mob =$json['display']['mobno'];
$state =$json['display']['state'];
$city =$json['display']['city'];
$dob =$json['display']['dob'];
echo $page;
$sql = "UPDATE data_table SET page = '".$page."' WHERE data ='".$data."' ";
mysqli_query($conn, $sql);
echo("Error description: " . mysqli_error($con)); // added to see error msg
}

Related

calculating the total of values from database with the same id

I want to calculate the sub total and grand total of values of amount_collected column with the same id. Here is my code:
<?php
include 'includes/config/db_connection.php'; // include database connection
$sql = "SELECT DISTINCT(gmt_no) FROM driver_travel";
$result = $db->query($sql);
$errorInfo = $db->errorInfo();
echo $error = $errorInfo[2];
while($row = $result->fetch())
{
$sql1 = "SELECT Balance FROM driver_travel WHERE gmt_no =". $row['gmt_no'];
$result1 = $db->query($sql1);
$errorInfo = $db->errorInfo();
$error = $errorInfo[2];
$gmtnocount = $result1->rowCount();
$gmtno[$gmtnocount] = Array();
$bal[] = Array();
$i = 0;
while($getrow = $result1->fetch())
{
echo $gmtnocount. " ";
$bal[$i] = $getrow['Balance']. "<p>";
$countbal = count($bal);
echo $countbal;
$i++;
}
}
?>
The result is
444455666

Why Getting only 1 array instead of many arrays?

I am a completely newbie in programming php I would like to make this code below return many arrays(to flash as3), however I only receive one array.Can anyone please pinpoint what is my mistake here? thanks.
$data_array = "";
$i = 0;
//if(isset($_POST['myrequest']) && $_POST['myrequest'] == "get_characters")
//{
$sql = mysqli_query($conn, "SELECT * FROM ns_users ORDER BY Char_id");
while($row = mysqli_fetch_array($sql))
{
$i++;
$fb_name = $row["Username"];
$fb_id = $row["Fb_id"];
$fb_at = $row["Access_token"];
$fb_sig = $row["Fb_sig"];
$char_id = $row["Char_id"];
if($i == 1)
{
$data_array .= "$fb_name|$fb_id|$fb_at|$fb_sig|$char_id";
}
else
{
$data_array .= "(||)$fb_name|$fb_id|$fb_at|$fb_sig|$char_id";
}
echo "returnStr=$data_array";
exit();
}
When you write your exit insight your loop you stop executing your program and you get only one record. You should set the echo and exit after your while loop.
$data_array = "";
$i = 0;
$sql = mysqli_query($conn, "SELECT * FROM ns_users ORDER BY Char_id");
while($row = mysqli_fetch_array($sql)) {
$i++;
$fb_name = $row["Username"];
$fb_id = $row["Fb_id"];
$fb_at = $row["Access_token"];
$fb_sig = $row["Fb_sig"];
$char_id = $row["Char_id"];
if($i == 1) {
$data_array .= "$fb_name|$fb_id|$fb_at|$fb_sig|$char_id";
} else {
$data_array .= "(||)$fb_name|$fb_id|$fb_at|$fb_sig|$char_id";
}
}
echo "returnStr=$data_array";
exit();
Those two last line of your should be outside of your loop:
$data_array = "";
$i = 0;
//if(isset($_POST['myrequest']) && $_POST['myrequest'] == "get_characters")
//{
$sql = mysqli_query($conn, "SELECT * FROM ns_users ORDER BY Char_id");
while($row = mysqli_fetch_array($sql))
{
$i++;
$fb_name = $row["Username"];
$fb_id = $row["Fb_id"];
$fb_at = $row["Access_token"];
$fb_sig = $row["Fb_sig"];
$char_id = $row["Char_id"];
if($i == 1)
{
$data_array .= "$fb_name|$fb_id|$fb_at|$fb_sig|$char_id";
}
else
{
$data_array .= "(||)$fb_name|$fb_id|$fb_at|$fb_sig|$char_id";
}
}
echo "returnStr=$data_array";
exit();
If you would name the columns that you want in the SELECT then it's much simpler. Make sure to use MYSQLI_ASSOC in the fetch:
$sql = mysqli_query($conn, "SELECT Username, Fb_id, Access_token, Fb_sig, Char_id FROM ns_users ORDER BY Char_id");
while($row = mysqli_fetch_array($sql, MYSQLI_ASSOC))
{
$data_array[] = implode('|', $row);
}
echo "returnStr=" . implode('(||)', $data_array);
exit();

PHP MySQLi Query returning null with valid syntax

Ok so,
I have been trying to make a ticket system for my wxPanel in order to provide basic support for the application. Although I am easily able to make a database record with the provided code:
PHP:
if (isset($_POST['submit'])) {
$subject = $_POST['subject'];
$message = $_POST['message'];
$date = date('D M H:i');
$subject = mysqli_real_escape_string($subject);
$message = mysqli_real_escape_string($message);
$ticket_id = 'TICK_'.rand(00000,99999);
if (strlen($subject) === 0) {
echo "Subject Invalid.";
} elseif (strlen($message) === 0) {
echo "Message Invalid.";
} else {
mysqli_query("INSERT INTO tickets VALUES(
NULL,
'".$ticket_id."',
'".$_SESSION['user']."',
'".$subject."',
'1',
'".$date."',
'".$message."'
)");
}
header('Location: /view-ticket?identifier='.$ticket_id);
}
Works fine...
Then there is this, which is ment to fetch the ticket records and display the titles one by one:
PHP:
$query = mysqli_query("SELECT `subject`,`ticket_id` FROM tickets WHERE `username` = '".$_SESSION['user']."'");
while ($row = mysqli_fetch_assoc($query)) {
$tickets = $row['subject'];
$id = $row['ticket_id'];
}
foreach ($tickets as $ticket) {
echo '
<h2>'.$ticket.'</h2>
';
}
This always returns NULL. And also none of this works either:
if (isset($_GET['identifier']) === false || empty($_GET['identifier']) === true) {
header('Location: /tickets');
exit();
}
$id = mysqli_real_escape_string($_GET['identifier']);
$query = mysqli_query("SELECT `ticket_id`,`message`,`timestamp`,`status` FROM tickets WHERE `ticket_id` = '".$id."'");
while($row = mysqli_fetch_assoc($query)) {
$ticket_id = $row['ticket_id'];
$message = $row['message'];
$timestamp = $row['timestamp'];
$status = $row['status'];
}
foreach($message as $msg) {
echo '
<div class="ticket-message">
<h2>'.$message.'</h2>
</div>';
}
Thank you in advance!
p.s. Some of my code may be messy. Advice is always appreciated :)
Once you get the SELECT query working you are also going to have to look at the code that processes the results.
If ticket_id identifies a unique row
$query = mysqli_query($con, "SELECT ticket_id,message,timestamp,status
FROM tickets WHERE ticket_id = '$id'");
$row = mysqli_fetch_assoc($query);
$ticket_id = $row['ticket_id'];
$message = $row['message'];
$timestamp = $row['timestamp'];
$status = $row['status'];
echo '<div class="ticket-message"><h2>'.$message.'</h2></div>';
If ticket_id does not identify a unique row
$query = mysqli_query($con, "SELECT ticket_id,message,timestamp,status
FROM tickets WHERE ticket_id = '$id'");
// initialise the arrays that hold multiple row results
$ticket_id[] = array();
$message[] = array();
$timestamp[] = array();
$status[] = array();
while($row = mysqli_fetch_assoc($query)) {
$ticket_id[] = $row['ticket_id'];
$message[] = $row['message'];
$timestamp[] = $row['timestamp'];
$status[] = $row['status'];
}
foreach($message as $msg) {
echo '<div class="ticket-message"><h2>'.$msg.'</h2></div>';
}

How to use parameters in url php?

I have a number pages namely
change=1.php
change=2.php
change=3.php
They all have similar coding but leaving 1 or 2 variable values.
And I know its a very bad idea! How can I make a link work like below:
change.php?id=1
change.php?id=2
change.php?id=3
http://oi62.tinypic.com/708gfm.jpg
<?php
include 'connection.php';
session_start();
include 'details.php';
/*$pkmn_id = $_SESSION['pkmn_id'];
$poke = $_SESSION['path'];*/
$data = mysql_query(" SELECT * FROM user_pokemon_db WHERE team = 1 AND user_id = '".$id."' ");
while($rows = mysql_fetch_array($data))
{
$rep_id = $rows[0];
$pkmn_id = $rows['pkmn_id'];
$path = mysql_query(" SELECT * FROM pokemons WHERE pk_id = '".$pkmn_id."' ");
$poke = mysql_result($path, 0, "path");
echo $poke;
echo "<br />";
$level = $rows['level'];
echo $level;
echo "<br />";
$exp = $rows['exp'];
echo $exp;
echo "<br />";
echo "<br />";
}
$data = mysql_query(" SELECT * FROM user_pokemon_db WHERE user_id = '".$id."' AND team = 0");
while($rows = mysql_fetch_assoc($data))
{
$db_id = $rows['id'];
$array[] = $db_id;
$level = $rows['level'];
$array1[] = $level;
$exp = $rows['exp'];
$array2[] = $exp;
$pkmn_id = $rows['pkmn_id'];
$data1 = mysql_query(" SELECT * FROM pokemons WHERE pk_id = '".$pkmn_id."' ");
while($rows = mysql_fetch_assoc($data1))
{
$poke = $rows['path'];
$array3[] = $poke;
}
}
$team = 1;
$_SESSION['team'] = $team;
$_SESSION['rep_id'] = $rep_id;
?>
My PHP code.
You probably want to use GET variables, for which you need to combine all the files into one, named change.php. In this file you need the line $foo = $_GET["id"] which will get the value of the variable "id" in the url change.php?id=1.
if (isset($_GET["id"])) {
$foo = $_GET["id"];
//your code here
}else{
echo 'ERROR!!! No id in URL';
}
You can have several variables in the URL like this: change.php?id=1&a=bar&b=toofoo
You can get current script's file name and parse integer.
__FILE__
gives current script's name. Then,
$myStr = preg_replace('/\.php$/', '', __FILE__);
$result = preg_replace('/change=$/', '', $myStr);
echo $result; // it's your id

php while loop only displays one result for a mysql query across multiple tables

I am having an issue with a while statement only returning one result. this is my first time trying to display product information from several tables and I don't know what I'm doing wrong. here is the code:
<?php
require('./includes/config.inc.php');
require(MYSQL);
$sql = sprintf("SELECT * FROM tea");
$res = mysqli_query($dbc, $sql);
if(!$res){
die('Could not complete query: '.mysqli_error($dbc));
} else {
echo 'Success!<br />';
while($row = mysqli_fetch_array($res)){
$table = $row['category'];
$inum = $row['item_number'];
echo $table.' '.$inum.'<br />';
$fetch = sprintf("SELECT sub_category, item_name, description FROM $table WHERE item_number ='$inum'");
$fetchRes = mysqli_query($dbc, $fetch);
if(!$fetchRes){
die('Could not fetch: '.mysqli_error($dbc));
} else {
while($fetchRow = mysqli_fetch_array($fetchRes)){
$subCat = $fetchRes['sub_category'];
$iNumber = $inum;
$iname = $fetchRes['item_name'];
$desc = $fetchRes['description'];
echo $id.' '.$subCat.' '.$iNumber.' '.$iname.' '.$desc.'<br />';
}
}
}
}
Inside your while loop, you should be using the $fetchRow variable as the array from which to grab columns, such as 'sub_category'.
IS
$subCat = $fetchRes['sub_category'];
$iNumber = $inum;
$iname = $fetchRes['item_name'];
$desc = $fetchRes['description'];
Needs to be: Res to Row
$subCat = $fetchRow['sub_category'];
$iNumber = $inum;
$iname = $fetchRow['item_name'];
$desc = $fetchRow['description'];

Categories