Home » Php » php call variable from json array

php call variable from json array

Posted by: admin February 25, 2020 Leave a comment

Questions:

from the below code, how can I call the value of poet from the array and set it in a php variable to use it for another query

What shall I write instead of ??? below

$ip = 1 ;
$query = mysqli_query($con, "SELECT * FROM poems WHERE ip = '$ip' ");
$json1 = array();
while($data = mysqli_fetch_assoc($query))
array_push($json1, array('title' => $data['poem_title'],
        'body' => $data['poem_body'],
         'poet' => $data['poet'],
            ));
$poet = ???; 
How to&Answers:

You just need to assign the value to a new variable, inside your loop. Your variable $poet will be available after the loop.

$query = mysqli_query($con, "SELECT * FROM poems WHERE ip = '$ip'");
$json1 = array();

while ($data = mysqli_fetch_assoc($query)) {
    array_push($json1, array(
        'title' => $data['poem_title'],
        'body' => $data['poem_body'],
        'poet' => $data['poet']
    ));
    $poet = $data['poet'];
}

// Your new variable is available
echo $poet

But what you’re doing here doesn’t really make sense because if you’re looping through multiple rows of data, $poet will only ever equal the last row’s value at the end of the loop. It will get overwritten on every iteration of the loop.

If, in your database, ip is a primary or unique key which you can guarantee to only retrieve one row, then you don’t want to use a loop at all. You can just simplify it to:

$query = mysqli_query($con, "SELECT * FROM poems WHERE ip = '$ip'");
$json1 = mysqli_fetch_assoc($result);
$poet = $json1['poet'];