Hi I'm currently using the following code (1) to LIMIT the number of lines for the results to be displayed. But I want to use a different method but it is not working (2) could someone please help me with the correct syntax?
Code (1) Current.
function find_all_limit10() {
global $db;
$sql = "SELECT * FROM stock ";
$sql .=" ORDER BY po_date DESC";
$sql .=" LIMIT 10";
return find_by_sql($sql);
}
Code (2) Desired but missing LIMIT 10 and ORDER BY
function find_all_limit10($table) {
global $db;
if (tableExists($table)) {
return find_by_sql("SELECT * FROM {$db->escape($table)}");
}
}
Any help will be much appreciated.
Thank you
I think this is what you are trying to do. In PHP you can join strings using . So we will append the result of the $db->escape($table) string to the end of the SELECT Statement.
function find_all_limit10($table) {
global $db;
$sql = "SELECT * FROM ". $db->escape($table);
$sql .=" ORDER BY po_date DESC";
$sql .=" LIMIT 10";
return find_by_sql($sql);
}
Not sure if this is what you are after...
function find_all_limit10($table) {
global $db;
if (tableExists($table)) {
$data = find_by_sql("SELECT * FROM " . $db->escape($table) );
// assuming $data is an array of rows
// keep just 10
return array_slice($data, 0, 10);
}
}
Related
I am new in oop and I am trying to change a sql query into 3 chained method and use like this:
$mtag = $mtag->allTags()->orderBy()->lastThree();
public function allTags()
{
$sql = "SELECT tag_id FROM posts_tags ";
$sql .= "GROUP BY tag_id ";
$sql .= "ORDER BY COUNT(*) DESC LIMIT 3 ";
$res = self::builder($sql);
return $res;
}
i want to use each $sql in to a separate chain method .
how can i do this?
i have tried this but it doesnt work
public function allTags()
{
$sql = "SELECT tag_id FROM posts_tags ";
self::builder($sql);
return $this;
}
public function orderBy()
{
$sql = "GROUP BY tag_id ";
self::builder($sql);
return $this;
}
public function lastThree()
{
$sql = "ORDER BY COUNT(*) DESC LIMIT 3 ";
self::builder($sql);
return $this;
}
my builder method looks like this
public function builder(string $sql)
{
$stmt = $this->database->prepare($sql);
$stmt->execute();
if (!$stmt) {
throw new Exception("Query failed . . .");
}
return $stmt;
}
The problem is that the self::builder($sql); method directly prepares the sql statement, instead of waiting for it to be completely constructed:
$mtag = $mtag
/*
the first self::builder($sql) is called,
prepares the statement without the order and group by
*/
->allTags()
/*
the second self::builder($sql) is called from orderBy, prepares "GROUP BY tag_id "
probably a syntax error is hidden here
*/
->orderBy()
/*
the third self::builder($sql) is called from lastThree
it tries to prepare "ORDER BY COUNT(*) DESC LIMIT 3 "
a syntax error is probably hidden here too
*/
->lastThree();
The statement is prepared over and over again. You can avoid this by doing, in that order
defining the statement with all its chained variants
calling a method to fetch data, preparing the statement composed from the various chained method calls.
$stmt = $mtag->allTags()->orderBy()->lastThree();
$result = $stmt->resolve();
where $stmt = $this->database->prepare($sql); only happens in the resolve method.
you have error in return code.
Change to that code!
public function lastThree()
{
$sql = "ORDER BY COUNT(*) DESC LIMIT 3 ";
$res = self::builder($sql);
return $res;
}
sorry my English is weak ....
how can i search multi values from db SQL So that there was any.
i can search name && family together but
I want when the user searched name And family leave empty Return result correctly
how can i write this
if (isset($_POST['searchname']) || isset($_POST['searchfamily'])) {
$sql = "select * from myinfo WHERE name='{$_POST['searchname']}' && family='{$_POST['searchfamily']}' ORDER BY id DESC";
}
else {
$sql = "select * from myinfo ORDER BY id DESC";
}
Your 3 main issues here..
the first being WHERE name= now.. name is already used by mysql therefore you shouldn't use it however.. If you do use it run it like this:
WHERE `name`=
You should always backtick database tables and columns to make life easier in the long haul.
The second issue being you used && where it should be AND
the third is you shouldn't be placing your variables straight into your query as you're left open for SQL Injection.
Now I'm running on the assumption you're using $mysqli as your variable however, this may need adjusting to suit the correct variable you are using:
if (isset($_POST['searchname']) || isset($_POST['searchfamily'])) {
$searchName = $_POST['searchname'];
$family = $_POST['searchfamily'];
$sql = $mysqli->prepare("select * from `myinfo` WHERE `name` = ? OR `family`= ? ORDER BY `id` DESC");
$sql->execute([$searchName, $family]);
} else {
$sql = $mysqli->prepare("select * from `myinfo` ORDER BY `id` DESC");
$sql->execute();
}
If you want to search with both then you need to change your if also. And change && to and in your query
if (isset($_POST['searchname']) && isset($_POST['searchfamily'])) {
$sql = "select * from myinfo WHERE `name`='{$_POST['searchname']}' AND family='{$_POST['searchfamily']}' ORDER BY id DESC";
}
else {
$sql = "select * from myinfo ORDER BY id DESC";
}
Edit
As per your comment try this:
if (isset($_POST['searchname']) || isset($_POST['searchfamily'])) {
$where="";
if(isset($_POST['searchname']))
$where=" WHERE `name`='{$_POST['searchname']}'";
if(isset($_POST['searchfamily']))
{
if($where=="")
$where=" WHERE family='{$_POST['searchfamily']}'";
else
$where=" AND family='{$_POST['searchfamily']}'";
}
$sql = "select * from myinfo $where ORDER BY id DESC";
}
else {
$sql = "select * from myinfo ORDER BY id DESC";
}
I build a query which i get an assoc array from. But how can I loop through them. this is what I have.
My SQL Query:
public static function album_display() {
global $database;
$sql = "SELECT a.*, ";
$sql .= "(SELECT photographs.filename ";
$sql .= "FROM photographs ";
$sql .= "WHERE photographs.albumid = a.name ";
$sql .= "ORDER BY photographs.creation_date ASC ";
$sql .= "LIMIT 1) ";
$sql .= "AS filename FROM album a ";
$result_set = $database->query($sql);
while($rows = mysqli_fetch_assoc($result_set)){
foreach($rows as $row) {
print_r($row);
}
}
}
If I use print_r() on $row the output is:
15Jaap1Jaap1.JPG16Jaap2Jaap4.JPG17Jaap3Jaap7.JPG18Jaap4Jaap12.JPG19Jaap5
I want to loop through Jaap1, Jaap2, Jaap3, Jaap 4 and put these in $albumid from the function album_path($albumid, $filename). I want to do the same wiht the JPG files. This function is in Class() Album. So is the function album_display()
The function album_path($albumid, $filename) if called needs to output the complete album/images path en echo these to the screen. And display the images
public function album_path($albumid, $filename) {
return $this->upload_dir.DS.$albumid.DS.$filename;
}
How can I use foreach for this. Or is there an other better way to do it?
Kind Regards,
Coos Wolff
Change the select a.*, into a select a.albumid. That should only return you the album id, and the filename, coming from the second SELECT statement.
Perhaps something like this? You can break the sql up onto multiple lines within the quotes which makes it easier to read and also use an alias for each of the tables, again making it slightly easier to read and quicker to write.
<?php
public static function album_display() {
global $database;
$sql = "SELECT a.*,
( SELECT p.`filename`
FROM `photographs` p
WHERE p`.`albumid` = a.name
ORDER BY p.`creation_date` ASC
LIMIT 1
) AS 'filename' FROM `album` a ";
$result_set = $database->query( $sql );
/* using object notation rather than array for ease */
while( $rows = mysqli_fetch_object( $result_set ) ){
$this->album_path( $rows->albumid, $rows->filename );
}
}
?>
$my_array = [];
public static function album_display() {
global $database;
$sql = "SELECT a.*, ";
$sql .= "(SELECT photographs.filename ";
$sql .= "FROM photographs ";
$sql .= "WHERE photographs.albumid = a.name ";
$sql .= "ORDER BY photographs.creation_date ASC ";
$sql .= "LIMIT 1) ";
$sql .= "AS filename FROM album a ";
$result_set = $database->query($sql);
while($rows = mysqli_fetch_assoc($result_set)){
foreach($rows as $row) {
$my_array['albumid'][] = $row->albumid;
$my_array['filename'][] = $row->filename;
}
}
}
foreach ($my_array['albumid'] as $albumid) {
echo $albumid;
}
foreach ($my_array['filepath'] as $filepath) {
echo $filepath;
}
album_path($my_array['albumid'], $my_array['filepath']);
mysqli_fetch_assoc returns one row at a time from the result set built by your query.
Each $row is an associative array and if you look more closely at the output of the var_dump() you will see that the array is a set of key - value pairs.
while($rows = mysqli_fetch_assoc($result_set)){
//echo $row['id'];
//echo $row['filename'];
//echo $row['albumid'];
// just to be sure add this line
// so we know exactly whats in $row
print_r($row);
}
Sorry because you used SELECT * for the other fields I dont know what to call the array elements. I hope you get the basic idea.
i have a simple query who select me 3 news from table, but i wont to change this number from other file whith variable.
So this is query:
$query = 'SELECT * FROM news ORDER BY created_at DESC LIMIT 3';
I tried differently, but did not work...
Help please
My code(i can't answer on my question so i add it here)
$newsAmount = 3;
function get_news() {
$query = "SELECT * FROM news ORDER BY created_at DESC LIMIT $newsAmount";
$result = mysql_query($query);
$news = array();
while ($row = mysql_fetch_array($result)) {
$news[] = $row;
}
return $news;
if (!$result) {
trigger_error('Invalid query: ' . mysql_error() . " in " . $query);
}
}
This is this code.
Actually you can just do this:
$query = "SELECT * FROM news ORDER BY created_at DESC LIMIT $newsAmount";
But make sure to keep the string in double quotes so the variable can be evaluated, Single quotes will be printed out as it is.
Try to echo $query, you will notice that its being printed.
Try this:
$newsAmount = 3;
$query = 'SELECT * FROM news ORDER BY created_at DESC LIMIT ' + $newsAmount;
you cannot return an array like you did in your code.
I would suggest to do the query inside your main code instead of writing it in a function.
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