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']];
}
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();
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I have been using the header() to redirect for several pages, but in this case it is not redirecting.
In this case, I will have a blank page as if the header part of the code is not working, the file path is correct to so I am not sure what could be the issue here.
The code:
<?php
//start session management
session_start();
//connect to the database
require 'connection.php';
// Require function
require_once "../model/functions_cars.php";
// Fetch the data required
$carID = $_GET['carID'];
$sold = $_GET['sold'];
$date = date('Y-m-d H:i:s');
$username = $_SESSION['user'] || $_SESSION['admin'] || $_SESSION['disabled'];
global $conn;
$sql = "SELECT userID FROM sport_cars.user WHERE username = :username";
$statement = $conn->prepare($sql);
$statement->bindValue(':username', $username);
$result3 = $statement->execute();
$statement->closeCursor();
$userID = $result3;
//call the buy_car() function
$result = buy_car($carID, $sold);
if (!$result) {
echo "Query error: " . mysqli_error($conn);
exit;
}
global $conn;
$sql = "INSERT INTO sport_cars.sold_cars (carID, userID, date) VALUES (:carID, :userID, :date)";
$statement = $conn->prepare($sql);
$statement->bindValue(':carID', $carID);
$statement->bindValue(':userID', $userID);
$statement->bindValue(':date', $date);
$result2 = $statement->execute();
$statement->closeCursor();
return $result2;
// header("location: ../cart_buy.php");
// Redirect the browser window back to the add cart page
if (!$result2) {
echo "Query error: " . mysqli_error($conn);
exit;
} else {
// Redirect the browser window back to the add cart page
header("location: ../cart_buy.php");
}
What could be the problem?
Your return statement is being called and preventing the rest of the code from executing, you need your if statement to still execute for $result2, and then trigger the header() redirect after.
This should work fine.
<?php
session_start(); // Start session management.
require 'connection.php'; // Connect to the database.
// Require function
require_once "../model/functions_cars.php";
// Fetch the data required.
$carID = $_GET['carID'];
$sold = $_GET['sold'];
$date = date('Y-m-d H:i:s');
$username = $_SESSION['user'] || $_SESSION['admin'] || $_SESSION['disabled'];
$sql = "SELECT userID FROM sport_cars.user WHERE username = :username";
$statement = $conn->prepare($sql);
$statement->bindValue(':username', $username);
$statement->execute();
$userID = $statement->fetchColumn();
//call the buy_car() function
$result = buy_car($carID, $sold);
$sql = "INSERT INTO sport_cars.sold_cars (carID, userID, date) VALUES (:carID, :userID, :date)";
$statement = $conn->prepare($sql);
$statement->bindValue(':carID', $carID);
$statement->bindValue(':userID', $userID);
$statement->bindValue(':date', $date);
$statement->execute();
// return $result2; <- move this somewhere else, this is what is causing your header() below to not redirect.
// Redirect the browser window back to the add cart page
header("Location: ../cart_buy.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.
This question already has an answer here:
$stmt->num_rows returning 0 even after calling store_result
(1 answer)
Closed 9 years ago.
i am just trying to learn prepared statement and i am following the PHP manual to guide me through, i have checked the answers regarding this problem on stackoverflow but, i can't find any solutions, the $stmt->num_rows always ( Return 0 )
there is a post on stackoverflow discussed the problem and they advised to use
$stmt->store_result() just before the $stmt-num_rows, but the $stmt->num_rows return 0
some one please can tell me what i am doing wrong here.... i am just sick of the procedural style coding and i want to enhance my skills with prepared statement
here is the function down below
function get_all()
{
// ** Initializing the Connection
$mysqli = Connect();
$sql = ( ' SELECT * FROM `users` ' );
$stmt = $mysqli->prepare($sql);
$stmt->execute();
$res = $stmt->get_result();
echo $num_count = $stmt->num_rows();
$user = array();
for ($counter = 0; $row = $res->fetch_assoc(); $counter++)
{
$user[$counter] = $row;
}
return $user;
}
// This is the second update
function get_all()
{
// ** Initializing the Connection
$mysqli = Connect();
$sql = ( ' SELECT * FROM `users` ' );
$stmt = $mysqli->prepare($sql);
$stmt->execute();
$res = $stmt->get_result();
echo $num_count = $stmt->num_rows;
$user = array();
while($row = $res->fetch_assoc())
{
$user[] = $row;
}
return $user;
}
// third update
function get_alll()
{
// ** Initializing the Connection
$mysqli = Connect();
// no need to use * character,
// need to write query this way
$sql = ( ' SELECT `id`,`fname`,`lname`,`uname`,`email` FROM `users` ' );
$stmt = $mysqli->prepare($sql);
// here need to use bind param
$stmt->bind_result( $id, $fname, $lname, $uname, $email);
$stmt->execute();
// it's important to store the result
// before using num rows
$res = $stmt->store_result();
echo $num_count = $stmt->num_rows;
//
while($stmt->fetch())
{
echo $fname;
}
}
num_rows is a property, not a method, try with $stmt->num_rows without brackets
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
I need to rewrite all my code.. I was told last time I was in here, that I needed to choose between mysqli or PDO.. now I have choosen PDO - but I must say that I don't understand NOTHING at all..
For example I have this piece of code:
//get the email
$email = mysql_real_escape_string($_POST['email']);
//mysql query to select field email if it's equal to the email that we check '
$result = mysql_fetch_array(mysql_query("SELECT email FROM business_members WHERE email = '".$email."'"));
//if number of rows fields is bigger them 0 that means it's NOT available '
if($result['email'] == $email){
//and we send 0 to the ajax request
echo "0";
}else{
//else if it's not bigger then 0, then it's available '
//and we send 1 to the ajax request
echo "1";
}
Are there any sites that can help me understand a little better and I have tried to read on php-net, but it is very confusing..
The best thing about PDO is that its object orientated. So keeping to that form and making the most of it we can create a PDO CRUD class that handles all your database query's ect.
Here is an example, custom methods/functions can be added to enhance functionality ect:
<?php
Class PDO_CRUD{
private $db;
function __construct($host,$dbname,$user,$pass){
$this->dbhost = $host;
$this->dbname = $dbname;
$this->dbuser = $user;
$this->dbpass = $pass;
}
private function connect(){
if (!$this->db instanceof PDO){
$this->db = new PDO('mysql:dbname='.$this->dbname.';host='.$this->dbhost, $this->dbuser, $this->dbpass);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
}
/*Raw Select*/
public function rawQuery($sql){
$this->connect();
return $this->db->query($sql)->fetchAll(PDO::FETCH_ASSOC);
}
public function get($table,$fieldname=null, $id=null){
$this->connect();
$sql = "SELECT * FROM $table WHERE $fieldname = :id";
$statement = $this->db->prepare($sql);
$statement->bindParam(':id', $id, PDO::PARAM_STR);
$statement->execute();
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
/*Insert*/
public function put($table,$values){
$this->connect();
$fieldnames = array_keys($values[0]);
$sql = "INSERT INTO $table ";
$fields = '('.implode(' ,', $fieldnames).')';
$bound = '(:'.implode(', :', $fieldnames).')';
$sql .= $fields.' VALUES '.$bound;
$statement = $this->db->prepare($sql);
foreach($values as $vals){
$statement->execute($vals);
}
}
/*Update*/
public function update($table,$fieldname, $value, $pk, $id){
$this->connect();
$sql = "UPDATE $table SET $fieldname = :value WHERE $pk = :id";
$statement = $this->db->prepare($sql);
$statement->bindParam(':id', $id, PDO::PARAM_STR);
$statement->bindParam(':value', $value, PDO::PARAM_STR);
$statement->execute();
}
/*Update Hits*/
public function add_hit($table,$id){
$this->connect();
$sql = "UPDATE $table SET hits = hits + 1 WHERE url = :id";
$statement = $this->db->prepare($sql);
$statement->bindParam(':id', $id, PDO::PARAM_STR);
$statement->execute();
}
/*Delete*/
public function delete($table,$id){
$this->connect();
$sql = "DELETE FROM $table WHERE url = :id";
$statement = $this->db->prepare($sql);
$statement->bindParam(':id', $id, PDO::PARAM_STR);
$statement->execute();
}
}
//Then we have a nice way to access all our querys from one class.
//ini the model class
$model = new PDO_CRUD('localhost','yourDB','User','Password');
$insert = array(array('id'=>NULL,'somecol'=>'someval'));
$model->put('someTable',$insert);
//multiple inserts
$insert = array(array('id'=>NULL,'somecol'=>'someval123'),
array('id'=>NULL,'somecol'=>'someval1234'),
array('id'=>NULL,'somecol'=>'someval12345'));
$model->put('someTable',$insert);
//or delete a row
$model->delete('someTable',1);
//or a raw query
$model->rawQuery('DELETE FROM someTable');
?>
PHP File containing the PDO functions:
<?php
class example {
public function __construct() {
$this->db = new PDO('mysql:host=localhost;dbname=testdb;', 'user', 'password');
}
public function checkMail($email) {
// This is the prepared SQL statement
// The values which you want to filter for in your WHERE clause, are replaced by ?
$sql = "SELECT
email
FROM
business_members
WHERE
email = ?";
// Prepare the statement
$stmt = $this->db->prepare($sql);
// Bind a value to a question mark (the 1 means, the position of occurence of the question mark)
$stmt->bindParam(1, $email);
// Query the db, output debug info if query failed
if(!$stmt->execute()) {
// Only for debugging, don't use in production
var_dump($stmt->errorInfo());
}
// Load result to var
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Check amount of records
if(count($result) > 0) {
// Records found
return 1;
} else {
// No records found
return 0;
}
}
}
?>
Main file:
<?php
include 'includes/pdo.include.php';
$example = new example;
echo $example->checkMail($_POST['email']);
?>