Return all values in a column - php

I am trying to return all the productnames from my MySQL table. At the moment this only returns the first name in the column
public function selectAll ()
{
$stmt = Database::get()->query('SELECT * FROM retrofootball_products');
while($row = $stmt->fetch())
{
return $row['productname'];
}
}
How do I get it to loop through and select all the productnames?

One way you could do is just select only the productname column, and then use $stmt->fetchAll(PDO::FETCH_ASSOC).
public function selectAll ()
{
$stmt = Database::get()->query('SELECT `productname` FROM retrofootball_products');
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

do:
public function selectAll () {
$stmt = Database::get()->query('SELECT * FROM retrofootball_products');
$allCols = array();
while($row = $stmt->fetch()) {
$allCols[] = $row['productname'];
}
return $allCols;
}

You are directly returning first value that was causing the problem.
Store each record in array and return that array.
public function selectAll ()
{
$stmt = Database::get()->query('SELECT * FROM retrofootball_products');
while($row = $stmt->fetch())
{
$arr[] = $row['productname'];
}
return $arr;
}

You can just avoid looping through as you're using PDO and use fetchAll.
public function selectAll ()
{
$stmt = Database::get()->query('SELECT * FROM retrofootball_products');
return $stmt->fetchAll();
}
http://php.net/manual/en/pdostatement.fetchall.php

While I'm new to stmp too, I imagine this might work
$result = $stmt->get_result();
while ($row = $result->fetch_assoc())
{
// do something with $row
}

Related

fetch_assoc() returning only first row [duplicate]

This question already has answers here:
return inside foreach php and laravel
(2 answers)
Closed 3 years ago.
Im fairly new to OOP way of coding and I want to fetch a record of users in my DB
This is my code below:
$con = new mysqli('localhost', 'root', '', 'goldpalace');
class User {
public $connect;
public function get_users() {
$sql = "SELECT * from users";
$result = $this->connect->query($sql);
$num_rows = $result->num_rows;
if ($num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$data[] = $row;
return $data;
}
}
}
}
$obj = new User();
$obj->connect = $con;
$user_data = $obj->get_users();
foreach ($user_data as $value) {
echo $value['name']."<br>";
}
I have a lot of records in my DB but it only returns the first row.
That's because you return the value of $data immediately after you retrieve one row. return will return that value and stop execution of that method. You need to return that value after you are done retrieving your values.
class User {
public $connect;
public function get_users() {
$sql = "SELECT * from users";
$result = $this->connect->query($sql);
$num_rows = $result->num_rows;
$data = [];
if ($num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$data[] = $row;
}
}
return $data;
}
}
FYI, you can use fetch_all() here to make this a bit simpler:
class User {
public $connect;
public function get_users() {
$sql = "SELECT * from users";
$result = $this->connect->query($sql);
$num_rows = $result->num_rows;
$data = [];
if ($num_rows > 0) {
$data = $result->fetch_all(MYSQLI_ASSOC);
}
return $data;
}
}
For you return in the first cycle in while
while ($row = $result->fetch_assoc()) {
$data[] = $row;
return $data;
}
just move the return out of while loop
while ($row = $result->fetch_assoc()) {
$data[] = $row;
}
return $data;

How to get multiple rows from mysql & PHP with this function

