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]);
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 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");
}
}
I have the following code that calls a DB function that retrieves all rows from a table and then echo's them in JSON.
$key = $db->getKeyPermissions();
if ($key != false) {
// use is found
$response["error"] = FALSE;
$response["key"]["endpoint_name"] = $key["endpoint_name"];
$response["key"]["live"] = $key["live"];
$response["key"]["activity_name"] = $key["activity_name"];
echo json_encode($response);
} else {
This is the DB function
public function getKeyPermissions()
{
$stmt = $this->conn->prepare("SELECT * FROM key_permissions WHERE 1");
if ($stmt->execute()) {
$key = $stmt->get_result()->fetch_assoc();
$stmt->close();
return $key;
} else {
return NULL;
}
}
This all works fine except that it only returns the first row and then stops. Read that you have to loop the fetch_assoc() but I couldn't get this working. I would like all rows to be pushed into $key and returned, but all attempts result in an array conversion and non-object errors. Can somebody help me along the way?
EDIT:
public function getKeyPermissions()
{
$stmt = $this->conn->prepare("SELECT * FROM key_permissions WHERE 1");
if ($stmt->execute()) {
$key = array();
while($row = $stmt->get_result()->fetch_assoc()) { //Call to a member function fetch_assoc() on a non-object
$key .= $row; // Array to string conversion
}
$stmt->close();
return $key;
} else {
return NULL;
}
}
You want to call get_result exactly once, and fetch_assoc as long as there are rows:
$result = $stmt->get_result();
$key = array();
while ($row = $result->fetch_assoc()) {
$key[] = $row;
}
return $key;
So I have a function within a class to take the highest value based on another value but I'm getting a blank page.
I checked for bad syntax but there's none that the validator found and if I change it to header("Location: https://facebook.com") it will go to the site so it seems the function is working. However I am not getting my variable back.
My connections and everything else are fine as my other functions in this class return what I want.
class FORUM
{
private $forum;
function __construct($DBFORUM_con)
{
$this->db = $DBFORUM_con;
}
public function addCount($id)
{
try
{
$stmt = $this->db->prepare("SELECT MAX(a_id) AS Maxa_id FROM forum_answer WHERE question_id = :id");
$stmt->execute(array(':id'=>$id));
$userRow = $stmt->fetch(PDO::FETCH_ASSOC);
if ($stmt->rowCount() > 0)
{
$Max_id = $userRow['Maxa_id'] + 1;
return $Max_id;
}
else {
$Max_id = 1;
return $Max_id;
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
}
Then in my page that processes the form:
//require class
$id = $_POST['id'];
if ($forum->addCount($id))
{
echo $Max_id;
}
else
{
echo $Max_id;
}
You're not assigning the return value to anything.
Try
$id = $_POST['id'];
$Max_id = $forum->addCount($id)
if ($Max_id)
{
echo $Max_id;
}
else
{
echo $Max_id;
}
I'm struggling to rewrite the following function to use a a PDO statement rather than mysql_*. It is obviously part of a larger script but I am having trouble converting this section.
//// What I have so far
function db_scalar($sql, $dbcon2 = null) {
if($dbcon2 ==''){
$dbcon2 = $GLOBALS['dbcon'];
}
$query = $dbcon2->prepare($sql);
if ($line = $query->fetch(PDO::FETCH_ASSOC)) {
$response = $line[0];
}
return $response;
}
//// Original function
function db_scalar($sql, $dbcon2 = null) {
if($dbcon2 ==''){
$dbcon2 = $GLOBALS['dbcon'];
}
$query = mysql_query($sql, $dbcon2) or die(db_error($sql));
if ($line = mysql_fetch_array($query)) {
$response = $line[0];
}
return $response;
}
?>
Any ideas?