Hi kinda new on JSON so please bear with my stupidty.. I'm developing a chat application and I'm trying to use json on my working php script.. What I've tried so far is that after I execute my database query I encode the result as a JSON then after that I use json_decode
then Insert it on my foreach statement Here is the php code with both json_encode
and json_decode
with it
<?php
session_start();
$username=$_SESSION['username'];
$user_id = $_SESSION['id'];
require "config.php";
$con = new PDO("mysql:host=".db_host.";dbname=chat_db",db_username,db_password);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql="SELECT id,firstname,lastname,status,flag,flag2 FROM users WHERE id != :uid";
$stmt=$con->prepare($sql);
$stmt->bindValue("uid", $user_id, PDO::PARAM_STR);
$stmt->execute();
$sql2="UPDATE users SET status= 1 WHERE status = 0 AND id = :uid";
$stmt2=$con->prepare($sql2);
$stmt2->bindValue("uid", $user_id, PDO::PARAM_STR);
$stmt2->execute();
$rows =$stmt->fetchAll();
$str = json_encode($rows);
$str2 = json_decode($str);
foreach($str2 as $row){
$uid = $row['id'];
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$sts = $row['status'];
$flg = $row['flag'];
$flg2 = $row['flag2'];
?>
<li>
<a href="#" data-usernem="<?php echo $username; ?>" data-suid="<?php echo $user_id; ?>" data-userid="<?php echo $uid; ?>" data-role="button"><?php echo $firstname . PHP_EOL . $lastname; ?> </a>
<span class="typing-stats idle" data-type-status="<?php echo $flg2; ?>"> Typing... </span>
<span class="mail msg" data-flag="<?php echo $flg; ?>"> <a href="#" data-role="button"><i class="fa fa-envelope-o"></i></a> </span>
<span class="bullet" data-status="<?php echo $sts; ?>"> </span>
</li>
<?php
}
?>
If this script executes it gives me an error Fatal error: Cannot use object of type stdClass as array in D:\\site_deploy\\chat\\includes\\loadusers.php on line 22
Am I using json_encode
and json_decode
correctly? I'm pretty sure I followed whats written on php manual under json_decode
I have tried to var_dump it and it gives me the set of data that was encoded FYI
使用参数true
将其转换为数组。
$str2 = json_decode($str, true);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.