I have this function which returns only one row, How can I modify the function so that it returns more than one row?
public function getVisitors($UserID)
{
$returnValue = array();
$sql = "select * from udtVisitors WHERE UserID = '".$UserID. "'";
$result = $this->conn->query($sql);
if ($result != null && (mysqli_num_rows($result) >= 1)) {
$row = $result->fetch_array(MYSQLI_ASSOC);
if (!empty($row)) {
$returnValue = $row;
}
}
return $returnValue;
}
There is a function in mysqli to do so, called fetch_all(), so, to answer your question literally, it would be
public function getVisitors($UserID)
{
$sql = "select * from udtVisitors WHERE UserID = ".intval($UserID);
return $this->conn->query($sql)->fetch_all();
}
However, this would not be right because you aren't using prepared statements. So the proper function would be like
public function getVisitors($UserID)
{
$sql = "select * from udtVisitors WHERE UserID = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $UserID);
$stmt->execute();
$res = $stmt->get_result();
return $res->fetch_all();
}
I would suggest storing them in an associative array:
$returnValue = array();
while($row = mysqli_fetch_array($result)){
$returnValue[] = array('column1' => $row['column1'], 'column2' => $row['column2']); /* JUST REPLACE NECESSARY COLUMN NAME AND PREFERRED NAME FOR ITS ASSOCIATION WITH THE VALUE */
} /* END OF LOOP */
return $returnValue;
When you call the returned value, you can do something like:
echo $returnValue[0]['column1']; /* CALL THE column1 ON THE FIRST SET OF ARRAY */
echo $returnValue[3]['column2']; /* CALL THE column2 ON THE FOURTH SET OF ARRAY */
You can still call all the values using a loop.
$counter = count($returnValue);
for($x = 0; $x < $counter; $x++){
echo '<br>'.$rowy[$x]['column1'].' - '.$rowy[$x]['column2'];
}

Pass table variable to SELECT function

I have a getData() function, and a database with two tables: employers and members.
I would like to pass a variable containing the table name, so inside an "if" I could execute the appropriate SELECT statement. My problem I believe that after the "if" the $stmt->bind_param(); doesn't know which $stmt to bind the take.
Any ideas on how I could achieve this?
Thanks
public function getData($table)
{
if ($table == "employers")
{
$stmt = $this->link->prepare("SELECT * FROM employers ");
}
else
{
$stmt = $this->link->prepare("SELECT * FROM members ");
}
$stmt->bind_param();
if ($stmt->execute())
{
$result = $stmt->get_result();
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
$row = array_map('stripslashes', $row);
$dataArray[] = $row;
}
}
return $dataArray;
}
No, since you aren't binding anything, that ->bind_param method is superfluous. Just take that off.
public function getData($table)
{
$dataArray = array();
$t = ($table === 'employers') ? 'employers' : 'members';
$query = "SELECT * FROM $t";
$stmt = $this->link->prepare($query);
if($stmt->execute()) {
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
$row = array_map('stripslashes', $row);
$dataArray[] = $row;
}
}
return $dataArray;
}
Sample Usage:
$data = $aministrator_query->getData('members');
$tbody = '';
foreach($data as $row) {
$tbody .= "<tr><td>{$row['user_id']}</td><td>{$row['user_password']}</td><td>{$row['user_first_name']}</td><td>{$row['user_last_name']}</td></tr>";
}
$table = sprintf('<table><thead><tr><th>ID</th><th>Password</th><th>First Name</th><th>Last Name</th></tr></thead><tbody>%s</tbody></table>', $tbody);
echo $table;

PHP to loop records from class method

