PDO select where - php

I am brand new to PHP and mysql and am trying something here. In my HTML, I have one form where I enter a mileage and it's passed on to the PHP code and converted to an integer. Then I want to take that and check against the database to isolate the record I want so I can do some computations. In other words, if the mileage entered (I save it in a veriable called $term) is less than or equal to a mileage in the table, I want to use the record that matches this criteria. For example, I enter 45 miles and the table has records at 40 miles and 50 miles, I want to pick the 50 mile level. If the user puts in 51, I want to use the 50 level. Things like that.
It connects to the database nicely but I'm not sure how to structure this at the foreach statement.
I have the following:
$term = (int)$_POST['term'];
try {
$dbh = new PDO("mysql:host=$hostname;dbname=ratetable", $username, $password);
/*** The SQL SELECT statement ***/
$sql = "SELECT * FROM rates WHERE mileage<=term";
foreach ($dbh->query($sql) as $row)
{
print $row['mileage'] .' - '. $row['ratepermile'] . '<br />';
}
/*** close the database connection ***/
$dbh = null;
}
When I do this, I get an invalid argument supplied foreach().
Then I started looking around and saw statements that look like this:
$stmt = $db->prepare( 'SELECT * FROM rates WHERE mileage<=:term' );
where the search parameter is passed and so on.
So now I'm confused about what the correct way is to select a single record in an ascending list of mileages in a database (the last matching record versus all that match) that satisfies a criteria or how to correctly structure the WHERE argument. Any suggestions?
Thank you for looking.

What you would need to do is use a WHERE clause in combination with ORDER BY and LIMIT clauses. For example to get the highest value that is less than or equal to a given search criteria you would do:
SELECT * FROM rates
WHERE mileage <= ?
ORDER BY mileage DESC
LIMIT 1
To get the lowest value that is greater than or equal to a given search value do:
SELECT * FROM rates
WHERE mileage >= ?
ORDER BY mileage ASC
LIMIT 1
As far as doing the actual PDO you would do something like this:
$stmt = $dbh->prepare('SELECT * FROM rates WHERE mileage <= ? ORDER BY mileage DESC LIMIT 1');
$stmt->execute(array($term));
$row_object = $stmt->fetchObject();

$sql = "SELECT * FROM rates WHERE mileage<=term";
What this means is select * from rates where the column mileage <= the column term. I do not think you have the column term as that should be a parameter.
You are right to take a look at parameters. The code should be something like:
$term = 150;
$sth = $db->prepare('SELECT * FROM rates WHERE mileage<=?');
$sth->execute(array($term));
To get only one of the records you should order by a column and get only the LIMIT 1
$term = 150;
$sth = $db->prepare('SELECT * FROM rates WHERE mileage<=? ORDER BY mileage DESC LIMIT 1');
$sth->execute(array($term));
Because you only want 1 row you can just do a $result=$sth->fetchColumn(); instead of the foreach.

Related

How to find out how many rows match a rule?

