How can I add prepare statement in my comment printing system - php

I'm currently building a system where users can write and read comments. So the comments will be inserted into database (the inserting part is already protected with the prepared statement), so now I want to add the prepared statement at the comment printing part too.
This is the comment inserting part
<?php
if (isset($_POST['submit'])) {
$nickname=$_POST['user_nickname'];
$email=$_POST['user_email'];
$comment=$_POST['cmt_text'];
$course=$_POST['user_course'];
$rating=$_POST['user_rating'];
$classof=$_POST['user_classof'];
$school_id=$_POST['id'];
$db="INSERT INTO comments(user_nickname,user_email,cmt_text,user_course,user_rating,school_id,user_classof) VALUES(?,?,?,?,?,?,?)";
$stmt=mysqli_stmt_init($con);
if(!mysqli_stmt_prepare($stmt,$db)){
echo "Data Error";
}else{
mysqli_stmt_bind_param($stmt,"ssssiii", $nickname,$email,$comment,$course,$rating,$school_id,$classof);
mysqli_stmt_execute($stmt);
}
header("location:Done.php");
exit;
}?>
And this is where I want to add prepared statements
<?php
$sql = "SELECT * FROM comments WHERE school_id=$sid ORDER BY Datetime DESC ";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
?>
<div class="single-item">
<h4><?php echo $row['user_nickname']; ?></h4>
<p><?php echo $row['Datetime'];
?></p>
<p><b>Course</b> : <?php echo $row['user_course'];
?></p>
<p><b>Class of</b> <?php echo $row['user_classof'];
?></b></p>
<p><b>Rating : </b><?php echo $row['user_rating'];
?>/5</p>
<p><b>Comment : </b><?php echo $row['cmt_text'];
?></p>
</div>
<?php
}
}
?>
I have tried adding, but I got stuck when it comes to the part where I need to put the parameter, since I am printing out all the comments, how can I add the ? parameter?
By the way, $sid is a specific id for one school. There's more than a hundred schools in thecomments table. I put all the comments from every schools in one table.

Just create a function in which you will prepare the data.
function selectComments(mysqli $mysqli, ?int $schoolId = null): array
{
if ($schoolId) {
$stmt = $mysqli->prepare('SELECT * FROM comments WHERE school_id=? ORDER BY Datetime DESC');
$stmt->bind_param('s', $schoolId);
$stmt->execute();
$result = $stmt->get_result();
} else {
$result = $mysqli->query('SELECT * FROM comments ORDER BY Datetime DESC');
}
return $result->fetch_all(MYSQLI_ASSOC);
}
Then you can call it like this:
foreach(selectComments($con, $sid) as $row) {
// your HTML table
}

Related

PHP PDO Display message if no results are found in search

