Don't encode json from php - php

I have 2 files php: connect.php and getsp.php. As follow:
- Connect.php:
$host = "localhost";
$username = "root";
$password = "";
$database = "thietbi";
$conn = mysqli_connect($host, $username, $password, $database);
mysqli_query($conn, "SET NAMES 'uft8'");
- Getsp.php
include "connect.php";
// mysqli_set_charset($conn, "utf8");
$page = $_GET['page'];
$idsp = 1;
$space = 5;
$limit = ($page - 1) * $space;
$mangsanpham = array();
$query = "SELECT * FROM sanpham WHERE idsanpham = $idsp LIMIT $limit,$space";
$data = mysqli_query($conn,$query);
while ($row = mysqli_fetch_assoc($data)) {
$id = $row['id'];
$tsp = $row['tensanpham'];
$gsp = $row['giasanpham'];
$hsp = $row['hinhanhsanpham'];
$mtsp = $row['motasanpham'];
$isp = $row['idsanpham']));
array_push($mangsanpham, new Sanpham($id, $tsp, $gsp, $hsp, $mtsp, $isp));
}
echo json_encode($mangsanpham);
class Sanpham{
function Sanpham($id, $tensp, $giasp, $hinhsp, $motasp, $idsanpham){
$this->id = $id;
$this->tensp = $tensp;
$this->giasp = $giasp;
$this->hinhsp = $hinhsp;
$this->motasp = $motasp;
$this->idsanpham = $idsanpham;
}
}
When I run file "Getsp.php", result is white blank page.
I replace getsp.php with content:
include "connect.php";
// mysqli_set_charset($conn, "utf8");
$page = $_GET['page'];
$idsp = 1;
$space = 5;
$limit = ($page - 1) * $space;
$mangsanpham = array();
$query = "SELECT * FROM sanpham WHERE idsanpham = $idsp LIMIT $limit,$space";
$data = mysqli_query($conn,$query);
while ($row = mysqli_fetch_assoc($data)) {
array_push($mangsanpham, new Sanpham(
$row['id'],
$row['tensanpham'],
$row['giasanpham'],
$row['hinhanhsanpham'],
$row['motasanpham'],
$row['idsanpham']));
}
echo json_encode($mangsanpham);
class Sanpham{
function Sanpham($id, $tensp, $giasp, $hinhsp, $motasp, $idsanpham){
$this->id = $id;
$this->tensp = $tensp;
$this->giasp = $giasp;
$this->hinhsp = $hinhsp;
$this->motasp = $motasp;
$this->idsanpham = $idsanpham;
}
}
The result is not. Where did I wrong?
I tried 2 ways:
$json = json_encode($mangsanpham, JSON_PRETTY_PRINT);
print_r($json);
and
echo json_encode($mangsanpham);
The results are not encode JSON. Hope to get help from everyone!

To use array_push, you have to declare first variable as array
i.e $mangsanpham = array(); //before while loop

Related

How do I store the results of the for loop as an array in the res variable?

