PDO, MySQL Insert fetched data into an array -
this question related previous question: pdo, mysql - how return array function?
but felt wasn't specific enough.
i want return each row of variables in own key in array can use them in calling program.
this code have far not sure if correct or going in right direction:
$total = $dbh->prepare("select count(post_id) mjbox_posts"); $stmt = $dbh->prepare("select * mjbox_images join mjbox_posts using (post_id) post_id = ?"); $stmt->bindparam(1,$post_id); $stmt->execute(); $resultarray = array(); while($row = $stmt->fetch(pdo::fetch_assoc)) { for($i=0;$i<=$total;$i++){ $resultarray[] = array("id"=>$row['img_id'],"filename"=>$row['img_file_name']); } } return $resultarray; it appears data inserted array , passed calling program seems duplicate each piece of data twice in array:
array ( [0] => array ( [0] => array ( [id] => 5 [filename] => fullsize/8520430289728860armor.jpg ) [1] => array ( [id] => 5 [filename] => fullsize/8520430289728860armor.jpg ) [2] => array ( [id] => 6 [filename] => fullsize/5535575154865203bg1.jpg ) [3] => array ( [id] => 6 [filename] => fullsize/5535575154865203bg1.jpg ) [4] => array ( [id] => 7 [filename] => fullsize/7598226850012898images.jpg ) [5] => array ( [id] => 7 [filename] => fullsize/7598226850012898images.jpg ) ) )
that code broken. $total going mysql prepared statement handle, you're using in integer comparison in inner for(...) loop.
your other query wasting lot of resources fetching fields in table, when need 2 fields you're saving array.
simplify mess into:
query:
select img_id id, img_file_name filename etc.... php:
$resultarray = array(); while($row = $stmt->fetch(pdo::fetch_assoc)) { $resultarray[] = $row; }
Comments
Post a Comment