PHP PDO check if data exists not working properly - php

I am working on my blog and I can't seem to figure this out. The if ($result->fetchColumn()) should be working. It does give the error but when data(row) exists it does not show anything. What is wrong?
<?php
$id = $_GET["id"];
$sql = "SELECT * FROM `posts` WHERE `id` = $id";
$result = $conn->query($sql);
if ($result->fetchColumn() > 0) {
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo '<div class="post-preview">
<a>
<h2 class="post-title">
'.$row["title"].'
</h2>
<h3 class="post-subtitle">
'.$row["content"].'
</h3>
</a>
<p class="post-meta">'.$row["creator"].' | '.$row["date"].'</p>
</div>
<hr>';
}
}
else {
echo "<center><h1>Post does not exist.</h1></center>";
header("Refresh: 2; url=index.php");
}
?>
Whenever I remove the line if ($result->fetchColumn() > 0) { it works fine. But I need to check if the $id exists in the database. If it does, it should show the data, if not it should show the error and link back to index.php.

Your code could be much simpler
Just populate your $row variable and see whether it contains anything or not.
<?php
$stmt = $conn->prepare("SELECT * FROM `posts` WHERE `id` = ?");
$stmt->execute([$_GET["id"]]); // essential to protect from SQL injection!
$row = $stmt->fetch(PDO::FETCH_ASSOC)
if ($row) {
echo '<div class="post-preview">
<a>
<h2 class="post-title">
'.$row["title"].'
</h2>
<h3 class="post-subtitle">
'.$row["content"].'
</h3>
</a>
<p class="post-meta">'.$row["creator"].' | '.$row["date"].'</p>
</div>
<hr>';
}
else {
echo "<center><h1>Post does not exist.</h1></center>";
header("Refresh: 2; url=index.php");
}

Related

Liking system, how do I fix it?

I have the following script for showing posts and liking them, but if I like one post it likes all the posts on the page, I can't think of another way to do it, can anyone give me some advice?
<?php
if ($sort == 1){
$result = $conn->query("SELECT * FROM posts ORDER BY date DESC LIMIT 4 ");
}
elseif($sort == 2)
{
$result = $conn->query("SELECT * FROM posts WHERE date > NOW() - INTERVAL 24 HOUR ORDER BY likes DESC");
}
elseif($sort == 3)
{
$result = $conn->query("SELECT * FROM posts ORDER BY likes DESC");
}
if ($result->num_rows > 0) :
while($row = mysqli_fetch_assoc($result)) : ?>
<div class="card mb-4">
<img class="card-img-top" src="<?php echo $row['image1'] ?>" alt="Card image cap">
<div class="card-body">
<h2 class="card-title"><?php print title; ?></h2>
<p class="card-text"><?php print text; ?></p>
Read More →
</div>
<div class="card-footer text-muted">
Posted on <?php print $row['date'] ?> by
<?php print $row['author']; ?>
<?php
$id=$row['id'];
if($_POST['like']) {
$update = "UPDATE posts set `likes` = `likes`+1 where `id` ='$id'";
if ($conn->query($update) === TRUE) {
} else {
echo "Error updating record: " . $conn->error;
}
} ?>
<form action="" method="POST">
<button type = "submit" value = "like" name='like'style="font-size:24px"><?php echo $row['likes']; ?><i class="fa fa-thumbs-o-up"></i>
</form>
</div>
</div>
<?php endwhile; endif; ?>
Your while loop contains the update query so your code should be change like this.
in order to get the id to like you just need to use a hidden field to post that id like in this code
<?php
if($_POST['like']) {
$id=$POST['id'];
$update = "UPDATE posts set `likes` = `likes`+1 where `id` ='$id'";
if ($conn->query($update) === TRUE) {
} else {
echo "Error updating record: " . $conn->error;
}
} ?>
<?php
if ($sort == 1){
$result = $conn->query("SELECT * FROM posts ORDER BY date DESC LIMIT 4 ");
}
elseif($sort == 2)
{
$result = $conn->query("SELECT * FROM posts WHERE date > NOW() - INTERVAL 24 HOUR ORDER BY likes DESC");
}
elseif($sort == 3)
{
$result = $conn->query("SELECT * FROM posts ORDER BY likes DESC");
}
if ($result->num_rows > 0) :
while($row = mysqli_fetch_assoc($result)) : ?>
<div class="card mb-4">
<img class="card-img-top" src="<?php echo $row['image1'] ?>" alt="Card image cap">
<div class="card-body">
<h2 class="card-title"><?php print title; ?></h2>
<p class="card-text"><?php print text; ?></p>
Read More →
</div>
<div class="card-footer text-muted">
Posted on <?php print $row['date'] ?> by
<?php print $row['author']; ?>
<form action="" method="POST">
<input name="id" type="hidden" value="<?php echo $row['id']; ?>">
<button type = "submit" value = "like" name='like'style="font-size:24px"><?php echo $row['likes']; ?><i class="fa fa-thumbs-o-up"></i>
</form>
</div>
</div>
<?php endwhile; endif; ?>

Pagination script added php page isn't loading or showing any error

I tried to add a pagination script to my existing php page of sql queries.
But after adding the script the page is kept on loading without showing any content or error.
My code goes as:
<?php include('db.php'); ?>
<?php // define how many results you want per page
$results_per_page = 10;
// find out the number of results stored in database
$sql10='SELECT * FROM smf_messages';
$result10 = mysqli_query($conn, $sql10);
$number_of_results = mysqli_num_rows($result10);
// determine number of total pages available
$number_of_pages = ceil($number_of_results/$results_per_page);
// determine which page number visitor is currently on
if (!isset($_GET['page'])) {
$page = 1;
} else {
$page = $_GET['page'];
}
// determine the sql LIMIT starting number for the results on the displaying page
$this_page_first_result = ($page-1)*$results_per_page;
?>
Now the sql query codes to get the data from the respective tables...
<?php
$sql2 = "SELECT * FROM smf_log_digest WHERE note_type = 'topic' ORDER BY id_msg DESC LIMIT 420";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
while($row2 = $result2->fetch_assoc()) {
$number = $row2["id_msg"];
?>
This query relates to the content from which table to be retrieved..
<?php
// retrieve selected results from database and display them on page
$sql20='SELECT * FROM smf_messages WHERE id_msg = $number AND id_board = 4 LIMIT ' . $this_page_first_result . ',' . $results_per_page;
$result20 = mysqli_query($conn, $sql20);
while($row20 = mysqli_fetch_array($result20)) {
$member = $row20["id_member"];
$replies = $row20["id_topic"];
?>
<?php
$sqlstep1 = "SELECT COUNT(*) AS total FROM smf_log_digest WHERE note_type = 'reply' AND id_topic = $replies";
$rowNumstep1 = mysqli_query($conn, $sqlstep1);
$countstep1 = mysqli_fetch_assoc($rowNumstep1);
?>
// Body
<article class="well btn-group-sm clearfix">
<div class="topic-desc row-fluid clearfix">
<div class="col-sm-2 text-center publisher-wrap">
<img src="assets/images/profile.png" alt="" class="avatar img-circle img-responsive">
<h5><?php echo $row3["poster_name"]; ?></h5>
<small class="online">Member</small>
</div>
<div class="col-sm-10">
<header class="topic-footer clearfix">
<!-- end tags -->
</header>
<!-- end topic -->
<h4> <?php echo $row20["body"]; ?></h4>
<div class="blog-meta clearfix">
<small><?php echo $countstep1["total"]; ?> Replies</small>
<small><?php echo date('m/d/Y', $row20["poster_time"]); ?></small>
</div>
View the topic →
</div>
</div>
</article>
//end of body
<?php
}
// display the links to the pages
for ($page=1;$page<=$number_of_pages;$page++) {
echo '' . $page . ' ';
}
?>
<?php }
} else {
echo "";
}
?>
Please note that the data base connections are all checked and are right..
Any help is appreciated..
add this on top then check for error.
error_reporting(E_ALL);
ini_set('desplay_errors','1');

