Im a "noob" in smarty. I need to execute following code in one of my .tpl files:
<? // SELECT sql query
$sql = "SELECT 'id' , 'title' FROM `forum_posts` WHERE bid = '1' ORDER BY 'date' DESC LIMIT 4";
// perform the query and store the result
$result = query($sql);
// if the $result contains at least one row
if ($result->num_rows > 0) {
// output data of each row from $result
while($row = $result->fetch_assoc()) {
echo '<tr>
<td>'. $row['title']. ' </td>
</tr> ';
}
}
else {
echo 'No news';
}
?>
I've been trying for 3 hours now, surfing all over the web but without success.
Help please!
You are using quotes instead of backtick for column name, simply change them to avoid the error
SELECT `id` , `title` FROM `forum_posts` WHERE `bid` = '1' ORDER BY `date` DESC LIMIT 4";
require('../libs/SmartySQL.class.php');
$smarty = new SmartySQL( array('pdo_dsn' => 'mysql:dbname=db_name;host=localhost',
'pdo_username' => 'username',
'pdo_password' => 'password',
'pdo_driver_options' => array() ) );
$smarty->display('index.tpl');
Related
From the code below, this what I'm trying to achieve: If citizenID found by the $get_friends query are 1 and 2. I would like the while loop to first get all the rows for 1 and then do the same for 2. The code I currently have below its only retrieving the last row for 1 and 2. Please help.
<?php
include ('session_start.php');
include_once('db_connect_universal.php');
$user_id = $_SESSION['sess_id'];
//GET USER FRIENDS AND DETAILS
$get_friends = "SELECT * FROM citizens
INNER JOIN user_details
ON citizens.citizenID=user_details.UserID
WHERE citizens.userID = '".$user_id."'";
$results_get_friends = $conn->query($get_friends);
$num_rows_friends = mysqli_num_rows ($results_get_friends);
while ($row_friends = $results_get_friends->fetch_assoc()) {
$citizenID = $row_friends['citizenID'];
//GET RATINGS AND COMMENTS
$sql = "SELECT * FROM comments
INNER JOIN organiser ON comments.movieID=organiser.movieID
WHERE comments.userID= '".$citizenID."'
AND ratings_n_comments.Time BETWEEN DATE_SUB(CURDATE(), INTERVAL 28 DAY)
AND DATE_ADD(CURDATE(), INTERVAL 10 DAY)
ORDER BY comments.Time DESC";
$result = $conn->query($sql);
$num_rows = mysqli_num_rows ($result);
$row = $result->fetch_assoc();
$n_Rating[]= array(
'dp' => $row_friends['display_pics'],
'uname' => $row_friends['Uname'],
'poster'=> $row['mooster'],
'title'=> $row['moitle'],
'genre'=> $row['moenre'],
'comment'=> $row['Comment'],
'mid'=> $row['mID'],
'check' => 'data'
);
}
header('Content-Type: application/json');
echo json_encode ($n_Rating);
}
//detailed error reporting
if (!$sql) {
echo 'MySQL Error: ' . mysqli_error($conn);
exit;
}
?>
You are only fetching one row with $row = $result->fetch_assoc();.
Are you trying to fetch all the comments for the users?
Because then you'll need to loop trough everything $result has just like you are doing with while ($row_friends = $results_get_friends->fetch_assoc())
Also instead of concatenating your SQL query, try using prepare and bind_param to avoid possible SQL injection
The code below returns nothing, but if I remove this line:
'desc' => $row['DESC'],
from the function it works fine.
DESC Is a valid column in the database and when I run the full query in phpmyadmin, it returns the desired result.
I am not sure why this line
'desc' => $row['DESC'],
breaks the return of the result.
=======
After more investigating I can see the JSON output has the same issue.
Altering the column name (since DESC is a keyword) and reflecting the changes in the query has no effect.
========
function get_all_subjects($db1) {
$stmt = $db1->query("SELECT DISTINCT NAME, DESC, CLASSCODE FROM tbl_subjects WHERE VISIBLE = 1 ORDER BY NAME ASC");
$stmt->execute();
$count = $stmt->rowCount();
$column = array();
if ($count >0)
{
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$column[] = array(
'name' => $row['NAME'],
'desc' => $row['DESC'],
'cc' => $row['CLASSCODE']
);
}
return json_encode(array('subjects' =>$column));
}
else
{
return $count;
}
}
DESC is a reserved word in SQL. If you want to use it as a column, you should protect it with forward quotes:
function get_all_subjects($db1) {
$stmt = $db1->query("SELECT DISTINCT NAME, `DESC` AS D, CLASSCODE FROM tbl_subjects WHERE VISIBLE = 1 ORDER BY NAME ASC");
$stmt->execute();
$count = $stmt->rowCount();
$column = array();
if ($count >0)
{
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$column[] = array(
'name' => $row['NAME'],
'desc' => $row['D'], // Using the alias, just in case
'cc' => $row['CLASSCODE']
);
}
return json_encode(array('subjects' =>$column));
}
else
{
return $count;
}
}
DESC is a reserved Keyword do something like
SELECT DISTINCT NAME, DESC as yourVar, CLASSCODE FROM tbl_subjects WHERE VISIBLE = 1 ORDER BY NAME ASC
and then like that
'desc' => $row['yourVar'],
$stmt = $db1->query("SELECT DISTINCT `NAME`, `DESC`, `CLASSCODE` FROM `tbl_subjects` WHERE `VISIBLE` = 1 ORDER BY `NAME` ASC");
there was syntax error because desc is reserved keyword, you have to use quotes, the best habbit is quote each column and each table name
Thank you all for your answers - I found the problem and what broke the script was that my strings in my JSON values had several - in them.
It took me a while to find it :-)
Im trying to get some values from mysql and echo each value inside an article. Everything is working fine , I just wanna know how to limit page articles to 15 per page and when the limit is reached create page #2 etc , Here is the php code im using
$query = "SELECT `text` FROM `items` ORDER BY 'id'";
if ($query_run = mysql_query($query))
while ($query_row = mysql_fetch_assoc($query_run)) {
$text = $query_row['text'];
echo "<article>$text</article>";
}
} else {
echo mysql_error($conn_error);
}
Any suggestions? Thanks .
This has nothing to do with HTML. Add a LIMIT clause to your SQL query.
select `text` from `items` order by 'id' limit 15
Read up on SQL Pagination.
In addition to #meagar's answer: mysql is deprecated. You should use the mysqli improved API.
Example:
$mysqli = new mysqli('host', 'user', 'password', 'databasename');
$query = "SELECT `text` FROM `items` ORDER BY 'id' LIMIT 15";
if($result = $mysqli->query($query)){
while ($row = $result->fetch_assoc()) {
$text = $row['text'];
echo "<article>$text</article>";
}
}
}
My page displays an image, and I want to display the previous and next image that is relevant to the current one. At the moment I run the same query 3x and modify the "where" statement with =, >, <.
It works but I feel there must be a better way to do this.
The image id's are not 1,2,3,4,5. and could be 1,2,10,20,21 etc. But if it is much more efficient I am willing to change this.
mysql_select_db("database", $conPro);
$currentid = mysql_real_escape_string($_GET['currentid']);
$query ="SELECT * FROM database WHERE id ='".$currentid."' LIMIT 1 ";
$result = mysql_query($query,$conPro) or die(mysql_error());
$affected_rows = mysql_num_rows($result);
if ($affected_rows==1)
{
$row = mysql_fetch_array($result)or die ('error:' . mysql_error());
$current_id = $row['id'];
$current_header = $row['title'];
$current_description =$row['desc'];
$current_image = "http://".$row['img'];
$current_url = "http://".$row['id']."/".$db_title."/";
$current_thumb = "http://".$row['cloud'];
}
mysql_select_db("database", $conPro);
$query ="SELECT * FROM database WHERE id <'".$currentid."' ORDER BY id DESC LIMIT 1 ";
$result = mysql_query($query,$conPro) or die(mysql_error());
$affected_rows = mysql_num_rows($result);
if ($affected_rows==1)
{
$row = mysql_fetch_array($result)or die ('error:' . mysql_error());
$previous_id = $row['id'];
$previous_header = $row['title'];
$previous_description =$row['desc'];
$previous_image = "http://".$row['img'];
$previous_url = "http://".$row['id']."/".$db_title."/";
$previous_thumb = "http://".$row['cloud'];
}else{
$previous_none = "true"; //no rows found
}
mysql_select_db("database", $conPro);
$query ="SELECT * FROM database WHERE id >'".$currentid."' ORDER BY id ASC LIMIT 1 ";
$result = mysql_query($query,$conPro) or die(mysql_error());
$affected_rows = mysql_num_rows($result);
if ($affected_rows==1)
{
$row = mysql_fetch_array($result)or die ('error:' . mysql_error());
$next_id = $row['id'];
$next_header = $row['title'];
$next_description =$row['desc'];
$next_image = "http://".$row['img'];
$next_url = "http://".$row['id']."/".$db_title."/";
$next_thumb = "http://".$row['cloud'];
}else{
$next_none = "true"; //no rows found
}
mysql_close($conPro);
Thank you for your time
You don't have to do select_db each time. Once you 'select' a db, it stays selected until you select something else.
You can't really get away from doing two separate queries to get the next/previous images, but you can fake it by using a union query:
(SELECT 'next' AS position, ...
FROM yourtable
WHERE (id > $currentid)
ORDER BY id ASC
LIMIT 1)
UNION
(SELECT 'prev' AS position, ...
FROM yourtable
WHERE (id < $currentid)
ORDER BY id DESC
LIMIT 1)
This would return two rows, containing a pseudofield named 'position' which will allow you to easily identify which row is the 'next' record, and which is the 'previous' one. Note that the brackets are required so that the 'order by' clauses apply to the individual queries. Without, mysql will take the order by clause from the last query in the union sequence and apply it to the full union results.
You can get the "previous" one first WHERE id <'".$currentid."' ORDER BY id DESC, and then query for two "above" it: SELECT * FROM database WHERE id >= '".$currentid."' ORDER BY id ASC then it takes only two queries instead of three.
I am trying to show all of the data in the 'status' column of my table but am having troubles. What am I doing wrong:
<?php
$query1 = "SELECT id, status FROM alerts WHERE customerid='".$_SESSION['customerid']."' ORDER BY id LIMIT $start, $limit ";
$result = mysql_query($query1);
while ($row = mysql_fetch_array($result))
{
echo $row['status'] ;
}
?>
Try this:
$query1 = "SELECT id, `status` FROM alerts WHERE customerid='".$_SESSION['customerid']."' ORDER BY id LIMIT $start, $limit ";
$result = mysql_query($query1) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
echo $row['status'];
}
Also, make sure that:
$_SESSION['customerid'], $start and $limit are not empty. You can test the constructed query with echo $query1;
Note: Addition of mysql_error() in in the mysql_query will allow you to see if there is an error in the query.
I am trying to show all of the data in
the 'status' column of my table
If you want to show all the rows, your query should be:
$query1 = "SELECT id, `status` FROM alerts ORDER BY id";
But if you want to show for a specific customer, your query should be:
$query1 = "SELECT id, `status` FROM alerts WHERE customerid='".$_SESSION['customerid']."' ORDER BY id";