I tried to get followers from MySQL usingy this class
class get_followers {
public $followers_arr = array();
public function __construct($user_id) {
$query = "select * from followsystem where following ='$user_id'";
$q = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($q);
if ($count > 0) {
while ($row = mysql_fetch_assoc($q)) {
array_push($this->followers_arr, $row['userid']);
}
}
return $this->followers_arr;
}
}
Then I initialize this class
$fol = new get_followers($userid);
$fol_arr = json_encode($fol);
echo $fol_arr;
Then I get
{"followers_arr":["1234","456"]}
but what i want want just to get this
["1234","456"]
How is that works?
I don't think you understand how constructors work. You can't return a value from a constructor because it's just used to instantiate the object. When you're doing $fol_arr = json_encode($fol); you're actually encoding the entire object, not it's return value.
If you really want to use a class to do this, you should add a method to the class and use that, like this:
class Followers {
public $followers_arr = array();
public $user_id = null;
public function __construct($user_id) {
$this->user_id = $user_id;
}
public function get()
{
$query = "select * from followsystem where following ='{$this->user_id}'";
$q = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($q);
if ($count > 0) {
while ($row = mysql_fetch_assoc($q)) {
array_push($this->followers_arr, $row['userid']);
}
}
return $this->followers_arr;
}
}
And use it like this:
$fol = new Followers($userid);
$fol_arr = json_encode($fol->get());
echo $fol_arr;
The solution to your problem is to do $fol_arr = json_encode($fol->followers_arr);
Nonetheless, making a class in this case is completely obsolete, since you only make it as a wrapper for a single function you want to execute (called get_followers) Instead of making a class, you could simply make the following:
function get_followers($user_id) {
$followers_arr = [];
$query = "select * from followsystem where following ='$user_id'";
$q = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($q);
if ($count > 0) {
while ($row = mysql_fetch_assoc($q)) {
array_push($followers_arr, $row['userid']);
}
}
return $followers_arr;
}
$fol = get_followers($userid);
$fol_arr = json_encode($fol);
echo $fol_arr;
There is no need to put it in a class unless the class serves the purpose of combining a few functions and variables to create a behaviour.
Related
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;
I have created the following function to fetch data from my database, but its capabilities are limited. Currently it can fetch one value at a time, which is fine for fetching the value of one column of one row, but as I progress with my work, I now want to be able to fetch multiple values in one call.
The Function:
function retrieve($value, $identifier = null) {
// Check if identifier is given
$identifier = (is_null($identifier)) ? "`ID` = '{$_SESSION["ID"]}'" : $identifier;
// Connect to the database
$connection = connect("limited");
// Pass query, get result and fetch value out of it
$query = "SELECT * FROM `users` WHERE $identifier";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
$data = mysqli_fetch_assoc($result);
return $data[$value];
}
mysqli_close($connection);
}
How I currently use it to fetch multiple values:
// Define variables
$x1 = retrieve("x1");
$x2 = retrieve("x2");
$x3 = retrieve("x3");
$x4 = retrieve("x4");
$x5 = retrieve("x5");
$x6 = retrieve("x6");
$x7 = retrieve("x7");
$x7 = retrieve("x8");
I have read other questions here on Stack Overflow, but none of them solves my problem as I use an optional parameter, which makes my life hard. For example, I thought of implementing the splat operator to allow unlimited parameters, but as I use the optional parameter $identifier, I can't make it into something like:
function retrieve($identifier = null, ...$value) {}
because it will use the first parameter as the identifier when I omit it.
I'm sure that regarding performance it would be better if I could fetch all the necessary values in one call of the function retrieve() instead of using it as shown above and that's why I would like to know:
How can I edit this function in order to fetch more values at once?
Calling it like so:
$x = retrieve($y);
$x1 = $y["x1"];
$x2 = $y["x2"];
...
EDIT:
Thanks to Manish Jesani for his help! I used his answer and modified to do exactly what I want. For anyone that may be interested in the future, here's the code:
function retrieve($value, $identifier = null) {
// Check if identifier is given
$values = array();
$identifier = (is_null($identifier)) ? "`ID` = '1'" : $identifier;
// Connect to the database
$connection = connect("limited");
// Pass query, get result and fetch value out of it
$query = "SELECT * FROM `users` WHERE $identifier";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
$data = mysqli_fetch_assoc($result);
if (is_array($value)) {
foreach($value as $_value) {
$values[$_value] = $data[$_value];
}
return $values;
}
else {
return $data[$value];
}
}
mysqli_close($connection);
}
You can call the function with as many parameters you want. Τo do this you have to use func_num_args() to get all of them, as shown below:
function retrieve() {
$args = func_num_args();
$query = "SELECT '".implode("','", func_get_args())."' FROM `users` WHERE $identifier";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
$data = mysqli_fetch_assoc($result);
return $data;
}
mysqli_close($connection);
}
You can call this function like this: $params = retrieve('x1','x2','x3').
Alternatively, you can retrieve them as variables list($x1, $x2, $x3) = retrieve('x1','x2','x3').
Please try this:
function retrieve($value, $identifier = null) {
// Check if identifier is given
$return = array();
$identifier = (is_null($identifier)) ? "`ID` = '{$_SESSION["ID"]}'" : $identifier;
// Connect to the database
$connection = connect("limited");
// Pass query, get result and fetch value out of it
$query = "SELECT * FROM `users` WHERE $identifier";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
$data = mysqli_fetch_assoc($result);
if(is_array($value))
{
foreach($value as $_value)
{
$return[$_value] = $data[$_value];
}
}
else
{
$return[$value] = $data[$value];
}
return $return;
}
mysqli_close($connection);
}
$x = retrieve(array("x1","x2","x3","x4","x5","x6"));
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();
}
the code is as follow:
Class userinfo {
function fetchdatabyemail($email) {
$result=mysql_query(" SELECT * FROM users WHERE email='$email'");
while($row = mysql_fetch_array($result)) {
$name = $row['name'];
$num = $row['num'];
$city = $row['city'];
}
$numrows= mysql_num_rows($result);
}
}
now to get the info I do this :
$info = new userinfo();
$info->fetchdatabyemail('email#email.com');
echo $info->city;
and it doesnt return the info. I think Im doing something wrong any ideas please
do it
public $numrows;
public function fetchDataByEmail($email) {
$result=mysql_query(" SELECT * FROM users WHERE email='$email'");
while($row = mysql_fetch_assoc($result)) {
$fetch[] = $row;
}
$this->numrows = mysql_num_rows($result);
return $fetch;
}
then
$info = new userinfo();
$detail = $info->fetchDataByEmail('email#email.com');
print_r($detail); // return all result array
$info->numrows; // will return number of rows.
Your variable working locally. You need to assign it in class level.
Your code should be:
Class userinfo {
public $name,$city,$num,$numrows;
function fetchdatabyemail($email) {
$result=mysql_query(" SELECT * FROM users WHERE email='$email'");
while($row = mysql_fetch_array($result)) {
$this->name = $row['name'];
$this->num = $row['num'];
$this->city = $row['city'];
}
$this->numrows= mysql_num_rows($result);
}
Then get to the info using this:
$info = new userinfo();
$info->fetchdatabyemail('email#email.com');
echo $info->city;
}
You should have a private variable and getter/setter for it (this is the proper way, see code below). You could also declare $city as a public variable and access directly to it from the class' instance.
class userinfo
{
private $city = '';
public function getCity()
{
return $this->city;
}
public function fetchDataByEmail($email)
{
// Your code here
$this->city = $row['city'];
}
}
$info = new userinfo();
$info->fetchDataByEmail('someone#example.com');
echo 'City: '.$this->getCity();
I think your problem is the scope/visbility of your variables think you need to declare them outside of the scope of the function:
http://www.php.net/manual/en/language.oop5.visibility.php
class userinfo {
public $name;
public $num;
public $city;
public $numrows;
function fetchdatabyemail($email) {
$result=mysql_query(" SELECT * FROM users WHERE email='$email'");
while($row = mysql_fetch_array($result)) {
this->$name = $row['name'];
this->$num = $row['num'];
this->$city = $row['city'];
}
this->$numrows= mysql_num_rows($result);
}
}
You need to first declare the class variables.
class Userinfo {
$city;
// then declare the function
}
The way you were doing it, the scope of $city was only within the function, not stored as a field
while loop in each iteration is updating info.
so, u can echo in the while like
function fetchdatabyemail($email) {
$result=mysql_query(" SELECT * FROM users WHERE email='$email'");
while($row = mysql_fetch_array($result)) {
echo $row['city'];
}
or can store values in an array which is globally declared in the class and than echo the array.
in your code you have $city declared with local function scope which is not accessible from class $info->city.
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