PHP MySQL - Counting Number of Rows from a select statement - php

I am attempting to create a discussion board, and am trying to display the number of topics and number of total posts in each forum. I believe the issue lies somewhere in my WHERE clause, as that was causing me issues before on a previous issue.
I know that rowCount() shouldn't be relied on, and in my case doesn't work anyway, mainly due to the fact that it doesn't work with SELECT statements.
I have looked into both SELECT count(*) statements as well as doing $row = $stmt->fetchAll(); $numrows = count($row) However, I didn't get either of them to work.
<?php
/* CATEGORIES */
/* SELECTS ALL OF THE CATEGORIES OF THE BOARD */
$query = "SELECT * FROM bkg_categories";
try {
$stmt = $db->prepare($query);
$result = $stmt->execute();
} catch(PDOException $e) {
$error[] = "An error has occured. Please try again later.";
}
$categories = $stmt->fetchAll();
/* FORUMS */
/* SELECT ALL OF THE FORUMS IN EACH CATEGORY FOR THE BOARD */
foreach($categories as $category) {
$catid = $category['category_id'];
$query = "SELECT * FROM bkg_forums WHERE category_id = :catid";
$query_params = array(':catid' => $catid);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
} catch(PDOException $e) {
$error[] = "An error has occured. Please try again later.";
}
$forums[$catid] = $stmt->fetchAll();
foreach($forums[$category['category_id']] as $forum) {
$query = "SELECT * FROM bkg_topics where forum_id = :forumid";
$query_params = array(':forumid' => $forum['forum_id']);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
} catch(PDOException $e) {
$error[] = "An error has occured. Please try again later.";
}
$rows3['forumid'] = $stmt->fetchAll();
$rowCount = count($rows3['forumid']);
echo $rowCount;
var_dump($rowCount);
}
}
/* END QUERIES */
?>
These are all of my select queries that I am using. In that last foreach loop in my PHP select queries, you can see what I was playing around with, the var_dump() and the echo works, when it's not inside any foreach loop except for the inital parent one, but once I move it down into my table, it doesn't seem to work.
<?php foreach($categories as $category): ?>
<table class="forumtable">
<tr>
<td colspan="2"><strong><?php echo $category['category_name']; ?></strong></td>
<td><strong>Lastest Post</strong></td>
<td><strong>Topics</strong></td>
<td><strong>Posts</strong></td>
</tr>
<?php foreach($forums[$category['category_id']] as $forum): ?>
<tr>
<td width="5%" class="forum"></td>
<td class="forum no-padding">
<?php echo $forum['forum_name']; ?>
<div class="description"><?php echo $forum['forum_desc']; ?></div>
</td>
<td width="15%" class="forum content">
<?php if($forum['forum_last_post_topic_id'] == 0): ?>
<div>No posts...</div>
<?php else: ?>
<?php if($forum['forum_last_post_id'] == 0): ?>
<?php echo substr($forum['forum_last_post_title'], 0, 10); ?>
<?php else: ?>
<?php echo substr($forum['forum_last_post_title'], 0, 10); ?>
<?php endif; ?>
<?php endif; ?>
</td>
<td width="5%" class="forum content">
<?php
echo $forum['forum_topics']; ?></td>
<td width="5%" class="forum content"><?php
echo $forum['forum_posts']; ?></td>
</tr>
<?php endforeach; ?>
</table>
<?php endforeach; ?>

I was able to finally get the select(*) to work.
$db->query('SELECT COUNT(*) FROM users')->fetchColumn(); was what I used to get what I needed to work.

Related

Pagination not working properly after adding in button for admin