I got below class to fetch records in database, how can use foreach to loop all data in page?
class User{
public function get_user_listing($user_id, $mysqli){
$sql = $mysqli->query("SELECT * FROM `listing` WHERE user_id='".$user_id."'");
if($sql->num_rows > 0){
return $query->result();
}else{
return false;
}
}
}
in my page, if I call:
$user = new User;
$listing = $user->get_user_listing($user_id, $mysqli);
foreach(listing as $value){
echo $value->table_field;
}
But I think that is not a correct way.
You need to return the actual result $sql:
if($sql->num_rows > 0){
return $sql;
} else {
return false;
}
Since you are returning a result set you need to fetch rows:
$user = new User;
$listing = $user->get_user_listing($user_id, $mysqli);
while($row = $listing->fetch_object()){
echo $row->table_field;
}
Or you could add the fetch loop to the class function and return an array of $row[] objects.
Also, I would make some changes here:
private $mysqli;
public function __construct($mysqli) {
$this->mysqli = $mysqli;
}
public function get_user_listing($user_id) {
$mysqli = $this->mysqli;
//or just use $sql = $this->mysqli->query("SELECT * FROM `listing` WHERE `user_id` = '$user_id'");
//etc...
}
Then:
$user = new User($mysqli);
$listing = $user->get_user_listing($user_id);
Better use a prepared statement to protect from SQL injection. And check the returned value from get_user_listing for false or undef.
public function get_user_listing($user_id, $mysqli){
$sql = "SELECT * FROM `listing` WHERE user_id=?";
if ($stmt = $conn->prepare($sql)) {
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
return $result;
}
}
$user = new User;
$result = $user->get_user_listing($user_id, $mysqli);
if(isset($result))
{
while ($row = $result->fetch_assoc()) {
print $row['table_field'];
}
/* free result set */
$result->free();
}

how to make function in php with mysql result?

I am using same query again and again on different pages in between to fetch result. I want to make a function for this query.
$result = mysql_query(" SELECT name FROM tablename where id= '$row[name_id]'");
$row = mysql_fetch_array($result);
echo $row ['name'];
How to make and how to call the function?
sample class stored sample.php
class sample
{
function getName(id)
{
$result = mysql_query("SELECT name FROM tablename where id='$id'");
$row = mysql_fetch_array($result);
return $row ['name'];
}
}
use page include sample.php,then create object,then call getName() function.
<?php
include "db.class.php";
include "sample.php";
$ob=new sample(); //create object for smaple class
$id=12;
$name=$ob->getName($id); //call function..
?>
This is a good idea but first of all you have to create a function to run queries (as you have to run various queries way more often than a particular one)
function dbget() {
/*
easy to use yet SAFE way of handling mysql queries.
usage: dbget($mode, $query, $param1, $param2,...);
$mode - "dimension" of result:
0 - resource
1 - scalar
2 - row
3 - array of rows
every variable in the query have to be substituted with a placeholder
while the avtual variable have to be listed in the function params
in the same order as placeholders have in the query.
use %d placeholder for the integer values and %s for anything else
*/
$args = func_get_args();
if (count($args) < 2) {
trigger_error("dbget: too few arguments");
return false;
}
$mode = array_shift($args);
$query = array_shift($args);
$query = str_replace("%s","'%s'",$query);
foreach ($args as $key => $val) {
$args[$key] = mysql_real_escape_string($val);
}
$query = vsprintf($query, $args);
if (!$query) return false;
$res = mysql_query($query);
if (!$res) {
trigger_error("dbget: ".mysql_error()." in ".$query);
return false;
}
if ($mode === 0) return $res;
if ($mode === 1) {
if ($row = mysql_fetch_row($res)) return $row[0];
else return NULL;
}
$a = array();
if ($mode === 2) {
if ($row = mysql_fetch_assoc($res)) return $row;
}
if ($mode === 3) {
while($row = mysql_fetch_assoc($res)) $a[]=$row;
}
return $a;
}
then you may create this particular function you are asking for
function get_name_by_id($id){
return dbget("SELECT name FROM tablename where id=%d",$id);
}
You should probably parse the database connection as well
$database_connection = mysql_connect('localhost', 'mysql_user', 'mysql_password');
function get_row_by_id($id, $database_link){
$result = mysql_query("SELECT name FROM tablename where id= '{$id}");
return mysql_fetch_array($result);
}
Usage
$row = get_row_by_id(5, $database_connection);
[EDIT]
Also it would probably help to wrap the function in a class.
function getName($id){
$result = mysql_query("SELECT name FROM tablename where id= '$row[name_id]'");
$row = mysql_fetch_array($result);
return $row ['name'];
}
call the function by
$id = 1; //id number
$name = getName($id);
echo $name; //display name

Categories