First I have the insertion part here it's getting data from json file then insert then select
$mysqli = new mysqli($servername, $username, $password,$db) or die("Connect failed:
%s\n". $mysqli -> error);
echo "Connected successfully";
$json = file_get_contents("https://raw.githubusercontent.com/SeteMares/full-stack-test/master/feed.json") ;
$json = json_decode( $json,true);
$content= array();
$TITLE = array();
$CONTENT = array() ;
$MEDIA = array() ;
$SLUG = array() ;
$categories = array() ;
foreach ($json as $key => $value){
$TITLE[] = $json[$key]['title'] ;
$CONTENT[] = $json[$key]['content'];
$MEDIA[] = $json[$key]['media'];
$SLUG[] = $json[$key]['slug'];
$categories[] = $json[$key]['categories'];
}
for($s=0;$s<sizeof($TITLE);$s ){
$url_string = $CONTENT[$s][0]['content'];
$res = urldecode($url_string);
$Cataggory = $categories[$s]['primary'];
echo gettype($Cataggory );
$slug = $SLUG[$s] ;
echo gettype($slug );
$sqlquery = "INSERT INTO `jsondata` (`title`, `slug`, `content`, `categories`, `media`) VALUES ( '$TITLE[$s]', ? , ?, ?, '$TITLE[$s]' )" ;
$stmt = $mysqli->prepare($sqlquery);
$stmt->execute(array($slug,$res,$Cataggory));
}
when i select the data it doesn't work it prints
Fatal error: Uncaught Error: Call to undefined method mysqli_stmt::fetchAll() in C:\xampp\htdocs\firstphp\index.php:68 Stack trace: #0 {main} thrown in C:\xampp\htdocs\firstphp\index.php on line 68
this the select code for sure all the code in the same file
$sqlquery3 = "SELECT 'title' FROM jsondata " ;
$sth = $mysqli->prepare($sqlquery3);
$sth->execute();
$result = $sth->fetchAll();
print_r($result);
CodePudding user response:
Firstly as @M.Eriksson commented fetchAll
is PDO syntax. For MySQLi the correct syntax is fetch_all
Secondly fetch_all
needs a mysqli_result object as a parameter so you have to use get_result
after your execute
command.
Then you had a typo as 'title'
should be with backticks instead of single quotes.
And while you are at it and you already use prepared statements for your insert then you should also change your Insert statement
"INSERT INTO `jsondata` (`title`, `slug`, `content`, `categories`, `media`) VALUES ( '$TITLE[$s]', ? , ?, ?, '$TITLE[$s]' )" ;
to
"INSERT INTO `jsondata` (`title`, `slug`, `content`, `categories`, `media`) VALUES ( ?, ? , ?, ?, ? )" ;
and bind $TITLE[$s]
so you are not vulnerable to injection attacks