I have pagination for a table to display data from the database in the table. This was working fine and I tried to add in a button which only admin's can see. If the user is not an admin they will not see this button. This feature works but once I did it, the pagination only shows one row of data compared to the maximum of 10 per page.
This is my code:
public function dataview($query)
{
$stmt = $this->db->prepare($query);
$stmt->execute();
if($stmt->rowCount()>0) // display records if there are records to display
{
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
$poll_id = $row['poll_id'];
$question = $row['question'];
?>
<tr>
<td><?php echo $row['poll_id']; ?></td>
<td><?php echo $row['question']; ?></td>
<td>Open Poll</td>
<td>Results</td>
<?php
$stmt = $this->db->prepare("SELECT * FROM users WHERE user_id=:user_id");
$stmt->execute(array(':user_id'=>$_SESSION['user_session']));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0){
$admin = $userRow['admin'];
if($admin == 1){
?>
<td>Delete Poll</td>
<?php
?>
</tr>
<?php
}
}
}
}
else
{
?>
<tr>
<td>Nothing here...</td>
</tr>
<?php
}
}
and this is the code on the html page which uses the pagination
<table align="center" border="1" width="100%" height="100%" id="data">
<?php
$query = "SELECT * FROM polls";
$records_per_page=10;
$newquery = $paginate->paging($query,$records_per_page);
$paginate->dataview($newquery);
$paginate->paginglink($query,$records_per_page);
?>
</table>
You are reusing variables like $stmt inside the loop that uses it. So do this:
$stmt = $this->db->prepare($query);
$stmt->execute();
if($stmt->rowCount()>0) // display records if there are records to display
{
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
$poll_id = $row['poll_id'];
$question = $row['question'];
?>
<tr>
<td><?php echo $row['poll_id']; ?></td>
<td><?php echo $row['question']; ?></td>
<td>Open Poll</td>
<td>Results</td>
<?php
$stmt2 = $this->db->prepare("SELECT * FROM users WHERE user_id=:user_id");
$stmt2->execute(array(':user_id'=>$_SESSION['user_session']));
$userRow=$stmt2->fetch(PDO::FETCH_ASSOC);
if($stmt2->rowCount() > 0){
$admin = $userRow['admin'];
if($admin == 1){
?>
<td>Delete Poll</td>
<?php
?>
</tr>
<?php
}
}
}
}
else
{
?>
<tr>
<td>Nothing here...</td>
</tr>
<?php
}
I have replace the $stmt inside the loop by $stmt2.

PHP MySQL Creating A Discussion Board

I am currently working on developing a discussion board. My issue is that it seems like it assigns each category the id of 4, and then displays the forums that are in category 4. (That's not explained very well, but hopefully you understand)...
<?php
/* CATEGORIES */
$query = "SELECT * FROM bkg_categories";
try {
$stmt = $db->prepare($query);
$result = $stmt->execute();
} catch(PDOException $e) {
$error[] = "An error has occured. Please try again later.";
}
$categories = $stmt->fetchAll();
/* FORUMS */
foreach($categories as $category) {
$catid = $category['category_id'];
$query = "SELECT * FROM bkg_forums WHERE category_id = :catid";
$query_params = array(':catid' => $catid);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
} catch(PDOException $e) {
$error[] = "An error has occured. Please try again later.";
}
$forums = $stmt->fetchAll();
foreach($forums as $forum) {
print $forum['forum_id'];
}
}
?>
and the html to display it all onthe page.
<?php foreach($categories as $category): ?>
<div><?php echo $category['category_name']; ?><?php echo $category['category_id']; ?></div>
<table width="100%">
<tr>
<td colspan="2">Forum</td>
<td>Lastest Post</td>
<td>Topics</td>
<td>Posts</td>
</tr>
<?php foreach($forums as $forum): ?>
<tr>
<td width="5%"></td>
<td><?php echo $forum['forum_name']; ?></td>
<td width="15%">
<!--<?php foreach($posts as $post): ?>
<?php echo substr($post['post_subject'], 0, 10); ?>
<?php endforeach; ?>-->
</td>
<td width="5%" class="text-center"></td>
<td width="5%" class="text-center"></td>
</tr>
<?php endforeach; ?>
</table>
<?php endforeach; ?>
EDIT:
I created four categories
General
Development
Gaming
Off-Topic
and 1 Forum with the category_id of 4, and that 1 forum, is displayed in each category.
You are overwriting $forums each time.
You could do something like
$forums[$catid] = $stmt->fetchAll();
and then
foreach($forums[$category['category_id']] as $forum):

Adding a new row in a table after every 3 images from database

I have a gallery where images are uploaded via MySQL database and displayed on my site in a table. Problem is, the images are inserted into rows of one. I need someone to alter my script to where a new row will be added after every 3 columns (images).
I asked this before but deleted the thread so I could start over. I've done a lot of research and learned a few things, but I cannot figure out how to write the script to fit my needs.
Script:
<table width="100%" border="1" cellspacing="0" cellpadding="4">
<?php
$sql = "SELECT * FROM ".$SETTINGS["data_table"]." ORDER BY id ASC";
$sql_result = mysql_query ($sql, $connection ) or die ('request "Could not execute SQL query" '.$sql);
if (mysql_num_rows($sql_result)>0) {
while ($row = mysql_fetch_assoc($sql_result)) {
?>
<tr>
<td><?php echo $row["img"]; ?><br>Size: <?php echo $row["size"]; ?><br>Views: <?php echo $row["clicks"]; ?></td>
</tr>
<?php
}
} else {
?>
<tr><td colspan="3">No results found.</td>
<?php
}
?>
</table>
You need to open and close your tags not every iteration, but every 3 iterations. The resulting code might look something like this:
<table width="100%" border="1" cellspacing="0" cellpadding="4">
<?php
$sql = "SELECT * FROM ".$SETTINGS["data_table"]." ORDER BY id ASC";
$sql_result = mysql_query ($sql, $connection ) or die ('request "Could not execute SQL query" '.$sql);
if (mysql_num_rows($sql_result)>0) {
$i=0;
while ($row = mysql_fetch_assoc($sql_result)) {
if ($i++ % 3 == 0) echo "<tr>";
?>
<td><?php echo $row["img"]; ?><br>Size: <?php echo $row["size"]; ?><br>Views: <?php echo $row["clicks"]; ?></td>
<?php
if ($i % 3 == 0) echo "</tr>";
?>
<?php
}
if ($i % 3 != 0) echo "</tr>";
} else {
?>
<tr><td colspan="3">No results found.</td>
<?php
}
?>
</table>
You the guy with this answer if ($i % 3 == 0) echo ""; are the savior. I tried so much in JavaScript. but haven't forgotten I could do this on back end.

How to use bootstrap css tables to display data from MySQL tables?

I'm trying to make it so that when a button is clicked on my main page, a php script takes action and fetches the information from the SQL tables, and displays it in a HTML/CSS table.
Here's the code of my main page -
<form id="myForm" action="select.php" method="post">
<button type="submit" class="btn btn-info" >
<span class="glyphicon glyphicon-tint"></span> View
</button>
<br /> <span class="badge alert-info"> Find out what is currently in the database. </span><br />
</form>
<br />
<br />
And here's what I currently have in my select.php -
<?php
/*** mysql hostname ***/
$hostname = '192.xx.xxx.xx';
/*** mysql username ***/
$username = 'Mitchyl';
/*** mysql password ***/
$password = 'root1323';
/*** database name ***/
$dbname = 'test';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
/*** The SQL SELECT statement ***/
$sql = "SELECT * FROM increment";
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
I just don't know how to take the data from the SQL query and put it inside a HTML table.
Any suggestions would be great!
Thanks!
Try this
<?php
$hostname = '192.xx.xxx.xx';
$username = 'Mitchyl';
$password = 'root1323';
$dbname = 'test';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$sql = $dbh->prepare("SELECT * FROM increment");
if($sql->execute()) {
$sql->setFetchMode(PDO::FETCH_ASSOC);
}
}
catch(Exception $error) {
echo '<p>', $error->getMessage(), '</p>';
}
?>
<div id="content">
<table>
<?php while($row = $sql->fetch()) { ?>
<tr>
<td><?php echo $row['column1_name']; ?></td>
<td><?php echo $row['column2_name']; ?></td>
<td><?php echo $row['column3_name']; ?></td>
...etc...
</tr>
<?php } ?>
</table>
</div>
Let's say your sql returns an array named $data and its format is sth like $data = [['name' => 'name1'], ['name' => 'name2'], ...];.
//First declare your data array
$data = [];
// Then execute the query
$result = $mysqli->query($sql)
// Then read the results and create your $data array
while($row = $result->fetch_array())
{
$data[] = $row;
}
Now that you have your data check if it is empty or not and then use foreach to present the results.
<?php if(empty($data)): ?>
<h1>No results were found!</h1>
<?php else: ?>
<h1><?= count($data) ?> results were found!</h1>
<table class="table">
<thead>
<th>#</th>
<th>Name</th>
</thead>
<tbody>
<?php foreach ($data as $key => $value): ?>
<tr>
<td><?= ++$key ?></td>
<td><?= $value['name'] ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
Of course you can add any class you like to the table apart from the default one that bootstrap uses (.table).

How to set my query for a PDO prepared statement

I have built a PDO connection and query, now I need it to be safe from SQL Injection
Here is my code
User Input
<?php $search=$_GET["Search"];?>
SQL that querys DB
<?php
// Issue the query
$Recordset1 = $dbh->query("SELECT * FROM catelogue
WHERE catelogue.TITLE LIKE '$search'");
$Recordset1->setFetchMode(PDO::FETCH_ASSOC);
?>
Fetch The rows
<?php $row_Recordset1 = $Recordset1-> fetch(); ?>
After this there is a table with a do-while loop to display everything that was returned
How do I make a prepared statement for my query?
Thanks
EDIT:
Ok That last bit of code that DavdRew posted helped to get my search working again. Now I have 2 new problems.
Problem 1: After doing a few querys I get this message
mysql_pconnect() [function.mysql-pconnect]: MySQL server has gone away
It still shows the rest of my page with what I searched for. How is this fixed?
Then Problem 2:
With every search the first record returned is empty, a blank record. It never did this before, Why is it doing it now?
Many Thanks DavdRew
EDIT: ADDED MORE CODE
THIS IS THE ENTIRE PDO CODE
<?php
$hostname_EchosPDO = "localhost";
$username_EchosPDO = "echos";
$password_EchosPDO = "echos";
$database_EchosPDO = "full catelogue";
$connStr = 'mysql:host=localhost;dbname=full catelogue';
try {
$dbh = new PDO($connStr, $username_EchosPDO, $password_EchosPDO);
/*** echo a message saying we have connected ***/
echo 'Connected to database';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
<?php
$q = $dbh->prepare("SELECT * FROM catelogue WHERE catelogue.TITLE LIKE ?"); // prepare statement
if ($q->execute(array('sharpay%'))) // execute wirh passed params array($search)
{
$row_Recordset1 = $q->fetchAll(PDO::FETCH_ASSOC); // store fetched result into $rows;
}
else
{
$error = $dbh->errorInfo();
throw new Exception("SQLSTATE: {$error[0]}. {$error[1]} {$error[2]}");
}
?>
<?php /* $row_Recordset1 = $Recordset1-> fetch(); */ ?>
<?php do { ?>
<table width="800" border="0">
<tr>
<form action="/Echos Online/Detail.php" method="get"><input value='<?php echo $row_Recordset1['CAT NO.']; ?>' name="detail" type="hidden"/><td width='100' rowspan='4'><input type="image" img src="<?php echo $row_Recordset1['IMAGE PATH']; ?>" width="<?php if ($row_Recordset1['FORMAT']=='DVD') {echo "70";} else if ($row_Recordset1['FORMAT']=='DVD+CD') {echo "70";} else if($row_Recordset1['FORMAT']=='BLURAY+CD') {echo "81";}else if($row_Recordset1['FORMAT']=='BLURAY+DVD') {echo "81";} else if($row_Recordset1['FORMAT']=='BLURAY') {echo "81";} else {echo "100";} ?>" height="100"></td></form>
<td width="100">Artist:</td>
<td><?php echo $row_Recordset1['ARTIST']; ?></td>
</tr>
<tr>
<td width="100">Title</td>
<td><?php echo $row_Recordset1['TITLE']; ?></td>
</tr>
<tr>
<td width="100">Format</td>
<td><?php echo $row_Recordset1['FORMAT']; ?></td>
</tr>
<tr>
<td width="100">Cat. No.</td>
<td><?php echo $row_Recordset1['CAT NO.']; ?></td>
</tr>
<hr background-color="#e4a566" color="#e4a566"; width="100%"/>
<?php } while ($row_Recordset1 = $q-> fetch()); ?>
</table>
Honestly now I'm at the piont of going back to preg_replace and mysql_real_escape_string
Thanks for the help
Like this:
$q = $this->pdo->prepare($query);
$data = array();
if ($q->execute($params)) // params is the array of values for each '?' in your prepared statement.
$data = $q->fetchAll($fetch);
else
{
$error = $this->pdo->errorInfo();
throw new \Exception("SQLSTATE: {$error[0]}. {$error[1]} {$error[2]}");
}
return $data;
Keep in mind that WHERE IN works bad, you need to put as much ? into you imploded by , and wrapped with IN ( from left and ) right.
Example:
$statement = $pdo->prepare('SELECT * FROM my_table AS m WHERE m.id = ?');
if ($statement->execute(array(24))) // here you can pass values too.
$data = $q->fetchAll(\PDO::FETCH_ASSOC);
else
exit('Shit happens');
This search for record with id = 24;
For your code, that would be:
$q = $dbh->prepare("SELECT * FROM catelogue WHERE catelogue.TITLE LIKE ?"); // prepare statement
if ($q->execute(array($search))) // execute wirh passed params array($search)
{
$rows = $q->fetchAll(PDO::FETCH_ASSOC); // store fetched result into $rows;
}
else
{
$error = $dbh->errorInfo();
throw new Exception("SQLSTATE: {$error[0]}. {$error[1]} {$error[2]}");
}
Output:
<table width="800" border="0">
<?php foreach ($rows as $row): ?>
<tr>
<form action="/Echos Online/Detail.php" method="get"><input value='<?php echo $row['CAT NO.']; ?>' name="detail" type="hidden"/><td width='100' rowspan='4'><input type="image" img src="<?php echo $row['IMAGE PATH']; ?>" width="<?php if ($row['FORMAT']=='DVD') {echo "70";} else if ($row['FORMAT']=='DVD+CD') {echo "70";} else if($row['FORMAT']=='BLURAY+CD') {echo "81";}else if($row['FORMAT']=='BLURAY+DVD') {echo "81";} else if($row['FORMAT']=='BLURAY') {echo "81";} else {echo "100";} ?>" height="100"></td></form>
<td width="100">Artist:</td>
<td><?php echo $row['ARTIST']; ?></td>
</tr>
<tr>
<td width="100">Title</td>
<td><?php echo $row['TITLE']; ?></td>
</tr>
<tr>
<td width="100">Format</td>
<td><?php echo $row['FORMAT']; ?></td>
</tr>
<tr>
<td width="100">Cat. No.</td>
<td><?php echo $row['CAT NO.']; ?></td>
</tr>
<hr background-color="#e4a566" color="#e4a566"; width="100%"/>
<?php endforeach; ?>
</table>
$pdo = new PDO('mysql:host=localhost;dbname=mydb', $username, $password);
$stmt = $pdo->prepare('SELECT * FROM catelogue WHERE catelogue.TITLE LIKE :search');
$stmt->bindValue('search', $search);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
OR
$stmt = $pdo->prepare('SELECT * FROM catelogue WHERE catelogue.TITLE LIKE :search');
$stmt->execute(array('search' => $search);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
note that you probably want to have your $search string wrapped with wildcard characters, like
$stmt->bindValue('search', '%'.$search.'%');
also note that searching using like wont use index if you have wildcard on left side of like criteria
$stmt->bindValue('search', '%'.$search.'%'); //will not use index
$stmt->bindValue('search', $search.'%'); //will use index

Categories