I am trying to set an 'No Results Found' message when no search results are found after executing a MySQL 'LIKE' Query
I have the following code below:
I have an if statement just to test to see if an error message will work but I seem to get the output of the else statement 'found'
<table class="center"> <!-- Creating a table with the class of 'center' -->
<!-- SEARCH FORM -->
<?php
$KEYWORD = $_POST['keyword'];
$stmt = $conn->prepare("SELECT DISTINCT dog_park_name FROM dog_park.items WHERE dog_park_name LIKE '%{$KEYWORD}%'");
$stmt->execute();
for($i=0; $row = $stmt->fetch(); ){
$_SESSION["KEYWORD".$i] = $row[0];
if(empty($stmt))
{
echo 'Nothing found';
}
else
{
echo 'found';
}
?>
<!-- DISPLAY RESULTS -->
<tr> <!-- Adding the first table row -->
<th>Dog Park</th> <!-- Adding the second table header -->
</tr>
<tr> <!-- Adding the second table row -->
<td><a href="individual_item_page.php?keyword='<?php echo $row[$i] ?>' " ><?php echo $row[$i] ?></a></td> <!-- Add the second cell on the second row -->
</tr>
<?php } ?>
</table>
Example:
If a user searches a keyword, and no results are found from that keyword, I am trying to get a message saying 'No Results found'
To make a Mike Brant's answer a proper one:
$stmt = $conn->prepare("SELECT DISTINCT dog_park_name FROM items WHERE dog_park_name LIKE ?");
$stmt->execute(array("%".$_POST['keyword']."%"));
$_SESSION['KEYWORD'] = $stmt->fetchAll(PDO::FETCH_COLUMN);
if($_SESSION['KEYWORD']) {
?>
<table>
<tr><th>Dog Park</th></tr>
<?php foreach($_SESSION['KEYWORD'] as $word):?>
<tr><td><?php echo $word?></td></tr>
<?php endforeach?>
</table><?php
} else {
echo 'Nothing found';
}
So in other words, you always have the query results to tell whether you have any results.
Your if structure should show 'found' because your query executed successfully, in this cases you can count rows for decide about this issue:
if($stmt->rowCount() == 0)
{
echo 'Nothing found';
}
else
{
echo 'found';
}
I am not going to get into the SQL injection problem you have with your current code. You need to fix it, likely using parameters with your prepared statement, but that is another topic.
I would also say your KEYWORD.$i approach is an antipattern. Why not just have numerically-indexed array under $_SESSION['KEYWORD']?
$_SESSION['KEYWORD'] = array();
$stmt = $conn->prepare("SELECT DISTINCT dog_park_name FROM dog_park.items WHERE dog_park_name LIKE '%{$KEYWORD}%'");
if($stmt) {
$result = $stmt->execute();
if($result) {
while($row= $stmy->fetch() {
$_SESSION['KEYWORD'][] = $row[0];
}
}
}
if(count($_SESSION['KEYWORD']) === 0) {
echo 'Nothing found';
} else {
echo 'found';
}

What is the procedural mysqli way of preparing SQL statements?

I have a SQL query in my code that I want to convert to a prepared statement to stop vulnerabilities like SQL injections. So this is what I want to convert:
<?php
$query = "SELECT * from `wp_posts` WHERE ID=$pid ";
$result = mysqli_query($link, $query);
//$id=$row['Gallery_Id'];
while($row = mysqli_fetch_array($result)){
?>
<h2 align="center"> <?php echo $row['post_title']; ?> </h2><br>
<div class="paracenter">
<p id="cont"><?php echo $row['post_content']; ?></p>
<hr color="black" width="10%">
</div>
<?php } ?>
This is what I tried, but it doesn't work.
$query = "SELECT * from `wp_posts` WHERE ID=? ";
$stmt = mysqli_prepare($link, $query);
if($stmt){
mysqli_stmt_bind_param($stmt, "i", $pid);
mysqli_stmt_bind_result($stmt, $dbpid);
mysqli_stmt_execute($stmt);
mysqli_stmt_fetch($stmt);
}
$result = mysqli_query($link, $query);
//$id=$row['Gallery_Id'];
while($row = mysqli_stmt_fetch($result)){
?>
<h2 align="center"> <?php echo $row['post_title']; ?> </h2><br>
<div class="paracenter">
<p id="cont"><?php echo $row['post_content']; ?></p>
<hr color="black" width="10%">
</div>
<?php } ?>
Almost all the examples online doesn't use the procedural method I use. How can I rectify this?
To protect your query against injection attack, you have two options. The first is super simple and just as secure as a prepared statement.
Cast $pid as an integer.
$query = "SELECT post_title, post_content FROM wp_posts WHERE ID = " . (int)$pid;
Secure and done.
How to write a prepared statement with result binding... (I don't use procedural mysqli syntax)
if (!$stmt = $link->prepare("SELECT post_title, post_content FROM wp_posts WHERE ID = ?")) {
echo "Syntax Error # Prepare"; // $link->error; <-- never show actual error details to public
} elseif (!$stmt->bind_param("i", $pid) || !$stmt->execute() || !$stmt->bind_result($title, $content)) {
echo "Syntax Error # ParamBind | Execute | ResultBind"; // $stmt->error; <-- never show actual error details to public
} else {
while ($stmt->fetch()) {
echo "<div>";
echo "<h2 align=\"cente\">$title</h2><br>";
echo "<div class=\"paracenter\">";
echo "<p id=\"cont\">$content</p>";
echo "<hr color=\"black\" width=\"10%\">";
echo "</div> ";
}
}
Some additional notes.
If you are not going to use result binding, you should use mysqli_fetch_assoc() instead of mysqli_fetch_array(). mysqli_fetch_array() will generate a bloated result set of both indexed and associative keyed elements (double what you actually need).
When you use bind_result(), you need to replace * in the SELECT clause with the columns to be extracted.
My first elseif() expression contains three separate calls & checks on $stmt. As soon as any one of those calls returns a falsey/erroneous response, the conditional expression short circuits and the remaining calls in the expression are never executed.
If adopting my object-oriented mysqli style, be sure to align your database connection syntax as object-oriented as well.

Handle query results properly multiple rows and columns

I want to do a a query to a mysql database that returns multiple rows and columns. I then want to assign the results to a variable and echo them out later in the page. However, the method I am using is long, tedious, and for this project impractical. here is what I am doing.
$result = mysql_query("SELECT * FROM people WHERE open_or_closed !='Closed' ORDER BY
number",$c) or die("two");
$number=mysql_num_rows($result);
if($mynumber>0){
$data= mysql_fetch_array($result,MYSQL_ASSOC);
$full_name1=mysql_result($result,0, 'full_name');
$phone_number1=mysql_result($result,0, 'phone_number');
$one=1;
}
if($mynumber>1){
$full_name2=mysql_result($result,1, 'full_name');
$phone_number2=mysql_result($result,1, 'phone_number');
$two=2;
}
Later when I want to echo it, I will not know if there is a record there or not, so I will have to
<?php if($one==1){echo '<div id="blackline"></div>';}?>
<div id="titletext"><?php echo $full_name1; ?></div><br />
<div id="datetext"><?php echo $phone_number1; ?></div>
Try this
$result = mysql_query("SELECT * FROM people WHERE open_or_closed !='Closed' ORDER BY
number",$c) or die("two");
$number=mysql_num_rows($result);
if($number>0)
{
$i=0;
while($row_result = mysql_fetch_array($result))
{
$full_name[$i][] = $row_result['full_name'];
$phone_number[$i][] = $row_result['phone_number'];
$i++;
}
}

mysql query within a mysql query

I'm trying to display information from a table in my database in a loop, but for certain information, I'm referencing other tables. When I try to get data from other tables, any data following will disappear. here is the code I am using:
`
//Below is the SQL query
$listing = mysql_query("SELECT * FROM Musicians");
//This is displaying the results of the SQL query
while($row = mysql_fetch_array($listing))
{
?>
...html here...
<? echo $row['name']; ?>
<? echo $row['Town']; ?>
<?
$CountyRef = $row['CountyId'];
$county = mysql_query("SELECT * FROM County WHERE CouInt='$CountyRef'");
while($row = mysql_fetch_array($county))
{
echo $row['CouName'];
}
?>
<?php echo $row['instrument']; ?>
<?php echo $row['style']; ?>`
My problem is that everything after the second while loop is not displaying. Anyone have any suggestions?
Thanks
Second loop should say $row2. $row is being overwritten. Both variables should be named different from each other.
You can acomplish that with a one single query:
SELECT *,
(SELECT CouName FROM County WHERE CouInt=mus.CountyId) as Country
FROM Musicians mus;
You final code should looks like:
<?php
$listing = mysql_query("SELECT *,
(SELECT CouName FROM County WHERE CouInt=mus.CountyId) as Country
FROM Musicians mus;");
//This is displaying the results of the SQL query
while($row = mysql_fetch_assoc($listing))
{
echo $row['name'];
echo $row['Town'];
echo $row['Country']; //Thats all folks xD
echo $row['instrument'];
echo $row['style'];
} ?>
Saludos ;)
And that?:
while($row2 = mysql_fetch_array($county)) {
echo $row2['CouName'];
}

error in storing data to mysql however echo gives correct output

in my tableX some datas are there which looks like this
<h1>ghhhhhh!</h1>
http://twitter.com/USERNAME
<h1></h1>
http://3.bp.blogspot.com/_fqPQy3jcOwE/TJhikN8s5lI/AAAAAAAABL0/3Pbb3EAeo0k/s1600/Srishti+Rai1.html
<h1></h1>
http://4.bp.blogspot.com/_fqPQy3jcOwE/TJhiXGx1RII/AAAAAAAABLc/XNp_y51apks/s1600/anus7.html
<h1></h1>
http://cyz.com/_fqPQy3jcOwE/TJhh1ILX47I/AAAAAAAABKk/gX-OKEXtLFs/s1600/4r-2.html
<h1></h1>
http://cyz.com/_fqPQy3jcOwE/TJhiHGgb-KI/AAAAAAAABK8/zEv_41YzMhY/s1600/19+(1).html
<h1></h1>
http://cyz.com/_fqPQy3jcOwE/TJhihkpZZKI/AAAAAAAABLs/zDnlZkerBd8/s1600/Pooja+Gurung.html
when i echo the same php code it gives correct output but when i am storing these details in mysql only one row is getting stored in mysql row.
my code is this
<?php
include('connect.php');
$idmg=$_POST["id"];
$res =mysql_query("select * from tablea");
$row = mysql_fetch_array($res);
if(sus== '0'){
$output=''.$row['content'].'';
echo $output;//this output gives the above result but when i store in db it stores first row
mysql_query ("INSERT INTO tablea (content) VALUES ('$output')");
} ?>
Your insert is failing because you have unescaped data in $output. Take DCoder's advice above and use PDO or mysqli.
Is there a reason you have sql_fetch_array() and not mysql_fetch_array() ?
You also need to iterate through your results if you want more than one row.
<?php
include('connect.php');
$idmg =$_POST["id"];
$res =mysql_query("select * from tablea");
$row = sql_fetch_array($res)
if($sus== '0'){
$output=mysql_real_escape_string($row['content']);
echo $output;
mysql_query ("INSERT INTO tablea (content) VALUES ('$output')");
}
?>
And as #DCoder said, you should be using prepared statements, the code you have now is vulnerable to SQL injection.
Your code some-what corrected:
<?php
include('connect.php');
$idmg=$_POST["id"];
$res = mysql_query("select * from tablea");
$row = mysql_fetch_array($res);
if($sus== '0'){ // what is sus? If variable.. should be $sus
$output = $row['content']; // .'' is literally nothing..
echo $output;
mysql_query ("INSERT INTO tablea (content) VALUES ('$output')");
}
?>
What I think you are trying to do:
<?php
include('connect.php');
$idmg = $_POST["id"]; // not actually used
$res = mysql_query('SELECT * FROM tablea');
while($row = mysql_fetch_array($res)) {
$output = $row['content'];
echo $output;
// do anything else you want.. in your case ?enter the data back in?
mysql_query("INSERT INTO tablea(content) VALUES('$output')");
}
?>
What you should be using:
<?php
$idmg = $_POST['id']; // <-- not actually used
$res = $mysqli_connection->query('SELECT * FROM tablea');
while($row = $res->fetch_array(MYSQLI_ASSOC)) {
$output = mysqli_connection->real_escape_string($row['content']);
echo $output;
// Do whatever else you like
$mysqli_connection->query("INSERT INTO tablea(content) VALUES('$output')");
}
$res->free();
$mysqli_connection->close();
?>

Categories