【问题标题】:从数据库 MySQL 中选择所有数据不工作 php 但插入工作 [重复]
【发布时间】:2022-01-23 14:29:07
【问题描述】:

首先我在这里有插入部分,它从 json 文件中获取数据,然后插入然后选择

  $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));
       
         
    }

当我选择它不起作用的数据时,它会打印出来

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

这个选择代码确定所有代码都在同一个文件中



     $sqlquery3 = "SELECT 'title'   FROM jsondata  " ;
     $sth = $mysqli->prepare($sqlquery3);
     $sth->execute();
  
     $result = $sth->fetchAll();
     print_r($result);
    

【问题讨论】:

  • 这能回答你的问题吗? How do I use fetchAll in php?
  • fetchAll() 是 PDO 语法。您正在使用 MySQLi。这是两个完全不同的扩展。
  • 正如@M.Eriksson 所说,fetchAll 是 PDO 语法。对于 MySQLi,正确的语法是 fetch_all link
  • @DimitrisFilippou 它几乎可以工作,是的,至少它打印了一些东西并执行了查询,但它是空的
  • 它如何正确打印字段数

标签: php mysql sql json


【解决方案1】:

首先@M.Eriksson 评论fetchAll 是PDO 语法。对于 MySQLi,正确的语法是 fetch_all

其次,fetch_all 需要一个 mysqli_result 对象作为参数,因此您必须在您的execute 命令之后使用get_result

那么你有一个错字,因为'title' 应该使用反引号而不是单引号。

当您使用它并且您已经使用准备好的语句进行插入时,您还应该更改您的插入语句

"INSERT INTO `jsondata` (`title`, `slug`, `content`, `categories`, `media`) VALUES (  '$TITLE[$s]',   ? ,   ?, ?,  '$TITLE[$s]' )" ;

"INSERT INTO `jsondata` (`title`, `slug`, `content`, `categories`, `media`) VALUES (  ?,   ? ,   ?, ?,  ? )" ;

并绑定$TITLE[$s],这样您就不会受到注入攻击

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-12
    • 1970-01-01
    • 2018-07-05
    • 1970-01-01
    • 2013-05-06
    • 2023-03-19
    • 1970-01-01
    相关资源
    最近更新 更多