I want to store the results of the for loop as an array in the variable
$res. How do I do it?
<?php
$servername = "localhost";
$username = "root";
$password = "";
$name = "abc";
$con = new mysqli ($servername, $username, $password, $name);
$sql1 = $con->query("SELECT (status) FROM `seita`");
$i = $sql1->num_rows;
echo $i;
for($x=1; $x<=$i; $x++)
{
echo $x;
$sql = $con->query("SELECT status FROM `seita` WHERE RollNo = '$x'");
$res = mysqli_fetch_row($sql);
}
?>
The answer given by Rohit Mittal gave me array to string conversion error. What do I do next?
You can fetch all in one query with fetch_all() of mysqli
$servername = "localhost";
$username = "root";
$password = "";
$name = "abc";
$con = new mysqli ($servername, $username, $password, $name);
$result = $con->query("SELECT status FROM `seita`")->fetch_all();
You could try to do it all in one line. Maybe something similar to this:
$res = $con->query("SELECT status
FROM `seita`
WHERE RollNo between 1 and (
SELECT count(status)
FROM `seita`
)
")->fetch_all();
You want to append to an array search google php array append which gives array_push($stack, "apple", "raspberry");
// Declare arrray
$res = []
for($x=1; $x<=$i; $x++)
{
echo $x;
$sql = $con->query("SELECT status FROM `seita` WHERE RollNo = '$x'");
// Append result to array
array_push($res, mysqli_fetch_row($sql));
}
You need to make an array and need to get only status value as below:
$res = [];
for($x=1; $x<=$i; $x++)
{
echo $x;
$sql = $con->query("SELECT status FROM `seita` WHERE RollNo = '$x'");
$statusData = mysqli_fetch_row($sql);
$res[] = $statusData['status'];
}

JSON Encode PHP

So this is my code:
<?php
ini_set('max_execution_time', 150);
require('db.php');
$values = array();
$data = array();
$username = $_GET['username'];
$username = $mysqli->real_escape_string($username);
$password = $_GET['password'];
$password = $mysqli->real_escape_string($password);
$query = $mysqli->query("SELECT premium_duration, vip_duration
FROM
users_account
WHERE
user_name='".$username."'
AND user_pass='".md5($password)."'
");
while($row = $query->fetch_assoc())
{
if($row['premium_duration'] > 0)
{
$timeremain = $row['premium_duration'];
$type = 'Premium';
}elseif($row['vip_duration'] > 0)
{
$timeremain = $row['vip_duration'];
$type = 'VIP';
}else{
$timeremain = 0;
$type = 'None';
}
$values['TimeRemain'] = $timeremain;
$values['Type'] = $type;
$data[] = $values;
}
echo json_encode(array("Durations" => ($data)));
?>
But it only results to:
{"Durations":[{"TimeRemain":"15847800","Type":"Premium"}]}
What I want to achieve is:
{ "Durations"😞 { "TimeRemain":74973600, "Type":"Premium"
}, { "TimeRemain":0, "Type":"VIP" } ] }
How I can do that?

unable to change input data and db query result to array for pattern recognition

I'm unable to change an input string($prima = $_POST['id'];) and a db query result ($systemuser['id'];) into an array
which will be used for pattern matching using one single character at a time and then trying to
find a match in the database "id" row that is queried. The point is to use two-third of an id(supposedly incomplete id of a user of a system) to query and find the complete id. Please see my code. I'd appreciate some help. Thanks
I'm getting "undefined offset:0 through 9" error.
<?php
session_start();
include_once('server.php');
$error = false;
$gat = "";
$get = "";
$rt1 = "";
$rt2 = "";
$rt3 = "";
$rt4 = "";
$rt5 = "";
$rt6 = "";
$rt7 = "";
$rt8 = "";
$rt9 = "";
$rt0 = "";
if(isset($_POST['btn-login'])){
$firstname = $_POST['firstname'];
$firstname = trim($firstname);
$firstname = trim($_POST['firstname']);
$firstname = htmlspecialchars(strip_tags($firstname));
$lastname = $_POST['lastname'];
$lastname = trim($lastname);
$lastname = trim($_POST['lastname']);
$lastname = htmlspecialchars(strip_tags($lastname));
$id = $_POST['id'];
$id = trim($id);
$id = trim($_POST['id']);
$id = htmlspecialchars(strip_tags($id));
$gender = $_POST['gender'];
if(!$error) {
//search data if no errors
$query = "select * from subscribers";
$conditions = array();
if(! empty($firstname)){
$conditions[] = "firstname='$firstname'";
}
if(! empty($lastname)){
$conditions[] = "lastname='$lastname'";
}
if(! empty($gender)){
$conditions[] = "gender='$gender'";
}
$sql = $query;
if(count($conditions) > 0){
$sql .= " WHERE " . implode(' AND ', $conditions);
}
$result = mysqli_query($conn, $sql);
while($systemuser = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$systemuser['id'];
$gat = $systemuser['id'];
}
//convert user input to array
$prima = $_POST['id'];
$prima = array();
$rt1 = $prima[0];
$rt2 = $prima[1];
$rt3 = $prima[2];
$rt4 = $prima[3];
$rt5 = $prima[4];
$rt6 = $prima[5];
$rt7 = $prima[6];
$rt8 = $prima[7];
$rt9 = $prima[8];
$rt0 = $prima[9];
//retrieve and convert db data into array
$gat = array();
foreach( $gat as $get ){
$rt1 = $prima[0];
if (preg_match("/[$rt1]+/", $gat));{
$get += 1;
}
$rt2 = $prima[1];
if (preg_match("/[$rt2]+/", $gat)){
$get += 1;
}
$rt3 = $prima[2];
if (preg_match("/[$rt3]+/", $gat)){
$get += 1;
}
$rt4 = $prima[3];
if (preg_match("/[$rt4]+/", $gat)){
$get += 1;
}
$rt5 = $prima[4];
if (preg_match("/[$rt5]+/", $gat)){
$get += 1;
}
$rt6 = $prima[5];
if (preg_match("/[$rt6]+/", $gat)){
$get += 1;
}
$rt7 = $prima[6];
if (preg_match("/[$rt7]+/", $gat)){
$get += 1;
}
$rt8 = $prima[7];
if (preg_match("/[$rt8]+/", $gat)){
$get += 1;
}
$rt9 = $prima[8];
if (preg_match("/[$rt9]+/", $gat)){
$get += 1;
}
$rt0 = $prima[9];
if (preg_match("/[$rt0]+/", $gat)){
$get += 1;
}
if ($get > 9){
echo 'match found!';
}
else{
echo 'match not found!';
}
}
}
}
?>
I started to refactor but there is just too much that is wrong.
You are getting that Undefined offset: 0 notice because...
<?php
$prima = array();
$rt1 = $prima[0];
Is referencing offset zero on an empty array. The code makes no sense. You seem to frequently assign a value and then overwrite in on the next line.
FWIW: strings in PHP can behave much like an array...
UPDATE:
I'm a little confused about crux here honestly. If I wanted to reference the first and second letters in a string I would do:
$str = "I like PHP";
$firstLetter = (isset($str[0])) ? $str[0] : '';
$secondLetter = (isset($str[1])) ? $str[1] : '';
See if you can follow this example:
$str = 'I like PHP';
for ($i=0; $i<strlen($str); $i++) {
echo $str[$i] . "|";
}
And then... are you looking to do a WHERE foo LIKE 'a%' type query? A "wildcard" search?

having an array to string conversion error

$conn = mysqli_connect("$host", "$username", "$password")or die("cannot connect");
mysqli_select_db($conn,"$db_name")or die("cannot select DB");
the below code is trying to get the MYSQL table and create the headers and columns for the table to print on a pdf page.
$result=mysqli_query($conn,"select Employee_number,date_start,date_end,Days_taken,Sick,Study,Annual,compassionate_leave,Other,Details,Status,approved_by from $tbl_name ");
$number_of_products = mysqli_num_rows($result);
//Initialize the 3 columns and the total
$column_Employee_number = "";
$column_date_start = "";
$column_date_end = "";
$column_Days_taken = "";
$column_Sick = "";
$column_Study = "";
$column_Annual = "";
$column_compassionate_leave = "";
$column_Other = "";
$column_Details = "";
$column_Status = "";
$column_approved_by = "";
$total = 0;
//For each row, add the field to the corresponding column
while($row = mysqli_fetch_array($result))
{
$Employee_number = $row["Employee_number"];
$date_start = $row["date_start"];
$date_end = $row["date_end"];
$Days_taken = $row["Days_taken"];
$Sick = $row["Sick"];
$Study = $row["Study"];
$Annual = $row["Annual"];
$compassionate_leave = ["compassionate_leave"];
$Other = $row["Other"];
$Details = $row["Details"];
$Status = $row["Status"];
$Other = $row["Other"];
$approved_by =$row["approved_by"];
$column_Employee_number =$column_Employee_number.$Employee_number."\n";
$column_date_start = $column_date_start.$date_start."\n";
$column_date_end = $column_date_end.$date_end."\n";
$column_Days_taken = $column_Days_taken.$Days_taken."\n";
$column_Sick = $column_Sick.$Sick."\n";
$column_Study = $column_Study.$Study."\n";
$column_Annual = $column_Annual.$Annual."\n";
$column_compassionate_leave = $column_compassionate_leave.$compassionate_leave."\n";
$column_Other = $column_Other.$Other."\n";
$column_Details = $column_Details.$Details."\n";
$column_Status = $column_Status.$Status."\n";
$column_approved_by = $column_approved_by.$approved_by."\n";
}
from the above code i get a error saying
Notice: Array to string conversion in C:\xampp\htdocs\Namtax\leave_view.php on line 64
which is this line
$column_compassionate_leave = $column_compassionate_leave.$compassionate_leave."\n";
and i dont seem to understand why the error is showing only for that line and not for the rest and any help on how to fix it ?
You have this code
$compassionate_leave = ["compassionate_leave"];
its array, change to
$compassionate_leave = $row["compassionate_leave"];
change your $compassionate_leave = ["compassionate_leave"]; it should be $compassionate_leave = $row["compassionate_leave"];
$compassionate_leave = ["compassionate_leave"];
This line will be
$compassionate_leave = $row["compassionate_leave"];

How to use rows of Mysql array in PHP function?

I have a function in PHP and I would like to export an array from my MYSQL Database and then use the rows in a loop to do some stuff with them.
$DB_Server = "XXX.XXX.XXX.XXX";
$DB_Username = "XXXX";
$DB_Password = "XXXXX";
$DB_Database = "XXXXX";
$conn = new mysqli($DB_Server, $DB_Username, $DB_Password, $DB_Database);
$query = "Select Name, Wert from test.DBPBX";
function show(array $options) {
global $showresult, $master, $conn, $query;
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($result)) {
$cnlongname = $row["Name"];
$usercontent = $row["Wert"];
$cn = $cnlongname;
$options['config']->value = 1;
$config = $options["config"]->value;
$show = new SimpleXMLElement("<show/>");
$user = $show->addChild("user");
$user->addAttribute("cn", $cn);
if ($config)
$user->addAttribute("config", "true");
print "cmd: " . htmlspecialchars($show->asXML()) . "\n";
$showresult = $master->Admin($show->asXML());
print "result: " . htmlspecialchars($showresult) . "\n";
$mod = "text=".$usercontent;
$modify = new SimpleXMLElement("$showresult");
$user = $modify->user;
$path = explode("/device/hw/", $mod);
$srch = $user;
$nsegments = count($path);
$i = 1;
foreach ($path as $p) {
if ($i == $nsegments) {
// last part, the modification
list($attr, $value) = explode("=", $p);
$srch[$attr] = $value;
} else {
$srch = $srch->$p;
}
$i++;
}
$modify = new SimpleXMLElement("<modify>" . $user->asXML() . "</modify>");
print "cmd: " . htmlspecialchars($cmd = $modify->asXML()) . "\n";
// do it
$result = $master->Admin($cmd);
print "result: " . htmlspecialchars($result);
}
}
For $cn I would like to use $cnlongname (or $row["Name"]). And for $mod I would like to use $usercontent (or $row["Wert"]). However when I would like to use it I get an error after the first loop:
Warning: mysqli_fetch_assoc() expects parameter 1 to be
mysqli_result, string given in /sample.php on
line 175
Line 175 is:
while ($row = mysqli_fetch_assoc($result)) {
Can you please help me?
Inside your while loop you overwrite your result, therefore you lose your mysql result and cannot query it any more.
// do it
$result = $master->Admin($cmd);
Use a different variable there. :)

Categories