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;
}
Related
I have been converting a small login script i did to PDO trying to give it a try.
Code mysqli
$stmt = $conn->prepare('SELECT id, name FROM users WHERE id = ?');
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($id, $name);
if ($stmt->fetch()) {
$_SESSION['id'] = $id;
$_SESSION['name'] = $name;
$is_valid = true;
} else {
$is_valid = false;
self::logout();
}
I changed to PDO
$sql = "SELECT id, name FROM users WHERE id = :id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':id', $id);
$stmt->bindParam(':name', $name);
$stmt->execute();
if ($stmt->fetch())
{
$_SESSION['id'] = $id;
$_SESSION['name'] = $name;
$is_valid = true;
} else {
$is_valid = false;
self::logout();
}
in mysqli i was able to bind and store $id and $name but read those were not available in PDO
$stmt->store_result();
$stmt->bind_result($id, $name);
There's no equivalent of bind_result in PDO because you don't really need it. Just read the data from the row:
if ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$_SESSION['id'] = $row["id"];
$_SESSION['name'] = $row["name"];
$is_valid = true;
}
You also don't need the $stmt->bindParam(':name', $name); line because there is no :name input parameter in your SQL.
More examples are available in the manual and elsewhere.
See also Is it possible to use store_result() and bind_result() with PHP PDO? for more useful background info.
The equivalent method is called bindColumn(). You can bind a variable to one column in the result set.
/* Bind by column number */
$stmt->bindColumn(1, $id);
$stmt->bindColumn(2, $name);
while ($stmt->fetch(PDO::FETCH_BOUND)) {
print $name . "\t" . $id. "\n";
}
However, I would recommend writing simpler code. PDO is designed to be easier to use.
If you want to make the code simpler, use arrays. The method fetch() returns an array with the current row. They are better when you need to fetch more than one column from the result. If you only need to fetch one column, use fetchColumn().
$sql = "SELECT id, name FROM users WHERE id = :id";
$stmt = $conn->prepare($sql);
$stmt->execute([
'id' => $id,
'name' => $name,
]);
if ($row = $stmt->fetch()) {
$_SESSION['id'] = $row['id'];
$_SESSION['name'] = $row['name'];
$is_valid = true;
} else {
$is_valid = false;
self::logout();
}
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;
}
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.
I am about to lose my mind.I dont have any php experince and I am struggling about php web service.
Here is my code;
<?php
private $username2 = "";
private $password2 = "";
private $DB_CONNECTION;
private $servername = "localhost";
private $username = "root";
private $password = "";
private $dbname = "dptest";
function __construct()
{
$this->DB_CONNECTION = mysqli_connect($this->servername, $this->username,
$this->password, $this->dbname);
}
function getUserType(){
$sql = "SELECT usertype FROM `login_test` WHERE username = '". $this->username2."'AND password = '".$this->password2."'";
$result = mysqli_query($this->DB_CONNECTION,$sql);
//$value = mysqli_fetch_array($result);
while(!is_null($value = mysqli_fetch_array($result))){
return $value['usertype'];
}
}
}
This is my function code.The other is my login code;
<?php
include_once 'Authentication.php';
use user\Authentication;
$auth = new Authentication();
$auth->prepare($_POST);
$userStatus = $auth->isUserValidToLogIn();
if ($userStatus) {
// user existed
// So log him to main page
$json['success'] = 1;
$json['message'] = 'access granted';
$json['usertype'] = $auth->getUserType();
echo json_encode($json);
} else {
$json['success'] = 0;
$json['message'] = 'error!';
echo json_encode($json);
}
I am trying to get the user's type but when try to get the data form phpmyadmin local database it only gives the first column's usertype.When I try to get 2nd,3rd,4th so on.. user's usertype it doesnt return anything and blank page shows up on postman app.
Also my database looks like this;
usertype username password
admin despro 1234
client test 1234
client despro2 1234
client despro3 1234
The reason you are only getting one column back is because you only request the one column. In order to get the columns you want you need to explicitly request them in your query or use '*' in order to get all columns back. So your query should look like this in order to get all columns from the data table:
$sql = "SELECT * FROM `login_test` WHERE username = '". $this->username2."'AND password = '".$this->password2."'";
In general, I highly recommend that you stop using MySQLi extension and start using PHP Data Objects (PDO). It makes it easy to use prepared statements. Which also makes your code safer.
Then your query could look something like this (this is NOT the complete code):
// connecting to db
$pdo = new PDO($dsn, $user, $pass, $opt);
$sql = 'SELECT *
FROM login_test
WHERE userName = :username
AND pass = :password;';
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':username', $username2, PDO::PARAM_STR);
$stmt->bindParam(':password', $password2, PDO::PARAM_STR);
$res = $stmt->execute();
if ($res) {
$response["userdata"] = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$myData = array();
$myData["usertype"] = $row["usertype"];
$myData["username"] = $row["username"];
array_push($response["userdata"], $myData);
}
}
Note that the code above is for returning multiple rows of data. If you just want the one row then use something like this:
if ($res) {
$response["userdata"] = array();
$myData = array();
$myData["usertype"] = $row["usertype"];
$myData["username"] = $row["username"];
array_push($response["userdata"], $myData);
}
removing the 'while' statement.
You might want to take a look at this answer I gave, recently. It is a comprehensive example of using a webservice from an Android app.
How to insert all the SQL table data into an array in java [android studio]
Basically I'm converting all my statements in my class file to prepared statements. After reading over the php.net manual, I still cannot see where or what my error is.
In this particular function I am getting the profile of a user by the users ID.
Any help fellas?
I was able to answer my own question. Using SELECT * doesn't work very well with object oriented prepared statements.
Rather, select all the fields in the table needed and then bind them accordingly.
This particular function is getting all the details of a user by their ID.
Enjoy.
public function getProfile($id){
if($result = $this->link->prepare("SELECT id,first,last,full_name,email,photo FROM dl_users WHERE id=?")){
$result->bind_param('i',$id);
$result->execute();
$result->store_result();
$result->bind_result($id,$first,$last,$full_name,$email,$bio,$hometown,$position,$skills,$photo);
if($result->num_rows == 1){
$user = array();
$result->fetch();
$user['id'] = $id;
$user['first'] = $first;
$user['last'] = $last;
$user['full_name'] = $full_name;
$user['email'] = $email;
$user['photo'] = $photo;
return $user;
}
$result->close();
}
}
MySQLi's prepared statements work with variable references. $result->fetch() doesn't return the fields, it returns a boolean.
What you are can do is this:
public function getProfile($id){
if($result = $this->link->prepare("SELECT * FROM users WHERE id =?")){
$result->bind_param("s", $id);
$result->execute();
$result = $stmt->get_result();
if($row = $result->fetch_assoc()){
return $row;
}else{
return array("error"=>"Profile-Not-Found");
}
$result->close();
}
}
Note: This requires mysqlnd be installed.
If your id field is an integer, you must bind the param in this way:
$result->bind_param("i", $id);
More info here: http://www.php.net/manual/en/mysqli-stmt.bind-param.php
I was able to answer my own question. Using SELECT * doesn't work very well with object oriented prepared statements.
Rather, select all the fields in the table needed and then bind them accordingly.
This particular function is getting all the details of a user by their ID.
Enjoy.
public function getProfile($id){
if($result = $this->link->prepare("SELECT id,first,last,full_name,email,photo FROM dl_users WHERE id=?")){
$result->bind_param('i',$id);
$result->execute();
$result->store_result();
$result->bind_result($id,$first,$last,$full_name,$email,$bio,$hometown,$position,$skills,$photo);
if($result->num_rows == 1){
$user = array();
$result->fetch();
$user['id'] = $id;
$user['first'] = $first;
$user['last'] = $last;
$user['full_name'] = $full_name;
$user['email'] = $email;
$user['photo'] = $photo;
return $user;
}
$result->close();
}
}