This is how I would normally run a loop with database information
$query = "SELECT * from courses ORDER BY id DESC LIMIT 4";
$stmt = $db->prepare($query);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { }
Now $row[] can be used to represent database information within the loop.
My problem is that I'll be utilizing this query a lot for separate while loops. However, I don't wish to have to complete this statement every time I require it, so I want a function to be able to refer to with any variables required.
For instance, I tried.
function retrieve_assoc_array_limit4($table) {
$user = '***';
$pass = '***';
$db = new PDO('mysql:host=localhost;dbname=***', $user, $pass);
$query = ("SELECT * FROM ? ORDER BY id DESC LIMIT 4");
$stmt = $db->prepare($query);
$stmt->bindValue(?, $table);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
return $row;
}
But when trying to while it I get an unlimited amount of returns of the same information whiled.
while($row = retrieve_assoc_array_limit4($table_name)) {
exho $data;
}
My question is how logically to use the first code in a function so that I can use it in the same with without writing out the full statement relentlessly.
many ways of doing this, to use your code with little changes:
calling fetchAll() instead of fetch():
function retrieve_assoc_array_limit4($table) {
$user = '***';
$pass = '***';
$db = new PDO('mysql:host=localhost;dbname=***', $user, $pass);
$query = ("SELECT * FROM ? ORDER BY id DESC LIMIT 4");
$stmt = $db->prepare($query);
$stmt->bindValue(?, $table);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $rows;
}
then call your function and do a while or foreach:
$rows = retrieve_assoc_array_limit4($table_name);
foreach($rows as $row){
//do your stuff
}
Related
I have multiple pages on a website that require the same data from a table. So instead of writing out an sql statement on each page I want to write a function.
Here is my function:
function getInfo($u_id) {
global $conn;
$stmt = $conn->prepare("SELECT report.*, users.* FROM report INNER JOIN users ON report.report_user_id=users.user_id WHERE report_user_id = ? ORDER BY report_id DESC LIMIT 5") or die ('Problem Preparing Query');
$stmt->bind_param("i", $u_id);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
//reports
$report_user_id = $row['report_user_id'];
$rep_date = $row['rep_date'];
$rep_location = $row['rep_location'];
$rep_notes = $row['rep_notes'];
//users
$user_id = $row['user_id'];
$username = $row['username'];
$fname = $row['user_firstname'];
$lname = $row['user_lastname'];
$user_email = $row['user_email'];
$user_image = $row['user_image'];
$user_number = $row['user_number'];
}
$stmt->close();
}
The function works, in that it fetches the data from the table but I don't know how to output the variables. Any example I have seen using prepared statements in functions are for inserting data into a table rather than fetching data.
I have tried binding the results, creating an array, returning each variable but in every case I have errors or can only return the first variable.
The function as is does not throw up any errors on its own but further down my webpage when I try to use one of the fetched variables it tells me that it is undefined.
$u_id = 1;
getInfo($u_id);
<a class="text-inherit" href="profile/index.html"><?php echo $fname .' '. $lname; ?></a>
Notice: Undefined variable: fname in....
So my question is, how can I get the variables that have been fetched in this function?
Here is a single row result solution:
function getInfo($u_id){
global $conn;
$stmt = $conn->query("SELECT * FROM report INNER JOIN users ON report.report_user_id=users.user_id WHERE report.report_user_id=$u_id ORDER BY DESC LIMIT 1") || die ('Problem Preparing Query');
if($stmt->num_rows > 0){
return $stmt->fetch_object();
}
else{
// no results were found
}
return false;
}
$obj = getInfo($u_id);
if($obj){
echo "<a class='text-inherit' href='profile/index.html'>{$obj->user_firstname} {$obj->user_lastname}</a>";
}
function getInfo($u_id) {
global $conn;
$stmt = $conn->prepare("SELECT report.*, users.* FROM report INNER JOIN users ON report.report_user_id=users.user_id WHERE report_user_id = ? ORDER BY report_id DESC LIMIT 5") or die ('Problem Preparing Query');
$stmt->bind_param("i", $u_id);
$stmt->execute();
$rows = [];
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
$stmt->close();
return $rows;
}
Of course it's not working since $fname and $lname are local variables in that function and when the function returns they are gone.
Put all of them inside an array and either return them or put them inside $GLOBAL.
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));
}
I am trying to get some distinct values from DB with ZF2 using Tablegateway.
$select = $this->sql->select($tableGateway->getTable());
$select->columns(array('city'));
$select->quantifier('DISTINCT');
$stm = $this->sql->prepareStatementForSqlObject($select);
$res = $stm->execute();
return $res;
This is returning an Iterate object, and I would like to have all the cities in an array. How can I do this ?
// whatever $select
$stm = $this->sql->prepareStatementForSqlObject($select);
$res = $stm->execute();
$resultSet = new \Zend\Db\ResultSet\ResultSet;
$resultSet->initialize($res);
foreach ($resultSet->toArray() as $row) {
// ...
}
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'];
}
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 ();