return statement doesn't return anything - php

So basically, I have a function getPayments(). This function should execute a query, selecting from multiple tables (with joined). Here is my code
function getPayments($userid, $schoolyear) {
$stmt = $this->con->prepare("SELECT tbl_payment.payment_receipt_type AS RType, tbl_payment.payment_receipt_number AS RNumber, tbl_feetype.feetype_name AS FName, tbl_payment.payment_amount AS PAmount, tbl_month.month_date AS MDate, tbl_payment.payment_dateadded AS PAdded
FROM tbl_payment
INNER JOIN tbl_student ON tbl_student.student_id = tbl_payment.student_id
INNER JOIN tbl_schoolyear ON tbl_schoolyear.schoolyear_id = tbl_payment.schoolyear_id
INNER JOIN tbl_feetype ON tbl_feetype.feetype_id = tbl_payment.feetype_id
INNER JOIN tbl_month ON tbl_month.month_id = tbl_payment.month_id
WHERE tbl_payment.schoolyear_id = ? AND tbl_payment.student_id = ? ORDER BY payment_dateadded DESC");
$stmt->bind_param("ss", $userid, $schoolyear);
$stmt->execute();
$stmt->bind_result($RType, $RNumber, $FName, $PAmount, $MDate, $PAdded);
$payments = array();
while ($stmt->fetch()) {
$temp = array();
$temp['paymenttype'] = $RType;
$temp['receiptnumber'] = $RNumber;
$temp['feename'] = $FName;
$temp['paymentamount'] = $PAmount;
$temp['monthname'] = $MDate;
$temp['paymentdate'] = $PAdded;
array_push($payments, $temp);
}
return $payments;
}
In my index.php file:
//getting payment details for a user
$app->get('/payment/{id}/{sy}', function (Request $request, Response $response) {
$route = $request->getAttribute('route');
// $userid = $request->getAttribute('id');
$userid = $route->getArgument('id');
$schoolyear = $route->getArgument('sy');
// $schoolyear = $request->getAttribute('sy');
$db = new DbOperation();
$payments = $db->getPayments($userid, $schoolyear);
$response->getBody()->write(json_encode(array("payments" => $payments)));
});
^ This line of code will take the returned array result from getPayment() function then encode it to json.
The problem is, after testing my API in Postman, Postman only gives me this result
{"payments":[]}
Please help me. Thank you. (Sorry for my bad english)

Find the answer.
I misplace some variables.
The line $stmt->bind_param("ss", $userid, $schoolyear); should be written as $stmt->bind_param("ss", $schoolyear, $userid); .
Everything is working now. Thank you. :)
This thread is now CLOSED.

Related

