pdo->execute() results in an empty value [closed] - php

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
I have a condition, if you find the exact url in the table, will return true, but if you do not think will return false.
But when I run the sql and it returns empty, the condition is as if I had found this condition, I will give an example.
$sql = "SELECT url FROM table WHERE url = '$link'";
$prepare = $conn->prepare($sql);
if ( $prepare->execute() ) {
return true;
} else {
return false; }
I want even when it returns empty, he gives the result of else.
If execute returns empty it feels true, but is false

I want even when it returns empty, he gives the result of else.
Well, that's not what execute does. It only returns false if the query failed. A query which is able to execute but returns 0 rows is not a failure.
http://us3.php.net/manual/en/pdostatement.execute.php
You will need to count the rows your statement would select first: http://us3.php.net/manual/en/pdostatement.rowcount.php
Go to Example #2 Counting rows returned by a SELECT statement

The return value of execute() indicates whether the query succeeded or failed. A query only fails if there's an error of some kind (network problems, permissions errors). If the query simply doesn't find any matching data, that's not an error, it's normal behavior, and execute returns true.
If you want to know if any data was returned, call fetch or fetchAll on the result.

You should use bind in PDO.
It will return false if no data found or query not executed.You can try this:
$sql = "SELECT url FROM table WHERE url = :link";
$prepare = $conn->prepare($sql);
prepare->bindParam(':link', $link, PDO::PARAM_STR, 12);
if ( $prepare->execute() ) {
if($prepare->rowCount()){
echo "got data";
return true;
}
else{
echo "no data";
return false;
}
} else {
return false;
}

Related

Printing PDO query results [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
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.
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.
Improve this question
I am trying to print all the results of a query, but for some reason I get the following error: Fatal error: Call to a member function fetch() on boolean in H:\Some-Location\ on line X
This is my code:
<?php
$query = "SELECT adID FROM given WHERE toUser = :userid";
$query_params = array( ':userid' => $_SESSION['user']['ID'] );
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
echo "Failed to run query: " . $ex->getMessage();
}
while ($row = $result->fetch(PDO::FETCH_ASSOC))
{
echo $row['adID'];
}
?>
What's wrong?
As the docs and the error show, execute returns a boolean: http://php.net/manual/en/pdostatement.execute.php
You need to call fetch() on the statement, not the return value of execute. : http://php.net/manual/en/pdostatement.fetch.php
so replace $result>fetch() with $stmt->fetch().
The execute() method on the PDOStatement does not return the results, it only signals if the query succeeded or not (only useful when not using exceptions).
PHP Documentation:
public bool PDOStatement::execute ([ array $input_parameters ] )
What you want to do is use the PDOStatement itself to get the data:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo $row['adID'];
}
Note: According to your current logic, the loop will execute even when an exception is thrown. Try either returning from the catch block or putting the loop inside the try block.
$result is only a boolean holding success/failure of execute statement.
You need to run fetch on $stmt:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo $row['adID'];
}
As per documentation here:
http://php.net/manual/en/pdostatement.fetch.php

I used this code for displaying 4 numbers randomly without repeating, but i got error as resource id#3 [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I used this code for displaying 4 numbers randomly without repeating, but i got error as resource id#3
$test = nonRepeat(0,4,4); //calling function nonrepeat defined earlier
for ( $i = 0; $i < 4; $i++ ) {
$result = mysql_query( "select * from abc where id='test[i]'" ); accessing data from data base as id in the array test.
print_r( $result );
}
1.- Don't use mysql_* functions they are deprecated and will not be included in future updates.
2.- Your question is pretty unclear, but when you execute a query using mysql_query you get a resource, so you need to iterate through this:
$test = nonRepeat(0,4,4); //calling function nonrepeat defined earlier
for($i=0;$i<4;$i++)
{
$result = mysql_query( "select * from abc where id='{$test[i]}'" ); <<<---- CHANGED
if ($result){
while ($row = mysql_fetch_assoc($result)) {
print_r($row); //Display each row data
}
}else{
print "Error:" . mysql_error();
}
}
Try this and see what is showing, and take a look to mysqli_ and PDO