I want to find out how many rows in a table of my database meet a certain rule, specifically that "category" matches another variable and "published" is today or earlier. Then I want to simply echo that number.
I have no idea how to go about doing this, though.
I thought I could use count() but I'm not sure how to call just a single column and put the results of each row in an array.
Thanks!
Do this using SQL:
Try this in your database (your columns/tables may be different):
SELECT count(*) FROM blog_posts WHERE category = 'hot_stuff' and published <= NOW();
Then to execute this in PHP, depending on your framework and connection to the database:
$myCategory = 'hot_stuff';
$myTable = 'blog_posts';
$sql = "SELECT count(*) FROM {$myTable} WHERE category = '{$myCategory}' and published <= NOW();";
$rowCount = $db->query($sql);
echo $rowCount;
Connect to your database.
$pdo = new PDO($dsn, $user, $password);
Create a prepared statement. This is essential because you need to pass a value for category from your application to the query. It is not necessary to pass a value for the current date because the database can provide that for you. The ? is a placeholder where the parameter you pass will be bound.
$stmt = $pdo->prepare("SELECT COUNT(*) FROM your_table
WHERE category = ? AND published <= CURDATE()");
Do not concatenate the parameter into your SQL string (like WHERE category = '$category') because this will create an SQL injection vulnerability.
Execute the prepared statement using your specified value for category.
$stmt->execute([$category]); // assuming you have already defined $category
Use fetchColumn to return a single value, the count of rows that matched your criteria.
echo $stmt->fetchColumn();

Retrieving total count of matching rows along with the rows themselves using PDO

I have a PDO snippet that retrieves a bunch of rows from a MySQL table and assigns the field values (2 fields are returned per row) to two arrays like so:
$connect = dbconn(PROJHOST,'dbcontext', PROJDBUSER, PROJDBPWD);
$sql= "SELECT contextleft, contextright FROM tblcontext WHERE contextleft REGEXP :word LIMIT 0, 25";
$xleft = array();
$xright = array();
$countrows = 0;
$word = "[[:<:]]".$term."[[:>:]]";
$query = $connect->prepare($sql);
$query->bindParam(":word", $word, PDO::PARAM_STR);
if($query->execute()) {
$rows = $query->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $row){
$pattern = '/\b'. $term .'\b/ui';
$replacer = function($matches) { return '<span class="highlight">' . $matches[0] . '</span>'; };
$xleft[$countrows] = preg_replace_callback($pattern, $replacer, $row['contextleft']);
$xright[$countrows] = $row['contextright'];
$countrows++;
}
$notfound = null;
}
$connect = null;
This works perfect. As you can see, I use the LIMIT clause to ensure only a maximum of 25 rows are extracted. However, there can actually be many more matching records in the table and I need to also retrieve the total count of all matching records along with the returned rows. The end goal is pagination, something like: 25 of 100 entries returned...
I understand I have 2 options here, both involving 2 queries instead of a single one:
$sql= "SELECT COUNT(*) FROM tblcontext WHERE contextleft REGEXP :word;
SELECT contextleft, contextright FROM tblcontext WHERE contextleft REGEXP :word LIMIT 0, 25";
or...
$sql= "SELECT SQL_CALC_FOUND_ROWS contextleft, contextright FROM tblcontext WHERE contextleft REGEXP :word LIMIT 0, 25;
SELECT FOUND_ROWS();";
But I am still confused around retrieving the returned count value in PHP. Like I could access the fields by running the fetchAll() method on the query and referencing the field name. How can I access the count value returned by either FOUND_ROWS() or COUNT()? Also, is there any way to use a single SQL statement to get both count as well as the rows?
If you have a separate query with the count, then you can retrieve its value exactly the same way as you read the values from any queries, there is no difference.
If you use SQL_CALC_FOUND_ROWS, then you need to have a separate query to call FOUND_ROWS() function:
SELECT FOUND_ROWS();
Since this is again a normal query, you can read its output the same way as you do now.
You can technically retrieve the record count within the query itself by adding a count(*) field to the query:
SELECT contextleft, contextright, (select count(*) from tblcontext) as totalrecords FROM tblcontext WHERE contextleft REGEXP :word LIMIT 0, 25
or
SELECT contextleft, contextright, totalrecords
FROM tblcontext WHERE contextleft, (select count(*) as totalrecords from tblcontext) t REGEXP :word LIMIT 0, 25
Limit affects the number of records returned, but does not affect the number of rows counted by the count() function. The only drawback is that the count value will be there in every row, but in case of 25 rows, that may be an acceptable burden.
You need to test which method works the best for you.

Get two types of number of rows with minimum lines