Variable for $_GET array not returning any values

I can't seem to return any values on my $_GET array.
It works fine when e.g.
$sql = "SELECT * FROM review WHERE brand='brandx'" but when I change it to brand='$id' in line 5, nothing gets passed.
The fetch array in my index.php works perfectly fine however when it gets href to brand.php (as shown below), I lose my marbles.
<?php
if(isset($_GET["id"])){
include "php_includes/db_conx.php";
$id = preg_replace('#[^0-9]#i', '', $_GET["id"]);
$sql = "SELECT * FROM review WHERE brand='$id'";
$query = mysqli_query($db_conx, $sql);
$productList = "";
// Now make sure that brand exists in the table
$productCount = mysqli_num_rows($query);// count the output amount
if($productCount > 0){
//get the products off the selected brand
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$username = $row['username'];
$productname = $row['productname'];
$comment = $row['comment'];
$rating = $row['rating'];
$date = $row['date'];
$productList .=
'
<div class="wrapper">
<div class="brand-and-name">
<div class="brand">
<a href="brand.php?id='.$id.'">
<span>'.$id.'</span>
</a>
</div>
<div class="prod-name">
'.$productname.'
</div>
</div>
<div class="prod-container" id="pd1">
<div class="prod-img"><img src="https://giovanniphotography.files.wordpress.com/2011/09/creativemevid19.jpg" /></div>
<div class="comment">
<b>My Score: '.$rating.'/10</b>
<br /><br />
<p>'.$comment.'</p>
</div>
<div class="profile">
<div class="profile-thumb" id="pt1"></div>
<div class="name" id="nm1">
'.$username.'<br />'.$date.'
</div>
</div>
<div class="social-share-1">
<div class="like-btn"></div>
<div class="comment-btn"></div>
<div class="wishlist-btn">+ wishlist</div>
</div>
</div><!--end .prod-container#pd1-->
</div><!--wrPer-->
';
}
}else{
echo "Product doesnt exist";
exit ();
}
}else{
echo "You got to pick a brand man!";
exit ();
}
?>
Does this code work, after your preg_replace? If not you may not have magic quotes enabled in php.ini. I notice in the rest of your output you are concatenating strings and variables.
print "ID: $id";
use a prepared statement and dont hassle with sanitizing of user input:
if($stmt = $db_conx->prepare("SELECT username, productname, comment, rating, date FROM review WHERE brand=?)")
{
$stmt->bind_value('s', $_GET["id"]);
$result = $stmt-execute();
$stmt->bind_result($username, $productname, $comment, $rating, $date ); //bind result to vars
//now you can loop through your result:
while($stmt->fetch()) {
//use $username, $productname, $comment, $rating, $date etc to work with your values
}
}

PHP and MySQL dynamic query only returns results without where clause

I am hoping someone can assist with a dynamic query in PHP. The first page below is a page which displays a number of items from MySQL. Once an item is clicked on it goes to another page which queries the database to bring up the selected product details. The page displaying the items a user can select from works fine, but the page displaying the item clicked on only works if I remove the WHERE clause, but of course it is no longer dynamic then. The error statement is suggesting that the syntax is not right for the version, yet it works on the other page. Using MySQL 5.6.17 and PHP 5.5.12.
Can anyone see where it is that I have gone wrong here please?
---------------------------------
Main Page (functions as expected)
<?php
ini_set('display_errors', '0');
$message = '';
$db=new MySQLi('localhost', 'someone', 'xxx','abc');
if ($db->connect_error) {
$message = $db->connect_error;
} else {
$sql = 'SELECT * FROM items';
$result = $db->query($sql);
if ($db->error) {
$message = $db->error;
}
}
?>
<!--other parts of the site--->
<?php if ($message) { ?>
<h2 class="inline_block">Sorry, there seems to be a problem.</h2>
<?php } else { ?>
<div>
<?php
$i = 0;
while ($row = $result->fetch_assoc()) {
if ($i % 4 === 0) { ?>
<div>
<ul>
<?php } ?>
<li> <a href="includes/details.php?id=<?php echo $row['itemID']; ?>"> <img src="img/<?php echo $row['image']; ?>" alt="<?php echo $row['alt']; ?>" height="150" width="150">
<p><?php echo $row['product']; ?></p>
<p class="reset">From $<?php echo $row['water']; ?></p></a> </li>
<?php $i++;
if ($i % 4 === 0) { ?>
</ul>
</div>
<?php } // end if
} // end of loop ?>
</div>
</div>
<?php } // end of page ?>
</div>
<!--other parts of the site--->
-----------------------------------------------------------------
Dynamic Page (returns an SQL error "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1". Line 1 is the same first line as showing below. This is also used in the previous page without issue. When the WHERE clause is removed from the SQL query it works but is no longer dynamic. )
<?php
ini_set('display_errors', '0');
$message = '';
$db=new MySQLi('localhost', 'someone', 'xxx','abc');
if ($db->connect_error) {
$message = $db->connect_error;
} else {
$sql = 'SELECT * FROM items WHERE xitemID=' . $db->real_escape_string($_GET['xitemID']);
$result = $db->query($sql);
if ($db->error) {
$message = $db->error;
} else {
$row = $result->fetch_assoc();
}
}
?>
<!--other parts of the site--->
<ul>
<li>Home</li>
<li>Things</li>
<li>Mixeda</li>
<li><?php echo $row['product']; ?></li>
</ul>
</div>
<div id="col_1" role="main">
<?php if ($message) { ?>
<p> ERROR</p>
<?php echo "<p>$message</p>";
} else { ?>
<h2 class="inline_block"><?php echo $row['product']; ?></h2>
<p class="figure"><img src="../img/<?php echo $row['image']; ?>" alt="<?php echo $row['alt']; ?>" width="200" height="200">Price from $<?php echo $row['product']; ?></p>
</div>
<div id="col_2">
<h3>Details</h3>
<p><?php echo $row['details']; ?></p>
</div>
<?php } ?>
<!--other parts of the site--->
Note you need to put single quotes around the item in xitemID='itemHere':
$sql = "SELECT * FROM items WHERE xitemID='" . $db->real_escape_string($_GET['xitemID']) . "'";
That should fix your problem as long as $_GET['xitemID'] is defined.
You are concatenating an escaped
value outside your string.
$sql = 'SELECT * FROM items WHERE xitemID=' .
$db->real_escape_string($_GET['xitemID']);
This looks like a valid action however when xitemID is a character value, you still need to enclose it in quotes yourself.
Better is to use a prepared statement:
You are using MySQLi already, so:
$sql="SELECT * FROM items WHERE xitemID=?";
$pstmt=$db->prepare_statement($sql);
$pstmt->bind_param("s",$_GET['xitemID']);
$results=$pstmt->execute();
That way php takes care of any quoting etc and prevents eventual sql injection.

Recommended user video Like youtube

I am trying to make a youtube like main page. With the code below I want to make videos that are recommended for my users.
The following code shows only a user's video.
<?php $query = "SELECT
user.uid,
user.user_name,
user.user_avatar,
user_posts.uid_dk,
user_posts.post_id,
user_posts.post_name,
user_posts.post_info,
user_posts.post_time,
user_posts.post_ext,
user_posts.post_num,
user_posts.post_views
FROM user
JOIN user_posts
ON user_posts.uid_dk = user.uid
WHERE user_name='$user_name' LIMIT 5";
$run_query = mysql_query($query);
while($data=mysql_fetch_assoc($run_query)){
$post_name=$data['post_name'];
$post_time = $data['post_time'];
$post_views = $data['post_views'];
$post_numid = $data['post_num'];
$post_id = $data['post_id'];
$user_name = $data['user_name'];
$user_avatar = $data['user_avatar'];
?>
<div class="onerilent"><img src="<?php echo $user_avatar;?>"><?php echo $user_name ;?> Recommended for you</div>
<div class="onmnwrp">
<div class="onmn">
<div class="onmn_img"><img src="<?php echo $base_url.'user_uploads/'.$post_num;?>.png"></div>
<div class="onmg_tit"><?php echo $post_name;?></div>
<div class="onm_snm">gönderen: <?php echo $user_name;?></div>
<div class="onm_tim"><?php echo $post_views;?> views</div>
</div>
</div>
<?php } ?>
I want to show this section only one time.
<div class="onerilent"><img src="<?php echo $user_avatar;?>"><?php echo $user_name ;?> Recommended for you</div>
Anyone can help me in this regard ?
The easiest way would be with a counter, like this:
<?php
$query = "SELECT
user.uid,
user.user_name,
user.user_avatar,
user_posts.uid_dk,
user_posts.post_id,
user_posts.post_name,
user_posts.post_info,
user_posts.post_time,
user_posts.post_ext,
user_posts.post_num,
user_posts.post_views
FROM user
JOIN user_posts
ON user_posts.uid_dk = user.uid
WHERE user_name='$user_name' LIMIT 5";
$run_query = mysql_query($query);
$counter = 1;
while($data=mysql_fetch_assoc($run_query)){
$post_name=$data['post_name'];
$post_time = $data['post_time'];
$post_views = $data['post_views'];
$post_numid = $data['post_num'];
$post_id = $data['post_id'];
$user_name = $data['user_name'];
$user_avatar = $data['user_avatar'];
if($counter == 1){
$counter++;
echo '<div class="onerilent"><img src="'.$user_avatar.'">'.$user_name.' Recommended for you</div>';
}
?>
<div class="onmnwrp">
<div class="onmn">
<div class="onmn_img"><img src="<?php echo $base_url.'user_uploads/'.$post_num;?>.png"></div>
<div class="onmg_tit"><?php echo $post_name;?></div>
<div class="onm_snm">gönderen: <?php echo $user_name;?></div>
<div class="onm_tim"><?php echo $post_views;?> views</div>
</div>
</div>
<?php
}
?>
note the $counter variable is set to 1 before the loop, and inside the loop there is a condition to check if it is set to the value 1, and if it is, then it echo's your html and increments the $counter, so that it is no longer set to 1

Categories