so I have the following method:
public function checkLogin($username){
$sql_login=$this->dbc->prepare("SELECT username FROM credentials WHERE username=?");
$sql_login->bind_param("s", $username);
$stmt=$sql_login->execute();
$result = $stmt->get_result();
return $result;
}
By doing a var_dump (and removing $result = $stmt->get_result();) I can see that $stmt is passing a boolean.
I'm new to OOP in php. I'm thinking that get_result() function should get the result of the $stmt execution.
What am I doing wrong please ?
$result = $stmt->get_result(); converts a mysqli::statement object into a mysqli::result object, it does not return any rows from the resultset
You are also using the returned value from $sql_login->execute(); which is in fact just a boolean instead of the statement object called $sql_login in your case i.e. $result = $sql_login->get_result();
So you need to add something to actually fetch the row that was returned by the query, for example $row = $result->fetch_assoc(); like this
public function checkLogin($username){
$sql_login=$this->dbc->prepare("SELECT username
FROM credentials
WHERE username=?");
$sql_login->bind_param("s", $username);
$sql_login->execute();
$result = $sql_login->get_result();
$row = $result->fetch_assoc(); // fetch the row as an assoc array
return $row;
}
Related
I have this code.
$stmt = $conn->prepare("SELECT * FROM UserData WHERE username = ?");
$stmt->bind_param('s',$username);
//$username = $_POST["username"];
$username ="netsgets";
$stmt->execute();
$stmt->store_result();
var_dump(stmt['likedFour']);
According to table UserData, likeFour should equal 'empty'. For some reason, var_dump(stmt['likedFour']); is returning the string 's'. Why is this?
Edit (this is what you told me to do but it is not working):
when I run this the script stops at the var_dump.
require "conn.php";
echo "debug 1";
$stmt = $conn->prepare("SELECT * FROM UserData WHERE username = ?");
$stmt->bind_param('s',$username);
//$username = $_POST["username"];
$username ="netsgets";
$stmt->execute();
$row = $stmt->fetch_assoc();
var_dump($row['likedFour']);
Why does var_dump(stmt['likedFour']); return 's':
Because you're missing the dollar sign before stmt, so PHP thinks you're trying to access the constant stmt instead of the variable $stmt. Since you haven't defined that constant, it will fall back to assuming you're trying to access the string "stmt". For strings, indices must be numeric so PHP should be throwing you an "Illegal string offset" warning but will try to fix it for you by casting 'likedFour' to an integer (which will be 0).
Therefore, var_dump(stmt['likedFour']) means the exact same thing as var_dump("stmt"[0]) to PHP, which is why you're getting the output "s": the first character from "stmt".
How to get the result you actually want:
You first need to retrieve the resulting rows from your query. $stmt is the mysqli_stmt object that you use to execute the query and retrieve the results, it is not actually the result itself.
To save yourself headaches in the future, always check whether your query even executed successfully before trying to retrieve the results. Then fetch the row of data:
$success = $stmt->execute();
if (!$success) {
echo $stmt->error;
} else if ($stmt->num_rows == 0) {
echo 'No results matching that username';
} else {
$result = $stmt->get_result();
$row = $result->fetch_assoc();
var_dump($row['likedFour']);
}
If you don't know how many rows will be returned, loop through them just to be safe:
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
var_dump($row['likedFour']);
}
I have this code.
$stmt = $conn->prepare("SELECT * FROM UserData WHERE username = ?");
$stmt->bind_param('s',$username);
//$username = $_POST["username"];
$username ="netsgets";
$stmt->execute();
$stmt->store_result();
var_dump(stmt['likedFour']);
According to table UserData, likeFour should equal 'empty'. For some reason, var_dump(stmt['likedFour']); is returning the string 's'. Why is this?
Edit (this is what you told me to do but it is not working):
when I run this the script stops at the var_dump.
require "conn.php";
echo "debug 1";
$stmt = $conn->prepare("SELECT * FROM UserData WHERE username = ?");
$stmt->bind_param('s',$username);
//$username = $_POST["username"];
$username ="netsgets";
$stmt->execute();
$row = $stmt->fetch_assoc();
var_dump($row['likedFour']);
Why does var_dump(stmt['likedFour']); return 's':
Because you're missing the dollar sign before stmt, so PHP thinks you're trying to access the constant stmt instead of the variable $stmt. Since you haven't defined that constant, it will fall back to assuming you're trying to access the string "stmt". For strings, indices must be numeric so PHP should be throwing you an "Illegal string offset" warning but will try to fix it for you by casting 'likedFour' to an integer (which will be 0).
Therefore, var_dump(stmt['likedFour']) means the exact same thing as var_dump("stmt"[0]) to PHP, which is why you're getting the output "s": the first character from "stmt".
How to get the result you actually want:
You first need to retrieve the resulting rows from your query. $stmt is the mysqli_stmt object that you use to execute the query and retrieve the results, it is not actually the result itself.
To save yourself headaches in the future, always check whether your query even executed successfully before trying to retrieve the results. Then fetch the row of data:
$success = $stmt->execute();
if (!$success) {
echo $stmt->error;
} else if ($stmt->num_rows == 0) {
echo 'No results matching that username';
} else {
$result = $stmt->get_result();
$row = $result->fetch_assoc();
var_dump($row['likedFour']);
}
If you don't know how many rows will be returned, loop through them just to be safe:
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
var_dump($row['likedFour']);
}
This function returns only one row from database while there are many of them.
Could someone tell me why please? Can i do this other way?
function writecomments($photoid){
include 'connect.php';
$stmt = $pdo -> query("SELECT * FROM comments WHERE photoid = '".$photoid."' ");
while($row = $stmt -> fetch()) {
return $row['comment'];
}
$stmt->closeCursor();
}
I have also tried this way:
function writecomments($photoid){
include 'connect.php';
$stmt = $pdo -> query("SELECT * FROM comments WHERE photoid = '".$photoid."' ");
while($row = $stmt -> fetch()) {
$allcomments = $allcomments . " " . $row['comment'];
}
return $allcomments;
$stmt->closeCursor();
}
Im assuming $pdo is a PDO connection object. In which case it could be to do with the fact you are using PDO::query - which is a bit of a tricky function - and how you are iterating through the result set.
If you want to use the PDO query method then it should be within a foreach loop.
From the PDO query official documentation
PDO::query() executes an SQL statement in a single function call, returning the result set (if any) returned by the statement as a PDOStatement object.
If you do not fetch all of the data in a result set before issuing
your next call to PDO::query(), your call may fail.
I would try:
function writecomments($photoid){
include 'connect.php';
foreach ($pdo -> query("SELECT * FROM comments WHERE photoid = '".$photoid."' ") as $row) {
return $row['comment'];
}
$stmt->closeCursor();
}
That's what fetch() does it returns the next row from the result
set. If you need all rows you will need to manually append them to an array, or use fetchAll() instead in order to get all rows at once.
It looks a little weird to have an include inside of the function, should be passed as parameter or maybe create the connection in the function.
Use prepared statements for this query.
I would do it this way:
Function:
function writecomments($pdo, $photoid){
$sql = "
SELECT *
FROM comments
WHERE photoid = ?
";
$stmt = $pdo -> prepare($sql);
$stmt->execute(array($photoid));
$rows = $stmt->fetchAll();
//return all rows
return $rows;
}
Usage:
include 'connect.php';
$rows = writecomments($pdo, $photoid);
var_dump($rows);
I'm fetching some data and trying to print it to the page but i'm getting the following error -
PHP Catchable fatal error: Object of class PDOStatement could not be converted to string
This is my query function;
function query($query, $bindings, $conn)
{
$stmt = $conn->prepare($query);
$stmt->execute($bindings);
return $stmt;
}
the query and printing to the page;
$testimonials = query ('SELECT * FROM testimonials ORDER BY id = :id DESC LIMIT 1',
array('id' => ['id']), $conn);
print $testimonials;
I'm not sure how I can turn it to a string without re-writing the function or should I be doing that?
You are not actually returning any results, you're returning the PDO object
change the return from
return $stmt;
to
return $stmt->fetchAll(PDO::FETCH_ASSOC);
this will return multiple results (if they are available)
or
return $stmt->fetch(PDO::FETCH_ASSOC);
will return a single result
UPDATE
To answer your comment, you can use
return ($stmt->rowCount() > 0) ? $stmt->fetchAll(PDO::FETCH_ASSOC) : false;
Note: this will return an array, which means you need to access the array to print what you want.. you can do this like so:
foreach( $testimonials as $testimonial )
{
print( $testimonial['field_name_from_database'] );
}
it should be,
print_r($testimonials);
For debug/test purpose, it's better to use var_dump(), it provide an html formated output with additionnal informations (type, length) and work recursively.
Also you return a PDOStatement object, it's a prepared request that havent been executed. You need it to fetch the results (fetch or fetchAll).
PHP :
function query($query, $bindings, $conn)
{
$stmnt = $conn->prepare($query);
$stmt->execute($bindings);
return $stmt->fetchAll();
}
I am new to Object Oriented PHP. Currently I am making a login script and am stuck at fetching & echo'ing the results. This is my script:
$stmt = $db->mysqli->prepare("select User from `users` where User = ? AND Password = ?");
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
$stmt->store_result();
$num = $stmt->num_rows;
$stmt->bind_result($username);
if ( $num !== 1 ) {
echo 'no result';
} else {
echo 'Your username: '. $username ;
}
$stmt->close();
As you can see I am not fetching a result in the script above. I tried using $stmt->fetch() in a while-loop prior to the $num !== 1.
However, the result of the fetching is "stored" as an array (I think), even though inside the while loop you don't use an array (just $username). What I want: echo the result of the select query OUTSIDE a while loop. Just as it is possible in the old fashioned way (assuming there is only 1 result, therefore no while-loop necessary):
$result = mysqli_query( $conn, $query );
$record = mysqli_fetch_array( $result );
echo $record['username'];
You need to accses to object variable:
echo $stmt->User;
Or you can save variable for later:
$user = $stmt->User;
After ending of your loop your $user will hold the value.
You can use $stmt->get_result() to do that, e.g.
$stmt->execute();
$result = $stmt->get_result();
$record = $result->fetch_assoc();
echo $record['username'];
Edit
Another method is to call fetch after bind_result
$stmt->bind_result($username);
$stmt->fetch()
echo $username;
Old fashion way:
print_r($record);
From the php manual: print_r