0

With the php code below, I am trying to select a record from my database. When I run the code I get this error:

Catchable fatal error: Object of class mysqli_result could not be converted to string

What I want to achieve is to convert the result into a jSON object, but instead I get this error.

<?php
session_start();
include_once 'db/dbconnect.php';


$var = $_GET['name'];

// echo $var;

$json = [];

$sql = "SELECT * from recipes WHERE recipes.recipeName = '.$var'";
$rslt = mysqli_query($con,$sql);

echo $rslt;


?>
Robert Ross
  • 1,151
  • 2
  • 19
  • 47
  • Your code is vulnerable to [**SQL injection**](https://en.wikipedia.org/wiki/SQL_injection) attacks. You should use [**mysqli**](https://secure.php.net/manual/en/mysqli.prepare.php) or [**PDO**](https://secure.php.net/manual/en/pdo.prepared-statements.php) prepared statements with bound parameters as described in [**this post**](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). – Alex Howansky May 07 '17 at 15:13

1 Answers1

1

you will need to iterate over the results, since mysqli returns one row at a time:

$sql = "SELECT * from recipes WHERE recipes.recipeName = '$var'";
$rslt = mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($rslt)){
   print_r($row);
}

or, to JSON it:

$json = array();
while($row = mysqli_fetch_assoc($rslt)){
   $json[] = $row;
}
echo json_encode($json);

mysqli_fetch_assoc returns the row as a keyd array - http://php.net/manual/en/mysqli-result.fetch-assoc.php

as to SQL injection defence, use mysqli_real_escape_string (http://php.net/manual/en/mysqli.real-escape-string.php) like:

$var = mysqli_real_escape_string($con,$_GET['name']);
Jameson the dog
  • 1,796
  • 1
  • 11
  • 12