mysqli_fetch_assoc in object - php

how to do array in object or with arrow to right. sorry i'm still a junior
this is function and worked
function check_level($id) {
global $connect;
$query = "SELECT level FROM s_user WHERE id='$id'";
$result = $connect->query($query);
$level = mysqli_fetch_assoc($result) ['level'];
return $level;
}
I was try like this but error, idk how to array in object
function check_level($id) {
global $connect;
$query = "SELECT level FROM s_user WHERE id='$id'";
$result = $connect->query($query);
$level = $result->fetch_object(['level']);
return $level;
}
can you help me ? thanks.

You may have solved it already. But here's the function anyway, that checks if there is a result before returning a value.
This function returns NULL if no record retrieved.
function check_level($id) {
global $connect;
$level = NULL;
$stmt = $connect->prepare("SELECT level FROM s_user WHERE id= ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
if($result){
if($result->num_rows > 0){
$row = $result->fetch_object();
$level = $row->level; // this
}
}
else {
echo "MySQL Error: ".$connect->error;
}
return $level;
}
The function also uses prepared statement to prevent sql injection attacks.

Read more about sql injection. You have to prepare and bind the parameter as code above. The $stmt is only "statement" or variable.

Related

Returning variables from a prepared statement function PHP

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.

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'];
}

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 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'];
}

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