bobbyjones
bobbyjones

Reputation: 2077

insert data into MYSQL using PHP array

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 */
$post_id = somefunction();
$title = $_POST['title'];
$body = $_POST['body'];

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

and this is inside my function.php

function insertToDB($myArray) {
    $db = dbConnect(); 
    $query = "INSERT INTO `posts`(`id`, `title`, `body`, `post_id`) VALUES ";
    $valuesArr = $array();

foreach($myarray as $row) {
         $id = (int)$row[0]; // as my primary, auto increment
         $title = mysql_real_escape_string($row[1]);
         $body = mysql_real_escape_string($row[2]);
         $post_id = (int)$row[3];

         $valuesArr[] = "(`id`, `title`, `body`, `post_id`)";
         }

         $sql .=implode(',', $valuesArr);
         $db->query($sql);
}

please note that my $id = (int)$row[0]; is primary and auto increment.

Upvotes: 0

Views: 5699

Answers (3)

Subin
Subin

Reputation: 3563

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

Upvotes: 2

versvs
versvs

Reputation: 643

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...

Upvotes: 0

HackerGK
HackerGK

Reputation: 370

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...

Upvotes: 0

Related Questions