How can I fix a php function bool? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I dont know what is the problem with this function:
function server_grafico_expirar($data) {
$data = sanitize($data);
$query = mysql_query("SELECT `data_exp` FROM `settings` WHERE `data_exp` = '$data'");
return (mysql_result($query, 0) == 1) ? true : false;
}
This function was supposed to return true if the date('d.m.Y') equals the date in mysql.
Im using like this:
$data = date('d.m.Y');
if(server_grafico_expirar($data)){
echo "Today, is the date!";
}
The error is:
Parse error: syntax error, unexpected T_IF in /home/mcser325/public_html/checker.php on line 35
Firstly, you must make sure that the settings table does contain a row that has the data_exp column set to todays date in the format d.m.Y.
mysql_result retrieves the contents of one cell from a MySQL result set. The cell that you are retrieving is data_exp. From your question I have assumed that data_exp is a date in the format of d.m.Y.
With that said, mysql_result($query, 0) will never be equal to 1 as it will return the date you are selecting. You could approach this in two ways, you could either check if the cell equals $data and then return true
function server_grafico_expirar($data) {
$data = sanitize($data);
$query = mysql_query("SELECT `data_exp` FROM `settings` WHERE `data_exp` = '$data'");
return mysql_result($query, 0) == $data;
}
You could also check how many rows are returned. If more than zero rows are returned then you can return true.
function server_grafico_expirar($data) {
$data = sanitize($data);
$query = mysql_query("SELECT `data_exp` FROM `settings` WHERE `data_exp` = '$data'");
return mysql_num_rows($query) > 0;
}
Please note that the mysql extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used.
Aside from any other potential errors, what your PHP parser is saying is that there is a syntax error. It's not in what you showed us at least, but make sure that you've closed every corresponding curly brackets ({ }) and they are properly matched up and that all lines end with a semicolon (;).
I'd suggest indenting properly to find the error more easily.

Output value from array (php, mysql) [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
function getById($id) {
global $mysqli;
$result = $mysqli->query("SELECT * FROM `ids` WHERE `id` = '".$mysqli->real_escape_string($id)."'") or die($mysqli->error);
$rows = array();
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
$rows[] = $row;
}
return $rows;
}
How do I get the value of id field?
$data = getById(1);
echo $data[0] or echo $data['id'] doesn't work.
Your function returns an array of arrays, so to get the first ID:
$data = getById(1);
echo $data[0]['id'];
Side notes:
Globals are undesirable. Consider passing the database connection object to the function as an argument instead.
Escaping like that is a primitive way of preventing SQL Injection. The use of a Prepared Statement would be more secure and easier.
or die(....) is bad practice because it exposes the detailed MySQL error to users, and it's hard to remove if you have written that hundreds of times. An alternative is trigger_error() which silently writes to your error log.
You no need to use while and array. Get single row and you can get without using array:
function getById($id) {
global $mysqli;
$result = $mysqli->query("SELECT * FROM `ids` WHERE `id` = '".$mysqli->real_escape_string($id)."'") or die($mysqli->error);
return $result->fetch_array(MYSQLI_ASSOC);
}
$data = getById(1);
echo $data['id'];

pdo - The username is already, but it isn't [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Function
public function isUsernameAvailable($username) {
$sql = "SELECT COUNT(*) FROM users WHERE username = '$username'";
$sql = $this->db->quote($sql);
if ($sth = $this->db->query($sql)) {
if ($sth->fetchColumn() > 0) {
return false;
} else {
return true;
}
}
}
if (!$user->isUsernameAvailable($_POST['username'])) {
echo 'The username is already taken!';
$error = 1;
}
I get the output "The username is already taken!" even though It isn't.
select count(*)... will ALWAYS return a record, even nothing is matched
so, you can try this :
select 1 from ...;
between, a proper method to check any record return should be using rowCount
as indicate by the rest :-
you should make use of bind rather than using quote
function should always return a value
Your isUsernameAvailable function will return NULL (equals to FALSE) when the query fails. This will trigger the The username is already taken! message.
Looks like your SQL query always fails, which I think is no wonder because you blindly apply quotes onto it.
After running a SQL query, you must more properly deal with the case that the query failed, e.g. display that an internal SQL error occured and log it, so you can look into the log and locate the cause of the error.
Additionally, you should use the PDO more properly, specifically when you want to prevent SQL injection (which you must care about). See Best way to stop SQL Injection in PHP.
Use rowCount() instead of fetchColumn()
if ($sth->rowCount() > 0) {
fetchColumn returns false if there is no column and also see ajreal answer.
if ($sth = $this->db->query($sql)) {
if ($sth->fetchColumn() == false) {
return true;
} else {
return false;
}
}
Can you try using the following code?
$st->rowCount() > 0
$sql = "SELECT COUNT(*) FROM users WHERE username = '$username'";
$sql = $this->db->quote($sql);
You are quoting the whole query, this does not make any sense and is outright dangerous from a security standpoint – and probably results in an invalid query anyway.
Here's a more proper code:
// return TRUE if user is available
public function isUsernameAvailable($username) {
$sql = "SELECT id FROM users WHERE username = :username";
$stmt = $this->db->prepare($sql);
$stmt->execute(array(':username' => $username));
return $stmt->fetch() === FALSE;
}
if (!$user->isUsernameAvailable($_POST['username'])) {
echo 'The username is already taken!';
$error = 1;
}

Categories