insert data into MYSQL using PHP array

前端 未结 3 1145
遇见更好的自我
遇见更好的自我 2021-01-26 08:07

hi im trying to insert data in mysql using array, can someone please look at my code, i cant seem to make it work.

this is my post.php

/* POST.PHP */
$p         


        
相关标签:
3条回答
  • 2021-01-26 08:45

    Construct the array with a key and a value

    $myarray = array("id"=>'',"title"=>$title,"body"=>$body,"pid"=>$rowId);
    

    and Use PDO instead of mysql_* functions (depreciated).

    $sql=$dbh->prepare("INSERT INTO `posts`(`id`, `title`, `body`, `post_id`) VALUES (:id,:title,:body,:pid)");
    foreach($myarray as $row=>$value){
     $sql->bindValue(":".$row,$value);
    }
    $sql->execute();
    

    More About PDO : http://www.php.net/manual/en/book.pdo.php

    0 讨论(0)
  • 2021-01-26 08:46

    in

    $myarray = array('','$title','$body','$rowId');

    code, you cannot use single quotations to read variables values in to string. you must use double quatations for that, because if you use single quotation, it not reading variable value, and php thinks its the value itself,

    try

    $myarray = array("","$title","$body","$rowId");

    this may help you...

    0 讨论(0)
  • 2021-01-26 08:47

    The thing is:

    • Maybe your code has some weird indent, but the first definition insertToDB neither appears to be properly closed (maybe it is, at the end of the code section you provide) nor have a return. If it is properly closed, it still lacks a return (it may help you diagnose what is going on have conditional return for success and error cases.
    • You define $query but do not use it later. Unless you append to that string the result of converting your array into another string (a thing that I dont see either), I dont think you are going to INSERT anything to your database.
    • You need to loop through $valuesArr and build a string from your array.

    Maybe I'm missing something...

    0 讨论(0)
提交回复
热议问题