PHP class functions [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last year.
Improve this question
I have problem with functions. I call getclass function with this.
<?php
require_once './DbOperations.php';
if($_SERVER['REQUEST_METHOD']=='POST'){
if(isset($_POST['username'])) {
$db = new DbOperations();
$classjson = $db->getclass($_POST['username']);
echo $classjson;
}
}
?>
But its not working for me. This is not working [$teacherfullname,$teacherpicture] = $this->getteacher($teacher);
But when i put this top and change $teacher to $uuid its good. But i need there $teacher.
public function getclass($uuid) {
//when i put here its working with $uuid but i need $teacher
[$teacherfullname,$teacherpicture] = $this->getteacher($uuid);
$stmt = $this->con->prepare("SELECT `id`, `name`, `teacher`, `student` FROM `class` WHERE teacher= ? OR student= ?");
$stmt->bind_param("ss", $uuid, $uuid);
$stmt->execute();
$stmt->bind_result($id, $name, $teacher, $student);
$product = array();
while($stmt->fetch()) {
//this is what not working
[$teacherfullname,$teacherpicture] = $this->getteacher($teacher);
$temp = array();
$temp['id'] = $id;
$temp['name'] = $name;
$temp['teacher'] = $teacherfullname;
$temp['picture'] = $teacherpicture;
$temp['student'] = $student;
array_push($product, $temp);
}
return json_encode($product);
}
private function getteacher($uuid) {
$stmt = $this->con->prepare("SELECT id, fullname, picture FROM users WHERE uuid = ?");
$stmt->bind_param("s", $uuid);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$stmt->store_result();
return [$row['fullname'], $row['picture']];
}
Help me to find the bug please.
Edit : misreading from the OP, sorry.
Try to replace
$stmt->bind_param("s", $uuid);
With :
$stmt->bind_param("uuid", $uuid);
Don't assign variables like this.
[$teacherfullname,$teacherpicture] = $this->getteacher($teacher);
I suggest you to do something like this :
...
$teacher = $this->getteacher($teacher);
$temp['teacher'] = $teacher['fullname'];
$temp['picture'] = $teacher['picture'];
...
private function getteacher($uuid) {
... //use named indexes, easier to maintain
return ["fullname" => $row['fullname'], "picture" => $row['picture']];
}

PHP Fetch all rows from MySQL

I'm trying to fetch all rows for parentId for my form. However my below code isn't able to fetches just 1 record, into my array:
public function getChildByParent($parentId)
{
$stmt = $this->conn->prepare("SELECT childId, nick, relation FROM childId WHERE parentId = ?");
$stmt->bind_param("s", $parentId);
$stmt->execute();
$stmt->bind_result($childId, $nick, $relation);
$stmt->fetch();
$user = array();
$user['childId'] = $childId;
$user['nick'] = $nick;
$user['relation'] = $relation;
return $user;
}
I understand that I need to tweek around $stmt->fetch() and $user = array() to fetch_all. Can you help me work around this code?
Appreciate your efforts.
Using $stmt->get_result() to setup $result->fetch_all() to get all records in one call.
Try:
public function getChildByParent($parentId)
{
$stmt = $this->conn->prepare("SELECT childId, nick, relation FROM childId WHERE parentId = ?");
$stmt->bind_param("i", $parentId);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_all(MYSQLI_ASSOC);
$stmt->close();
return $user;
}

How do I make a function out of these sql statements so I dont have to repeat them so many times?

I would like to make these statements into a function instead, as you see its kind of repetitive. How would you make this more efficient using a function? Very grateful for tips!
if (isset ($_GET["news"])){
$statement = $pdo->prepare("SELECT * FROM posts INNER JOIN users ON
posts.userID = users.id
WHERE category = 'news'");
$statement->execute();
$blog = $statement ->fetchALL(PDO::FETCH_ASSOC);
}
if (isset ($_GET["style"])){
$statement = $pdo->prepare("SELECT * FROM posts INNER JOIN users ON
posts.userID = users.id
WHERE category = 'style'");
$statement->execute();
$blog = $statement ->fetchALL(PDO::FETCH_ASSOC);
}
if (isset ($_GET["interior"])){
$statement = $pdo->prepare("SELECT * FROM posts INNER JOIN users ON
posts.userID = users.id
WHERE category = 'interior'");
$statement->execute();
$blog = $statement ->fetchALL(PDO::FETCH_ASSOC);
}
if (isset ($_GET["featured"])){
$statement = $pdo->prepare("SELECT * FROM posts INNER JOIN users ON
posts.userID = users.id
WHERE category = 'featured'");
$statement->execute();
$blog = $statement ->fetchALL(PDO::FETCH_ASSOC);
}
Its based on a category sorting(news, style, interior, featured).
There are a couple of ways to skin this cat, but I use a function from which I can run all queries with PDO. Here is that function, along with the connection:
function dataQuery($query, $params) {
// what kind of query is this?
$queryType = explode(' ', $query);
// establish database connection
try {
$dbh = new PDO(DBL, USER, PASS);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo $e->getMessage();
$errorCode = $e->getCode();
}
// run query
try {
$queryResults = $dbh->prepare($query);
$result = $queryResults->execute($params);
if($queryResults != null && 'SELECT' == $queryType[0]) {
// only return results for SELECT queries - the remainder need no output
$results = $queryResults->fetchAll(PDO::FETCH_ASSOC);
return $results;
}
$queryResults = null; // first of the two steps to properly close
$dbh = null; // second step to close the connection
return $result;
}
catch(PDOException $e) {
$errorMsg = $e->getMessage();
echo $errorMsg;
}
}
NOTE: The try/catch is not necessary but I do capture the error messages for other pruposes, so this is a handy way of doing it.
Then, any time I need to query I can just write the query and send the parameters with the request:
$role = $_POST['role'];
$getRoleID = "SELECT `id` FROM `roles` WHERE `role` = :role;";
$params = array(':role'=>$role);
$result = dataQuery($getRoleID, $params);
However, your's is a little more specific. You want a single function for your blog. Combining yours with mine you could do this:
function getBlogPosts($type) {
$getPosts = "SELECT * FROM posts INNER JOIN users ON posts.userID = users.id WHERE category = :category");
$params = array(':category'=>$type);
$result = dataQuery($getPosts, $params);
return $result;
}
Now, to call the function you just have to insert the type of posts you want:
$featured = getBlogPosts('featured');
or:
$interior = getBlogPosts('interior');
Parse the returned results and you're well on your way.

php Fetch(), SQL Join, in a while()

I am trying to display a clients projects. I would like to display the client information once and the projects multiple times
$stmt = $conn->prepare("SELECT client.client_id, client.firstname, client.lastname, project.project_title
FROM client
INNER JOIN project ON client.client_id = project.client_id
WHERE client.client_id = ?");
$stmt->bind_param("i", $userid);
$userid = $_GET['clientid'];
$stmt->execute();
$stmt->bind_result($clientid, $firstname, $lastname, $project);
while($stmt->fetch()){
echo $clientid;
echo $project;
}
The problem I have is the $clientid will not work anywhere out side of the $stmt->fetch(), just as I can not use the $stmt->fetch() out side the while to get the $clientid and use the $stmt->fetch() again for the while loop.
Is there away to call and Display the Client information once, and the project information multiple times?
Just an example how you can ,"save" the data. I think you must read about how scopes works in php.
$clients = array();
$projects = array();
$some_id = null;
while($stmt->fetch()){
$clients[] = $clientid;
$projects[] = $project;
$some_id = $clientid;
}

MYSQL - PHP : getting MySQLi results as array

This is the update code
But I got the error : FATAL ERROR (Call to undefined method User::fetch_assoc())
this is my method code
public function getAllUsers(User $user)
{
$stmt = $this->conn->prepare("SELECT u.user_id, u.email, u.name, u.phone, u.picture, s.status
FROM ".$this->table_name." as u, status as s
WHERE u.status_id = s.status_id");
if($stmt == FALSE)
{
die($this->conn->error);
}
else
{
$stmt->execute();
$stmt->bind_result($user_id, $email, $name, $phone, $picture, $status);
while($stmt->fetch())
{
$user->setUserId($user_id);
$user->setEmail($email);
$user->setName($name);
$user->setPhone($phone);
$user->setPicture($picture);
$user->setStatus($status);
}
$stmt->close();
return $user;
}
}
and this is my code in index.php who called the object method.
$app->get('/users', 'authenticate', function()
{
global $user_id;
$response = array();
$user = new User();
// fetching all users
$userDB = new UserDb(MySqlDb::getInstance()->connect());
$result = $userDB->getAllUsers($user);
$response["error"] = false;
$response["users"] = array();
// looping through result and preparing users array
while ($user = $result->fetch_assoc())
{
$tmp = array();
$tmp["user_id"] = $user->getUserId();
$tmp["email"] = $user->getEmail();
$tmp["name"] = $user->getName();
$tmp["phone"] = $user->getPhone();
$tmp["picture"] = $user->getPicture();
$tmp["status"] = $user->getStatus();
array_push($response["users"], $tmp);
}
echoRespnse(200, $response);
});
please check my foreach, is it wrong ?
Thanks :)
getAllUsers returns an array of Users
so $result is an array of Users, not a database query result as you may expect.
then you call fetch_assoc() on $result, which is an array of users, and as it doesn't have this method, you get Call to undefined method User::fetch_assoc()

Categories