简体   繁体   English

PHP MySQL 查询 2 个数据表并组合成一个 json 数组以进行回显?

[英]PHP MySQL query 2 tables for data and combine into one json array for echo?

How to combine these 2 queries into one php array that echos back to ajax request in json format?如何将这 2 个查询组合成一个 php 数组,以 json 格式回显 ajax 请求? Each statement is confirmed working alone.每个语句都被确认单独工作。
Something that looks like:看起来像的东西:

 'fname' => $fname,
 'lname' => $lname,
'gender' => $gender,
  'city' => $city,
 'state' => $state
   'bio' => $bio


PHP MySQL request PHP MySQL 请求

<?php
include 'sqlconnection.php';
$conn = OpenCon();

$stmt = $conn->prepare('SELECT fname,lname,gender,city,state FROM users WHERE uid='.$_POST['info']);
$stmt->execute();
$stmt->bind_result($fname,$lname,$gender,$city,$state);
while($stmt->fetch()) {
    $output=array(
        'fname' => $fname,
        'lname' => $lname,
        'gender' => $gender,
        'city' => $city,
        'state' => $state
    );
}
$json=json_encode($output);
echo $json;

$stmt = $conn->prepare('SELECT bio FROM profile WHERE uid='.$_POST['info']);
$stmt->execute();
$stmt->bind_result($bio);
while($stmt->fetch()) {
    $output=array(
        'bio' => $bio
    );
}
$json=json_encode($output);
echo $json;

$stmt->close();
CloseCon($conn);
?>

You can simply JOIN your two tables on uid to merge the two queries into one.您可以简单地在uidJOIN您的两个表以将两个查询合并为一个。 Note you are not using prepared statements properly, you should put in a placeholder for uid and then use bind_param to attach a value:请注意,您没有正确使用准备好的语句,您应该为uid放置一个占位符,然后使用bind_param附加一个值:

$stmt = $conn->prepare('SELECT u.fname,u.lname,u.gender,u.city,u.state,p.bio
                        FROM users u
                        JOIN profile p ON p.uid = u.uid
                        WHERE u.uid=?');
$stmt->bind_param('s', $_POST['info']);
$stmt->execute();
$stmt->bind_result($fname,$lname,$gender,$city,$state,$bio);
while($stmt->fetch()) {
    $output=array(
        'fname' => $fname,
        'lname' => $lname,
        'gender' => $gender,
        'city' => $city,
        'state' => $state,
        'bio' => $bio
    );
}

Note that if it's possible a user will not have an entry in the profile table, you should use a LEFT JOIN instead of a JOIN .请注意,如果用户可能在profile表中没有条目,则应使用LEFT JOIN而不是JOIN

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM