PHP PDO Order ASC - php

I have this code as my function of getting the list, however with the ORDER BY code it doesnt work (doesn't return anything). How do i go about ordering it? I have looked at other peoples work on how o do it but i can't get it to work.
<?php
function getGenericList($conn, $limit) {
$sql = "SELECT * FROM `jobs_current` LIMIT ".$limit." ORDER BY `jobs_current`.`school` ASC";
$query = $conn->prepare($sql);
$query->execute();
$count = $query->rowCount();
if($count == 0){
return '<td class="td1"></td><td class="td2" style="color: red;">Sorry, there doesnt seem to be any results!</td><td class="td3"></td>';
}
$end = "";
foreach ($conn->query($sql) as $row) {
$end = $end.'<tr class="hoverOver"><td class="td1">'.$row['school'].'</td>';
$end = $end.'<td class="td2">'.$row['job_type'].'</td>';
$end = $end.'<td class="td3">'.$row['location'].'</td></tr>';
}return $end;
}
?>
Why doesn't it just return the rows in order defined? I generated the query using phpmyadmin so i don't understand why it doesnt work.

You query syntax is wrong, the correct way to write this is first ORDER and then LIMIT :
"SELECT * FROM `jobs_current` ORDER BY `jobs_current`.`school` ASC LIMIT ".$limit.""

Related

PDO pagination with LIKE

The following PHP SQL code shows error
Recoverable fatal error: Object of class PDOStatement could not be converted to string in /home/customer/xxxx/fetch_data.php on line 28
I was trying to display products information from the table filter
There are two $statement->execute();, one is to count total search results and another one is to display products for the current page.
I new to PDO method and not an expert in overall coding.
The $filter_query = $stmt . 'LIMIT '.$start.', '.$limit.''; is causing issues.
With that and related functions, the code works and displays data. But if I enable it, the error shows up.
$limit = '5';
$page = 1;
if($_POST['page'] > 1)
{
$start = (($_POST['page'] - 1) * $limit);
$page = $_POST['page'];
}
else
{
$start = 0;
}
$search = "%samsung%";
$stmt = $connect->prepare("SELECT * FROM filter WHERE product_name LIKE :needle");
$stmt->bindParam(':needle', $search, PDO::PARAM_STR);
##
##
$filter_query = $stmt . 'LIMIT '.$start.', '.$limit.'';
$statement->execute();
$total_data = $stmt->rowCount();
$stmt = $connect->prepare($filter_query);
$stmt->execute();
$result = $stmt->fetchAll();
$total_filter_data = $stmt->rowCount();
$output = '
<h3> '.$total_data.' results found </h3>
and display each product
I tried the following code as suggested by Your Common Sense and the pagination and total search result count is working fine, but no products are getting displayed.
$limit = '5';
$page = 1;
if($_POST['page'] > 1)
{
$start = (($_POST['page'] - 1) * $limit);
$page = $_POST['page'];
}
else
{
$start = 0;
}
$name=str_replace(' ', '%', $_POST['query']);
$search = "%$name%";
$base_sql = "SELECT %s FROM filter WHERE product_name LIKE ?";
##
##
####
$count_sql = sprintf($base_sql, "count(*)");
$stmt = $connect->prepare($count_sql);
$stmt->execute([$search]);
$total_data = $stmt->fetchColumn();
####
$data_sql = $count_sql = sprintf($base_sql, "*")." LIMIT ?,?";
$stmt = $connect->prepare($data_sql);
$stmt->execute([$search, $start, $limit]);
$result = $stmt->fetchAll();
##
$output = '
<h3> '.$total_data.' results found </h3> ';
if($total_data > 0)
{
foreach($result as $row)
{
and display each product
Using the following line makes the code show some data, but the pagination is not working.
$data_sql = sprintf($base_sql, "*");
$stmt = $connect->prepare($data_sql);
$stmt->execute([$search]);
$result = $stmt->fetchAll();
That's a not a trivial task as we need to run the same query twice but with minor differences. The first query will use count(*) SQL function to get the total number of records matching the search criteria. The second query will select actual fields with LIMIT clause to get the data for the single page.
$base_sql = "SELECT %s FROM filter WHERE product_name LIKE ?";
$count_sql = sprintf($base_sql, "count(*)");
$stmt = $connect->prepare($count_sql);
$stmt->execute([$search]);
$total = $stmt->fetchColumn();
$data_sql = $count_sql = sprintf($base_sql, "*")." LIMIT ?,?";
$stmt = $connect->prepare($data_sql);
$stmt->execute([$search, $start, $limit]);
$data = $stmt->fetchAll();
Important: In order for this code to work, make sure you are connecting to mysql properly. the proper connection will let a LIMIT clause to accept placeholders and also will warn you in case of any problems.

Why is store_result() not returning num_rows equivalent to mysqli Regular Statement?

I've been combing through previous questions and trying many solutions but cannot figure this out. I'm trying to convert this query to a Prepared Statement:
$query = mysqli_query($this->con, "SELECT * FROM notifications WHERE user_to='$userLoggedIn' ORDER BY id DESC");
Here is what I have:
$query = $this->con->stmt_init();
$query->prepare('SELECT * FROM notifications WHERE user_to=? ORDER BY id DESC');
$query->bind_param('s', $userLoggedIn);
$query->execute();
$query->store_result();
$qty = $query->num_rows;
$query_result = $query->get_result();
Below this code I have variables being used like this:
if($qty == 0) {
echo "<li class='no-more-posts' style='height: 0px; text-transform: uppercase;'>- You have no notifications! -</li>";
return;
}
$num_iterations = 0; //Number of messages checked
$count = 1; //Number of messages posted
while($row = $query_result->fetch_assoc()) {
if($num_iterations++ < $start)
continue;
if($count > $limit)
break;
else
$count++;
$user_from = $row['user_from'];
etc.etc.
What I am getting is blank result in my dropdown. If I change the while statement back to the original while($row = mysqli_fetch_array($query)) { (which I know is wrong and from old statement) my result is always returning the li No More Posts to Show. This tells me that $qty = $query->num_rows; is returning 0. Based on documentation my understanding is that once I buffered the result set with store_result() I could call $qty = $query->num_rows; right after. What am I missing here?
I'm certain this isn't the most efficient way to do things, but it's all I have on it; decided to break the statement up.
First I did a statement for the count:
$query_count = $this->con->stmt_init();
$query_count->prepare('SELECT COUNT(*) FROM notifications WHERE user_to=?');
$query_count->bind_param('s', $userLoggedIn);
$query_count->execute();
$query_count_result = $query_count->get_result();
$rows_count = $query_count_result->fetch_array();
$qty = array_shift($rows_count);
Then I did a statement for the data:
$query = $this->con->stmt_init();
$query->prepare('SELECT * FROM notifications WHERE user_to=? ORDER BY id DESC');
$query->bind_param('s', $userLoggedIn);
$query->execute();
$query_result = $query->get_result();
It solved my problem & everything works as expected. I know there is a better way to do this, so if someone has that suggestion great. In the meantime this will have to do.

Mysql pdo equal less than greater than characters for date

I am using that code without any problem via non-pdo.
mysql_query("
SELECT * FROM table
WHERE date_start >= '$date_start'
and date_end <= '$date_end'
");
But when I try using with pdo, code didn't work.
$query = $this->db->prepare("
SELECT * FROM table
WHERE date_start >= :date_start
and date_end <= :date_end
");
$query->execute(array(
'date_start'=>'2017-05-01 00:00',
'date_end'=>'2017-05-30 00:00'
));
Can I get help? Where is problem?
MORE INFO : (EDITED)
System : Windows (Appserv)
PHP Version : 5.6.30
I didn't see any error in error.log file.
I guess problem coming from $params array. Because worked like this:
$query = $db->prepare("SELECT * FROM brands WHERE brand_status=:brand_status and date_start >= :date_start and date_end <= :date_end");
$query->execute(array('brand_status'=>$brand_status, 'date_start'=>$date_s, 'date_end'=>$date_e));
But when I used execute(array($params)) not working. Actually if I not use date parameters working, but when I use date parameters not working. My example code below:
$extra = '';
$params = array();
$sql = "SELECT * FROM brands ORDER BY brand_name";
$brand_status = "1";
$brand_name = "";
$date_start = "2017-05-01 00:00:00";
$date_end = "2017-06-30 23:59:59";
if ($brand_status) {
$extra .= "brand_status=:brand_status and ";
$params[] = array("brand_status" => $brand_status);
}
if ($brand_name) {
$extra .= "brand_name LIKE :brand_name and ";
$params[] = array("brand_name" => "%" . $brand_name . "%");
}
if (dbDate($date_start)==1 and dbDate($date_end)==1)
{
$extra .= "date_start >= :date_start and date_end <= :date_end and ";
//problem here:
$params['date_start'] = $date_start;
$params['date_end'] = $date_end;
}
if (count($params) > 0) {
if (strlen($extra) > 0) {
$extra = rtrim($extra, ' and ');
}
$sql = "SELECT * FROM brands WHERE $extra ORDER BY brand_name";
$query = $db->prepare($sql);
$result = $query->execute($params);
} else {
$result = $query = $db->query($sql);
}
if($result)
$num = $query->rowCount();
if($num > 0) {
while($row = $query->fetch()) {
echo $row['brand_name'] . "<br>";
}
}
function dbDate($value)
{
$pattern = "/^1|2[0-9]{3}\-(0[1-9]|1[0-2])\-(0[1-9]|[1-2][0-9]|3[0-1])( [0-9]{2}:[0-9]{2}(:[0-9]{2})?)?$/";
if (preg_match($pattern, $value, $m)) { return 1; } else { return 0; }
}
How can I fix that $params problems for dates? Phil sorry my English is not good. I didn't understand totally your suggestions. I guess you found reason of problem.
execute(['date_start' => $date_start, 'date_end' => $date_end])
Finally I found reason of problem and I fixed my problem. Actually $params haven't any problem in execute array for dates too. Problem coming from $extra=rtrim($extra, ' and '); I changed to $extra=substr($extra, 0, -5); again and problem fixed.
This is correct sql with substr:
date_start >= :date_start and date_end <= :date_end
rtrim didn't give any error for other parameters but when I used rtrim for date_end sql it happened this way:
date_start >= :date_start and date_end <= :date_e
(nd character removed from date_end in sql)
Thanks your answers and your suggestions.

PHP loop from database and calculate

$st = $this->db->prepare("SELECT * FROM users WHERE id=? ORDER BY id ASC");
$st->execute(array($id));
if($st->rowCount() >= 1){
foreach ($st as $row) {
echo $row["exp"]."+";
}
}
So what I've tried is to echo $row["exp"]."+"; to simply add in a loop, but it just print it out. How can I fix?
Try like this
$st = $this->db->prepare("SELECT * FROM users WHERE id=? ORDER BY id ASC");
$st->execute(array($id));
$sum=0;
if($st->rowCount() >= 1){
foreach ($st as $row) {
$sum += $row["exp"];
}
echo $sum
}
you can also get sum of exp by single query SELECT SUM(exp) as exp FROM users WHERE id=? ORDER BY id ASC
Here, this should give you all the answers you need: http://www.homeandlearn.co.uk/php/php.html
In particular, look at section 6, Addition in PHP

why this sql not working?

I have a query
public static function TestQuery(
$start=0,
$limit=0){
$sql = "
SELECT count(*) AS total
FROM db.table1
JOIN db.table2
ON table1.fieldID = {$fieldID}
AND table2.assigned = 'N'";
$qry = new SQLQuery;
$qry->query($sql);
if($row = $qry->fetchRow()){
$total = intval($row->total);
}
return $total;
}
which works fine but when I add the limit as below, then it doesnt work and gives me errors
public static function TestQuery(
$start=0,
$limit=0){
$sql = "
SELECT count(*) AS total
FROM db.table1
JOIN db.table2
ON table1.fieldID = {$fieldID}
AND table2.assigned = 'N'";
//this fails
if($recordlimit > 0) $sql .= "LIMIT {$startRecord}, {$recordLimit} ";
//
$qry = new SQLQuery;
$qry->query($sql);
if($row = $qry->fetchRow()){
$total = intval($row->total);
}
return $total;
}
Any help will be appreciated
Put a space in front of LIMIT:
" LIMIT {$startRecord}, {$recordLimit} "
without the space you sql will result in a syntax error.
Edit: This is answer is not correct! MySQL will not error without a space before LIMIT (however, earlier versions of phpmyadmin will incorrectly parse such sql).
Your variables are called $limit and $start:
if($limit > 0) $sql .= " LIMIT {$start}, {$limit} ";
Try changing
if($recordlimit > 0) $sql .= "LIMIT {$startRecord}, {$recordLimit} ";
To
if($recordlimit > 0) $sql .= " LIMIT {$start}, {$limit} ";
It looks like your SQL is getting squished together and should be getting a bad syntax error, and you had the wrong (seemingly) variable names in there.
Wrong variables
if($recordlimit > 0) $sql .= "LIMIT {$startRecord}, {$recordLimit} ";
Solved
Thanks

Categories