Returning Multiple Rows with MySqli and Arrays - php

For the past two days or so I've been converting my functions to mysqli. I've run into a problem. I have a function that returns an array containing a row from the database. However, I want the array to contain multiple rows versus one. Also, how would I be able to echo out the individual posts. Here is my failed attempt that only displays one row in the array.
$mysqli = new mysqli("localhost", "user", "password", "database");
function display_posts ($mysqli, $user_id) {
$fields = "`primary_id`, `poster_id`, `profile_user_id`, `post`";
$user_id = (int)$user_id;
$query = "SELECT DISTINCT $fields FROM `posts` WHERE `profile_user_id` = $user_id
LIMIT 4";
if ($result = $mysqli->query($query)) {
$row = $result->fetch_assoc();
return $row;
$result->free();
$stmt->close();
}}
Here I am trying to display the data.
$user_id = 1;
$posts = display_posts($mysqli, $user_id);
//Not sure what to do with $posts. A While loop perhaps to display each post?

You have to use a loop to get them all at once:
<?php
function resultToArray($result) {
$rows = array();
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
// Usage
$query = 'SELECT DISTINCT $fields FROM `posts` WHERE `profile_user_id` = $user_id LIMIT 4';
$result = $mysqli->query($query);
$rows = resultToArray($result);
var_dump($rows); // Array of rows
$result->free();

Why not use directly like this:
$result = mysqli_fetch_all($mysqli->query($query), MYSQLI_ASSOC);

I'm late, but I believe this is what you wanted to achieve:
$mysqli = new mysqli("localhost", "user", "password", "database");
$fields = "`primary_id`, `poster_id`, `profile_user_id`, `post`";
function display_posts () {
global $mysqli;
global $fields;
$query = "SELECT DISTINCT $fields FROM `posts` WHERE `profile_user_id` = $user_id LIMIT 4";
$posts = $mysqli -> query($query) or die('Error: '.$mysqli -> error);
if ($posts -> num_rows > 0) {
while ($row = $posts -> fetch_assoc()) {
$value = $row['/*The table column here (You can repeat this line with a different variable e.g. $value 2, $value 3 etc and matching them with the respective table column)*/'];
echo $value./*Concatenate the other variables ($value 1 etc) here*/'<br />';
}
}else {
echo 'No records found.';
}
}
//Call the function
display_posts ();

Related

PHP PDO for getting MySQL fileds name

I have a function from class that gets data from MySQL. All works OK but I also want to know how I can get the column names for MySQL data.
Here is my code :
public static function getTickets(){
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "select tickets.*,customers.* from tickets,customers where
(tickets.ticket_customer_id = customers.customer_id) order by tickets.ticket_open_date desc ";
$st = $conn->prepare($sql);
$st->execute();
$list = array();
while($row=$st->fetch()) {
$tickets = New Tickets($row);
$list[] = $tickets;
}
//total rows of customer
$sql = "select FOUND_ROWS() as totalRows";
$totalRows = $conn->query($sql)->fetch();
$conn=null;
$columnCount = $st->columnCount();
//pass the values to page
return (array("results"=>$list ,"totalRows"=>$totalRows,"columnCount"=>$columnCount));
}
It's hard to tell what you need here, but looking at your code I would say that everything you need you can get from the very data you are fetching
public static function getTickets($conn){
$sql = "select tickets.*,customers.* from tickets,customers where
(tickets.ticket_customer_id = customers.customer_id) order by tickets.ticket_open_date desc ";
$st = $conn->query($sql);
$list = array();
while($row=$st->fetch(PDO::FETCH_ASSOC)) {
$list[] = New Tickets($row);
$columnNames = array_keys($row);
}
//total rows of customer
$totalRows = count($list);
$columnCount = count($columnNames);
//pass the values to page
return (array("results"=>$list ,"totalRows"=>$totalRows,"columnCount"=>$columnCount));
}

Values stored multiple times into array

I am trying to save values from my database into an array, this works however it shows some of the values multiple times some of them 2 and other ones 3 times.
<?php
$conn = mysqli_connect("127.0.0.1", "root", "", "testdb");
$sql = ("SELECT * FROM vraag");
$result = $conn->query($sql);
// run query
$query = mysqli_query($conn, $sql);
// set array
$array = array();
// look through query
while($row = mysqli_fetch_assoc($query)){
// add each row returned into an array
$array[] = $row;
// OR just echo the data:
echo $row['vraag']; // etc
}
while ($row = mysqli_fetch_array($result)) {
foreach ($row as $columnName => $columnData) {
echo $columnData;
}
}
?>

Collect all ID's MySQL

I've done this:
$result = mysql_query("SELECT image, id FROM store WHERE username = '$username_show'");
$num_rows = mysql_num_rows($result);
$ids = mysql_fetch_assoc($result);
$ids = $ids['id'];
for ($i = 0; $i < $num_rows; $i++) {
echo "<img src='get.php?id=$ids[$i]' height='300'><p/>";
}
I want to show all of my photos that has that username. But the $ids array only gets one index, and that's the last ID. What am I doing wrong?
Like #Matthew said thet are deprecated use :
// mysqli
$mysqli = new mysqli("example.com", "user", "password", "database");
$result = $mysqli->query("SELECT image, id FROM store WHERE username = '$username_show'");
$row = $result->fetch_assoc();
echo htmlentities($row['row']);
// PDO
$pdo = new PDO('mysql:host=example.com;dbname=database', 'user', 'password');
$statement = $pdo->query("SELECT image, id FROM store WHERE username = '$username_show'");
$row = $statement->fetch(PDO::FETCH_ASSOC);
echo htmlentities($row['row']);
To answer your comment :
- use the array function
$result_array = array();
while($row = mysql_fetch_assoc($result))
{
$result_array[] = $row;
}
$result = $mysqli->query("SELECT id FROM store WHERE username = '$username_show'");
$result_array = array();
while($row = mysqli_fetch_assoc($result))
{
$result_array[] = $row;
}

how to properly use while loop in PDO fetchAll

please be easy on me, i just started learning PDO and still finding my way how to convert my mysqli to PDO.
so i have a function to get the contents from my database
function getContent() {
$db = PDOconn();
$query = "SELECT * FROM posts ORDER BY id DESC LIMIT 0,3";
$sql = $db->prepare($sql);
$row = $sql->fetchAll(PDO::FETCH_ASSOC);
return $row;
}
normally when i return $row in mysqli, i would define fetch_assoc() in my while loop.
while ($row = $result->fetch_assoc()) {
$id = $row['id'];
$content = $row['content'];
}
Now, since (PDO::FETCH_ASSOC) is already declared in my function.
how would i properly create my while loop to print the values in PDO?
[edit]
updated code
i will be declaring my while loop outside of the function. so i need something to return from my function but i dont know what that is..
function getContent() {
$db = PDOconn();
$query = "SELECT * FROM posts ORDER BY id DESC LIMIT 0,3";
$sql = $db->prepare($query);
$row = $sql->execute();
return $row;
}
this is my while loop outside the function.
$sql = getContent();
while ($row = $sql->fetchAll(PDO::FETCH_ASSOC)) {
$id = $row['id'];
$content = $row['content'];
}
With fetchAll() you don't have to use while at all. As this function returns an array, you have to use foreach() instead:
function getContent() {
$db = PDOconn();
$query = "SELECT * FROM posts ORDER BY id DESC LIMIT 0,3";
$sql = $db->prepare($query);
$sql->execute();
return $sql->fetchAll();
}
$data = getContent();
foreach($data as $row) {
$id = $row['id'];
$content = $row['content'];
}

PHP PDO can't update records in foreach loop

Script searchs through DB and fix broken links. Search and replace functionality works fine, but when trying to save updated data scripts wrights only first raw. I'm stucked! I can use simple mysql_query commands to update data, but needs PDO...
header('Content-Type: text/html; charset=UTF-8');
error_reporting(E_ALL);
echo "Welcome";
$mysql = new PDO('mysql:host=localhost;dbname=db_name;charset=UTF-8','user','12345');
if (!$mysql) die('Can\'t connect');
$tables = array(
'categories',
'news',
'pages'
);
function getContent($table) {
global $mysql;
$fieldnum = 0;
$fields = array();
$vals = array();
$st = $mysql->query("SHOW FIELDS FROM `{$table}`");
while ($row = $st->fetch(PDO::FETCH_ASSOC)) {
$fields[$fieldnum]=$row["Field"];
$fieldnum++;
}
$totalfields=$fieldnum;
$res = $mysql->query("SELECT * FROM `{$table}`");
$sql = "UPDATE `:table` SET :field = ':val' WHERE `:idf` = :id;";
while ($row = $res->fetch(PDO::FETCH_NUM)) {
for ($j=0; $j<$res->columnCount();$j++) {
$rs = str_replace('index.php/','',$row[$j],$m);
if ($rs && $m>0) {
if ($table == 'categories')
$prim= 'cat_id';
elseif($table == 'news') $prim= 'news_id';
elseif($table == 'pages') $prim= 'page_id';
else $prim= $table.'_id';
$upd = $mysql->prepare($sql);
$update = $upd->execute(array(
':table'=>$table,
':field'=>$fields[$j],
':val'=>$rs,
':idf'=>$prim,
':id'=>$row[0]
));
}
}
}
}
foreach ($tables as $t) {
getContent($t);
}
Need help to fix it!
try to fetch all and then go through array
and you do not need to use prepare every time - just once see Example #2
....
$res = $mysql->query("SELECT * FROM `{$table}`");
$rows = $res->fetchAll(PDO::FETCH_NUM);
$sql = "UPDATE `:table` SET :field = ':val' WHERE `:idf` = :id;";
$upd = $mysql->prepare($sql);
foreach ($rows as $row) {
foreach ($row as $col_name => $value) {
......
prepare outside the loop! you are loosing its value this way, also try $upd->debugDumpParams(); and binding before execution, maybe the values u r binding is not right.

Categories