I have the following query.
$sql = "SELECT customer FROM furniture WHERE id = :id AND category = :cat";
$stmt = $connectdb->prepare($sql);
$stmt->execute(array(':id'=>$id, ':cat'=>"1"));
$resulta = $stmt->fetchAll(PDO::FETCH_ASSOC);
$rowcount = count($result);
This works perfectly. But I have a requirement to get the number of rows from WHERE id = :id AND category = :cat as well as to get the number of rows from WHERE category = :cat. Is it possible to do both of them without having to write all those SELECT query lines twice?
You can use conditional sum to get the 2 different counts something as
select
sum(id = :id AND category = :cat) as count1,
sum(category = :cat) as count2
from furniture;
Later you just fetch the records and get the values of count1 and count2
NOTE : If you just do row count it will always return 1 since its using the aggregate function
I would suggest that you write the query as:
select sum(id = :id) as numCatId, count(*) as numCat
from furniture
where cat = :cat;
Putting the condition in the where clause allows MySQL to use an index on furniture(cat) (or better yet furniture(cat, id). In general, it is a good idea to put common filtering conditions in the where clause. This reduces the number of rows needed for processing the rest of the query.

Fast select by category and price range in large mysql table

I need to select a random product from large MySQL table(~9000000 rows, 4.5GiB) with specific category ID and price range.
The solution I am using now takes about 30 seconds to complete request.
$query = mysqli_query($db, "SELECT MAX(id) FROM `products` WHERE category = $cat AND price >= $price_min AND price <= $price_max");
$f = mysqli_fetch_array($query);
$max_id = $f[0];
$random_id = rand(0, $max_id);
mysqli_free_result($query);
$query = mysqli_query($db, "SELECT * FROM `products` id=$random_id LIMIT 1");
$product = mysqli_fetch_assoc($query);
Is it possible to optimize the request?
To get some speed, you'll need to look into making sure category has an index.
But you can cut out a query if you use this:
$query = mysqli_query(
$db,
"
SELECT *
FROM `products`
WHERE
`category` = $cat
AND `price` BETWEEN $price_min AND $price_max
ORDER BY RAND()
LIMIT 1
"
);
$product = mysqli_fetch_assoc($query);
Hope this helps.
Use EXPLAIN to see the execution plan for the query. Make sure that MySQL is making use of an appropriate index to satisfy the query.
Reference: https://dev.mysql.com/doc/refman/5.5/en/using-explain.html
An appropriate index for this query would have category as a leading column, followed by price, and including the id column.
As an example:
CREATE INDEX products_IX1 ON products (category, price, id);
With that index in place, we'd expect the EXPLAIN output to show that MySQL is performing a range scan operation on the index, using the first two columns (as indicated by key_len column.) We also expect the EXPLAIN output to show "Using index" in the Extra column, since the index is a "covering" index for the query.
NOTE
This is not related to the question you asked, but...
The code example is vulnerable to SQL Injection. Potentially unsafe values that are incorporated into the text of a SQL statement must be properly escaped.
http://php.net/manual/en/mysqli.real-escape-string.php
A better pattern is to make use of prepared statements with bind placeholders.

Count rows, or keep int field for counting?

When I want to find out how many shoes Alfred has, I always count the rows in the table "usershoes" where the userid matches Alfred's
But since I switched to PDO, and select row count is not simple or bulletproof/consistent, I'm reconsidering my methods
Maybe I should instead keep an int field "shoes" directly in table "users", keep number of shoes there, and then increase/decrease that number for that user along the way? Feels not right..
If anyone has a solid method for simple row counting on an existing select query, without extra query, let me know
Try something like this
SELECT COUNT(*) FROM usershoes
WHERE userid="theIdOfTheUser";
I could not get count(fetchColumn()) or fetchColumn() to work correctly (outputted 1 when 0 was the real number)
So now I'm using this, and it works:
$sql = 'SELECT COUNT(*) as numrows, shoecolor FROM usershoes WHERE userid = ?'
$STH = $conn->prepare($sql);
$STH->execute(array($someuseridvar));
And then:
$row = $STH->fetch();
if ($row['numrows'] > 0) {
// at least one row was found, do something
}
With MySQL, you can use FOUND_ROWS():
$db = new PDO(DSN...);
$db->setAttribute(array(PDO::MYSQL_USE_BUFFERED_QUERY=>TRUE));
$rs = $db->query('SELECT SQL_CALC_FOUND_ROWS * FROM table LIMIT 5,15');
$rs1 = $db->query('SELECT FOUND_ROWS()');
$rowCount = (int) $rs1->fetchColumn();
$rowCount will contain the total number of rows, not 15.
Taken from:
http://php.net/manual/en/pdostatement.rowcount.php#83586

Categories