I have a class called Person, with its getters and setters, and I want to know how I can return a List from Data Layer. In C# I use List and I can return the list, but in PHP I don't know how.
function AllPersons()
{
try
{
$objConn = new Connection();
$conn = $objConn ->Connect();
$sql = "SELECT * FROM PERSON";
$answer= mysqli_query($cn, $sql);
if(mysqli_num_rows($answer) > 0)
{
while($row = mysqli_fetch_array($answer))
{
/*here i want to do something like in C#
List<Person>listPerson;
listPerson.add(objPerson);*/
}
}
else
{
return null;
}
}
catch (Exception $e)
{
//FB::log("nada");
}
}
Create an array and fill it.
listPerson = [];
while($row = mysqli_fetch_array($answer)) {
listPerson[] = new Person($row);
}
In PHP arrays replace the use of Lists/Arrays you'd use in .NET.
They're really flexible when it comes down to mutations.
In this case you'd probably approach it like:
...
$persons = array();
while($row = mysqli_fetch_array($answer))
{
// Using [] appends the content of $row to the $persons array.
$persons[] = $row;
}
...
Read more about the flexibility of PHPs arrays here.
List is a dimensionless array in C# (Can also be used in dimensional). The arrays in PHP also dimensionless. So you can use arrays.
...
$listPerson = array();
while($row = mysqli_fetch_array($answer))
{
$listPerson[] = objPerson;
}
...
function AllPersons()
{
try
{
$objConn = new Connection();
$conn = $objConn ->Connect();
$sql = "SELECT * FROM PERSON";
$answer= mysqli_query($cn, $sql);
if(mysqli_num_rows($answer) > 0)
{
while($row = mysqli_fetch_array($answer))
{
print_r($row);
}
}
else
{
return null;
}
}
catch (Exception $e)
{
//FB::log("nada");
}
}
Related
While doing a PHP function using two mysql query, the second one returns null, which shouldn't have, since both of them works in phpmyadmin SQL query submition.
Here is the function:
public static function getStates($countryId) {
try {
$query = "SELECT * FROM `Apostas` WHERE `idConfronto` = ".$countryId;
$result = dbconfig::run($query);
if(!$result) {
throw new exception("Confronto invalido.");
}
$res = array();
while($resultSet = mysqli_fetch_assoc($result)) {
$sql2 = "SELECT * FROM `Mercados` WHERE `idMercado` = ".$resultSet["idMercado"];
$result2 = dbconfig::run($sql2);
if(!$result2) {
throw new exception("Não há mercados.");
}
while ($row2 = mysqli_fetch_assoc($result2)) {
$res[$resultSet['idMercado']] = $row2['nomeMercado'];
}
}
$data = array('status'=>'success', 'tp'=>1, 'msg'=>"States fetched successfully.", 'result'=>$res);
} catch (Exception $e) {
$data = array('status'=>'error', 'tp'=>0, 'msg'=>$e->getMessage());
} finally {
return $data;
}
}
The first query works everytime, but the second one goes towards the exception "Não há mercados".
After debugging the function the variable $resultSet["idMercado"] is working and the sql query also works, but the code results in the exception.
What I'm doing wrong? Perhaps something with the syntax?
--EDIT1:
As requested, the code for dbconfig::run:
public static function run($query) {
try {
if(empty($query) && !isset($query)) {
throw new exception("Query string is not set.");
}
$result = mysqli_query(self::$con, $query);
self::close();
return $result;
} catch (Exception $e) {
echo "Error: ".$e->getMessage();
}
}
--EDIT2:
As Cavid suggested, do all querys before closing the connection, here is how the function turned out:
public static function getStates($countryId) {
try {
$query = "SELECT * FROM `Apostas` WHERE `idConfronto` = ".$countryId;
$result = $conn->query($query);
if(!$result) {
throw new exception("Confronto invalido.");
}
$res = array();
if ($result->num_rows > 0) {
while ($resultSet = $result->fetch_assoc()) {
$sql2 = "SELECT * FROM `Mercados` WHERE `idMercado` = ".$resultSet['idMercado'];
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
while ($row2 = $result2->fetch_assoc()) {
$res[$resultSet['idMercado']] = $row2['nomeMercado'];
}
}
}
}
$data = array('status'=>'success', 'tp'=>1, 'msg'=>"States fetched successfully.", 'result'=>$res);
} catch (Exception $e) {
$data = array('status'=>'error', 'tp'=>0, 'msg'=>$e->getMessage());
} finally {
return $data;
}
$conn->close();
}
Its giving me now a error code 500 "Internal server error"
Instead of going in two different tables that has a Reference id in both, i suggest you to JOIN them and only use one while loop:
public static function getStates($countryId) {
try {
// Inner join both tables
$query = "SELECT a.idMercado, a.idConfronto, b.nomeMercado FROM Apostas AS a ";
$query .= "INNER JOIN ";
$query .= "Mercados AS b ";
$query .= "ON a.idMercado = b.idMercado ";
$query .= "WHERE a.idConfronto = " . $countryId;
$result = dbconfig::run($query);
if(!$result) {
throw new exception("Confronto invalido.");
}
// Results
$res = array();
while ($row = mysqli_fetch_assoc($result)) {
$res[$row['idMercado']] = $row['nomeMercado'];
}
$data = array('status'=>'success', 'tp'=>1, 'msg'=>"States fetched successfully.", 'result'=>$res);
} catch (Exception $e) {
$data = array('status'=>'error', 'tp'=>0, 'msg'=>$e->getMessage());
} finally {
return $data;
}
}
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.
I'm having some issue with two functions at the moment; I'm trying to get an array to pass from the first function to the other--but for some reason I cannot get it to work.
function getResourceXML($id)
{
$xml = simplexml_load_file('resources.xml');
foreach($xml->children()->children() as $children)
{
if($children['id'] == $id)
{
$resource[] = $children["income"];
return $resource;
}
}
}
function getResourceMultiplier()
{
$sql = "SELECT resourceArray FROM starinformation WHERE starOwner = :uid";
$que = $this->db->prepare($sql);
$que->bindParam('uid', $this->uid);
try
{
$que->execute();
while($row = $que->fetch(PDO::FETCH_BOTH))
{
$resource = $this->getResourceXML($row[0]);
return $resource;
}
}
catch(PDOException $e) {}
}
Move the return statement to after the loop } in both functions or else you only get one loop iteration. Also, in getResourceMultiplier() you're not creating an array. You need (or similar):
$resource[] = $this->getResourceXML($row[0]);
I am working on an MLM application in which i need to show all users as a tree. For this is implemented parent child relationship among the users. my table structure is here :-
I had retrieve the id's of users in a multidimensional array as per the relation. Here is array:-
For this i used this code :-
<?php
$con = mysql_connect('localhost', 'root', '');
mysql_select_db('testapp', $con);
function create_tree( $parent_id = 0 )
{
$result_array = array();
$Query = 'SELECT * FROM `user` WHERE `parent`=\''.$parent_id.'\';';
$query_result = mysql_query($Query);
if(mysql_num_rows($query_result)>0)
{
while($row = mysql_fetch_assoc($query_result))
{
if(!array_key_exists($row['user_id'], $result_array))
{
//$result_array[$row['user_id']] = $row;
$result_array[$row['user_id']] = create_tree($row['user_id']);
}
}
}
return $result_array;
}
$tree = create_tree();
print_r($tree);
Now, i need to show the data in a tree structure like :-
Any hint will be helpful. I am very near to complete this...
Yes, you are so near..!!
Try below it will be work for you..
<?php
$con = mysql_connect('localhost', 'root', '');
mysql_select_db('testapp', $con);
function create_tree( $parent_id = 0 ,$result_array = array())
{
$Query = 'SELECT * FROM `user` WHERE `parent`=\''.$parent_id.'\';';
$query_result = mysql_query($Query);
if(mysql_num_rows($query_result)>0)
{
while($row = mysql_fetch_assoc($query_result))
{
if(!array_key_exists($row['user_id'], $result_array))
{
//$result_array[$row['user_id']] = $row;
$result_array[$row['user_id']] = create_tree($row['user_id'],$result_array);
}
}
}
return $result_array;
}
$tree = create_tree();
print_r($tree);
?>
If this will not work for you than let me know..!!
Thanks..
try that, it should give you the structure;
function create_tree( $parent_id = 0 , $result_array = array() )
{
//$result_array = array();
$Query = 'SELECT * FROM `user` WHERE `parent`=\''.$parent_id.'\';';
$query_result = mysql_query($Query);
if(mysql_num_rows($query_result)>0)
{
while($row = mysql_fetch_assoc($query_result))
{
if(!array_key_exists($row['user_id'], $result_array))
{
//$result_array[$row['user_id']] = $row;
$result_array[$row['user_id']] = create_tree($row['user_id'], $result_array[$row['user_id']]);
}
}
}
return $result_array;
}
edit; forgot the remove result_array in function
I was wondering if someone could help me with this problem.
I want to print/echo the solution of the function multiple times on the same page. Is that possible?
Here's my function:
public function getFeedback($p_iUserid) {
include("Connection.php"); //open db
try
{
$sql = "select DiaryOpmerkingen, DiaryDoctorcomment from tblDiary
WHERE fk_UserId = ".$p_iUserid."
AND DiaryDay = '".$this->Day."';";
$rResult = mysqli_query($link, $sql);
return $rResult;
}
catch(Exception $e)
{
// no connection database
$feedback = $e->getMessage();
}
mysqli_close($link);
}
And this is how I manage to call on the function by now. But it only works once:
if(mysqli_num_rows($feedbackPatient) > 0)
{
while($oUser = mysqli_fetch_assoc($allUsers))
{
echo $oUser['DiaryOpmerkingen'];
}
}
I hope someone can help!
Thanks anyway.
Create a function for your printing task, then call it as many times as you want:
function print_the_stuff($feedbackPatient){
if(mysqli_num_rows($feedbackPatient) > 0)
{
while($oUser = mysqli_fetch_assoc($allUsers))
{
echo $oUser['DiaryOpmerkingen'];
}
}
}
Then, wherever you need to print:
print_the_stuff($feedbackPatient);
The easiest way to do this is probably to get the whole result set in one go, and then pass that around.
This might be costly in terms of performance if the result set is large, but it's probably not going to make a significant difference. It is particularly easy with the mySqli extension, because you can use mysql_fetch_all.
public function getFeedback($p_iUserid) {
include("Connection.php"); //open db
try
{
$sql = "select DiaryOpmerkingen, DiaryDoctorcomment from tblDiary
WHERE fk_UserId = ".$p_iUserid."
AND DiaryDay = '".$this->Day."';";
$rResult = mysqli_query($link, $sql);
return mysqli_fetch_all($rResult, MYSQLI_ASSOC);
}
catch(Exception $e)
{
// no connection database
$feedback = $e->getMessage();
}
mysqli_close($link);
}
You would then get an associative array returned from getFeedback, and could loop through this as normal:
$feedback = getFeedback($id);
foreach ($feedback as $item) {
echo $item['DiaryOpmerkingen'];
}
I think it should be :
$feedbackPatient = getFeedback($p_iUserid);
if(mysqli_num_rows($feedbackPatient) > 0)
{
while($oUser = mysqli_fetch_assoc($feedbackPatient))
{
echo $oUser['DiaryOpmerkingen'];
}
}
why are u using diff result for mysqli_num_rows and sqli_fetch_assoc ?