I am trying to run a simple SELECT query. here is the query
$sql1=$conn->prepare("SELECT q.quoteid, q.customername, q.customersurname, q.timestamp, o.name
FROM quotes as q, occasions as o
WHERE q.occasionid=o.occasionid
AND companyid=1
AND q.day=:day
AND q.month=:month
AND q.year=:year
AND staffid='-1'
AND (q.complete != 'W' OR q.complete != 'Y')
AND q.online=0");
$sql1->execute($exearray);
/* here $exearray contain following value */
Array ( [:day] => 24 [:month] => 1 [:year] => 2014 )
Its not even showing any error.
If I pass static value 1 in month it is showing data.
I run this query directly on DB its working.
So I think there is no error in query.
I am running this query locally on MAMP.
have you tried to parse your month's data to string before passing to the pdo???
$exearray = array(':day'=>24, ':month'=>(string)1, ':year'=>2014);
once i faced this situation and i did this and it worked for me.
i always have this problem while i trying to use LIMIT command in mysql. i just parse my value to string or pass it through statically.
and it doesn't relevant to your MAMP. i have this problem on LAMP and WAMP too.
apparently it's a common problem which it's in PDO libraries.
and for the record don't forget to use intval() while you pass your month's variable directly to your query.
You need to fetch your result, execute only returns a boolean (true or false) whether query execution succeeded or not.
Example:
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll();
print_r($result);
from: http://php.net/manual/en/pdostatement.fetchall.php
Perhaps doing it the "long-way" with the parameters, and/or changing the query to use a join would help.
Also, the try/catch on PDOException might provide more information.
Lastly, note the $cmd->fetch(PDO::FETCH_ASSOC) invoked for iterating through the recordset.
try {
$db = new PDO("mysql:host=localhost;charset=utf8", "root", "root");
$cmd = $db->prepare("
SELECT q.quoteid, q.customername, q.customersurname,
q.timestamp, o.name
FROM quotes q
LEFT JOIN occasions o on q.occasionid = o.occasionid
WHERE companyid=1
AND q.day = :day
AND q.month = :month
AND q.year = :year
AND staffid = '-1'
AND (q.complete != 'W' OR q.complete != 'Y')
AND q.online = 0
");
$cmd->bindParam(':day', 24, PDO::PARAM_INT);
$cmd->bindParam(':month', 1, PDO::PARAM_INT);
$cmd->bindParam(':year', 2014, PDO::PARAM_INT);
if ($cmd->execute()) {
while ($row = $cmd->fetch(PDO::FETCH_ASSOC)) {
echo $row['quoteid']."|".$row['customername']."|".$row['name']."<br/>";
}
} else {
echo "$cmd->execute() returned false.";
}
} catch (PDOException $e) { echo $e->getMessage(); return; }
In table month column type was Varchar.
I change that to integer and now it is working.
p.s. I have tried using (string) before variable and even double quotes and single quotes on variable value but it didn't work.
Thank you everyone. :)
Related
I am trying to bind values to a query in PHP. I have done this successfully many times, but for some reason my code isn't working.
function get_movies($vars, $page) {
global $db;
$get_movies = $db->prepare('SELECT * FROM `movies` WHERE LOWER(genres) LIKE :genre AND `qualities` LIKE :quality AND `rating` >= :imdb_min AND `rating` <= :imdb_max AND `year` >= :year_min AND `year` <= :year_max ORDER BY id DESC');
$get_movies->bindValue(':genre', $vars['genre']);
$get_movies->bindValue(':quality', $vars['quality']);
$get_movies->bindValue(':imdb_min', $vars['imdb_min']);
$get_movies->bindValue(':imdb_max', $vars['imdb_max']);
$get_movies->bindValue(':year_min', $vars['year_min']);
$get_movies->bindValue(':year_max', $vars['year_max']);
try {
$get_movies->execute();
$movies = $get_movies->fetchAll(); // list of all movies fitting parameters
$movie_offset = ($page - 1) * VIDEOS_PER_PAGE;
$movies = array_slice($movies, $movie_offset, VIDEOS_PER_PAGE);
return $movies;
} catch (Exception $e) {
throw $e;
return false;
}
}
The above code does not work. No exception is thrown, but it returns 0 results. However, if I built the query manually (ex: replacing each :key with the $vars['key'] and preparing the statement from the resulting string) the query returns results perfectly fine.
Any tips would be greatly appreciated.
Edit:
Here's the $vars array passed to the $get_movies function.
$vars = array(
'genre' => "Action",
'quality' => 1080,
'imdb_min' => 0.1,
'imdb_max' => 10.0,
'year_min' => 2000,
'year_max' => 2019
);
When I use pdo, this is how I do my query
Eg
$stmt=db_conn->prepare ("SELECT * FROM table WHERE id = ? AND name = ? AND = uptime = ?");
$stmt->bindParam (1, $firstvariable);
$stmt->bindParam (2, $secondvariable);
$stmt->bindParam (3, $thirdvariable);
$stmt->execute();
$result=$stmt->fetchAll();
It Will bind respectfully to the blind parameters (?)
Try and ignore the movie offset and movies variables for now and fetch the results using foreach loop.
Try this & see. Hope it helps you.
I managed to fix the problem. When executing the query manually, the " characters surrounding strings in the LIKE comparison are interpreted as indicators that the value in between them is a string. When binding a value with " characters surrounding the string, the characters are included in the value itself. This is why no exception was thrown and the query returned 0 results. Thank you for the help.
So the query I am running can have 0, 1, or many results. I need to store the number of rows in a query to a variable. Using PDO I should be able to do that using the fetchColumn() method. But it is not givng ANY result. When I echo out $numrows I am getting nothing, not even a zero. I know it is probably something really small but I have been staring at this code for an hour now and I need a fresh set of eyes guys.
try {
$count = $db->prepare('SELECT COUNT(*) FROM location WHERE location.zip = :input');
$count->bindValue(':input', $input);
$numrows = $count->fetchColumn();
} catch (Exception $e) {
// Problem on MySQL PDO interaction - error message passed
$error = $e->getMessage();
}
You forgot to add just after binding the values, before fetchColumn():
$count->execute();
I want my below PDO select to work with the bottom two IF statements?
The first IF I just want to make sure there is no error.
The second IF I want to check how many rows it returns. I know that this number of rows == 0 will not work.
Is there a way to do that?
try {
$conn = new PDO('mysql:host=localhost;dbname=zs', 'zs', 'rlkj08sfSsdf');
$conn ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo $e->getMessage();
die();
}
$stmt = $conn->prepare("SELECT * FROM zip WHERE zip_code =:zip1");
$stmt->bindValue(':zip1', $_POST[zipcode], PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
if($rows = "") {
echo "<p><strong>There was a database error attempting to retrieve your ZIP Code.</strong></p>\n";
}
if(number of rows == 0) {
echo "<p><strong>No database match for provided ZIP Code.</strong> Please enter a new ZIP Code.</p>\n";
}
You're interested only in whether there are records containing a particular value. It makes no sense to select everything and count the records in PHP. It's a waste of resources. Imagine what happens if there's a million records.
Solution you're after is to simply ask your database about the COUNT of rows containing a particular value. Your code should be quite simple:
$stmt = $conn->prepare("SELECT COUNT(*) AS num_rows FROM zip WHERE zip_code = :zip");
$stmt->bindValue(':zip', $_POST['zipcode'], PDO::PARAM_INT);
$stmt->execute();
$count = (int)$stmt->fetchColumn();
if($count)
{
echo "Success";
}
else
{
echo "Bummer";
}
Notes:
if successful, the above query will always return 1 row with 1 column, named num_rows which will be 0 for no matching records or an integer larger than 0 if there are records. If you use MySQL native driver with PHP, PHP will correctly represent this value as integer internally. I deliberately put typecasting in, you can remove it (the (int) part) if you have MySQL ND.
if something goes wrong during query execution, an exception will be thrown. The snippet doesn't cover that. You correctly set PDO in exception mode, and along with using bindValue instead of bindParam, this implies you did your research right and you're using PDO correctly which means that error handling should be implemented easily by you in this particular case.
I'm fetching results from MySQL database using PDO and I use value from $_GET request method as a condition. Everything works fine but if there is any fullstop (dot) in the $_GET value, MySQL returns 0 rows.
Here is my sample:
<?php
function filter($val) {
$f = htmlentities($val);
$f = filter_input(INPUT_GET, $f);
return strip_tags($f);
}
$dev = filter("dev");
function DevFetch($dev) {
$q = $this->link->prepare("SELECT app FROM table WHERE dev = ?");
$q->bindValue("1", $dev);
$q->execute();
if($q->rowCount() > 0) {
return $q->fetchAll();
} else {
return false;
}
}
?>
Here are some examples.
Case 1:
results.php?developer=Google+Inc // works fine
Case 2:
results.php?developer=Google // works fine
Case 3:
results.php?developer=Google+Inc. // doesn't work with dot at the end
Please help with this. Note that I'm encoding (urlencode()) the $_GET value as well as filtering it using filter_input() function. Without filtering / encoding also doesn't work.
Since you use prepared statements, you don't need that filter function.
Just that simple:
function DevFetch($dev) {
$q = $this->link->prepare("SELECT app FROM table WHERE dev = ?");
$q->bindValue(1, $dev);
$q->execute();
$result = $q->fetchAll();
if(count($result) > 0) {
return $result;
} else {
return false;
}
}
$input = $_GET["dev"];
DevFetch($input);
Taken directly from the docs:
PDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.
If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.
This means that this statement (being a SELECT):
$this->link->prepare("SELECT app FROM table WHERE dev = ?");
does not affect the return value of rowCount. To get the row count, you'll have to resort to mysqli or write:
$rows = $stmt->fetchAll();
$rowCount = count($rows);
If what you say is indeed true, and only the value with a dot on the end doesn't return a value for rowCount, then here's a couple of things you really ought to check:
PDO dsn string: specify the charset (add ;charset=utf8 to the end of the DSN string. details here
Set the error mode to have PDO throw exceptions on failure: PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
Check your DB for rows with the value that has the dot on the end, if it isn't there, than your code works as expected, simply because there are no results to work with
Would someone please me with the code below, I am inexperienced in this area and my class in SQL was "A long time ago in a galaxy far, far away..." I know the connection string works because I have used it in other functions with this app. I have even used the code below for retrieving *rows from another table in another function, for the most part, except that I didn't use the WHERE clause.
First, I am able to store IP addresses in the table using a function and it is working well. Now I want to check to see if a given one exist in this table. Partial code is given below.
What seems to always return is 0 rows. I have put in test data into the table and hard-coded the $ipA, but I still get 0 rows return. Please help if possible and thanks for the effort spent.
function checkDB($ipA) {
require_once('connection.inc.php');
$resultAns = "";
//create db connection
$conn = dbConnect();
//init prepared stmt
$stmt = $conn->stmt_init();
//Set sql query for ipAddress search
//prepare the SQL query
$sql = 'SELECT * FROM ipAddress WHERE ipA = ?';
//submit the query and capture the result
if ($stmt->prepare($sql)) {
$stmt->bind_param('s', $ipA);
$stmt = $stmt->execute();
//if qry triggers error affeted_rows value becomes -1 &
//php treats -1 as true; so test for greater than 0
$numRows = $stmt->num_rows; //not to sure about the syntax here
}
// I want to know if the query brought back something or not, I don't what
// to know exactly what, only that it found a match or did not find a match.
// echos are for testing purposes to show me where I am landing.
if ($numRows == 0) {
echo '<script type="text/javascript">window.alert("numRows = 0")</script>';
$resultAns = 0;
} elseif ($numRows == 1) {
echo '<script type="text/javascript">window.alert("numRows = 1")</script>';
$resultAns = 1;
}
return $resultAns;
}
Try storing the result after you execute
$stmt->store_result();
Use $stmt->store_result(); before you call num_rows.
While the others caught one reason that $numRows would never receive a value other than 0, the other piece of code that was flawed and caused problems was...
$stmt = $stmt->execute(); which should have been just $stmt->execute();
I must have mixed it up with other code I wrote from somewhere else.
Thanks for the answers, they did help.