Why does my code only show one post? - php

I have been developing a social network, and a key function is to be able to post on other users' profiles. However, my current code will only show one post. Also, it seems to be the first post that is shown. I have tested this by creating new accounts, and writing a test post. The code does show this first post, but if I try it again, only the first post is visible. The code is as follows:
The code to send post to database:
$person = "profile.php?id={$id}";
$post = $_POST['post'];
if($post != "")
{
$data_added = date("Y-m-d");
$added_by = $session_username;
$user_posted_to = $id;
$post = preg_replace("#[^0-9a-z]#i", "", $post);
$sqlCommand = "INSERT INTO posts VALUES ('',
'$post',
'$data_added',
'$added_by',
'$user_posted_to')";
$commandQuery = mysql_query($sqlCommand) or die ("Couldn't send post");
}
else
{
echo "You have to fill in the post form...";
}
The code to retrieve it (and display it):
$getPosts = mysql_query("SELECT *
FROM posts
WHERE user_posted_to='$id'
ORDER BY id DESC LIMIT 15") or die("Couldn't find any posts");
while($row = mysql_fetch_array($getPosts))
{
$id = $row['id'];
$body = $row['body'];
$date_added = $row['date_added'];
$added_by = $row['added_by'];
$user_posted_to = $row['user_posted_to'];
$querya = mysql_query("SELECT *
FROM members
WHERE username='$added_by' LIMIT 1");
while($row = mysql_fetch_array($querya))
{
$user_added = $row['id'];
}
$user_added = "profile.php?id={$user_added}";
}
echo "
<div>
<h3><a href='$user_added'>$added_by</a> - $date_added </h3>
<p> $body</p>
</div><br />
";
If anyone needs some more of the code, like my database connection, just comment.

In your while cicle you fill in some variables but you do not use them.
You use echo only outside the cycle, so just once, and thus you print only the values of the last istance of the while cycle.
Try
$getPosts = mysql_query("SELECT * FROM posts WHERE user_posted_to='$id' ORDER BY id DESC LIMIT 15") or die("Couldn't find any posts");
while($row = mysql_fetch_array($getPosts)){
$id = $row['id'];
$body = $row['body'];
$date_added = $row['date_added'];
$added_by = $row['added_by'];
$user_posted_to = $row['user_posted_to'];
$querya = mysql_query("SELECT * FROM members WHERE username='$added_by' LIMIT 1");
while($row = mysql_fetch_array($querya)){
$user_added = $row['id'];
}
$user_added = "profile.php?id={$user_added}";
echo "
<div><h3><a href='$user_added'>$added_by</a> - $date_added </h3><p> $body</p></div><br />";
}

Related

How to handle special characters in mysql

I have a form that users enter data in and it gets entered into a mysql database. The issue is when they have entered a "%" sign or other special characters it causes problems when my website is trying to display the record. It actually causes nothing to be shown for that record when displaying results. How do I fix this?
$query = "SELECT * FROM makerperk WHERE pid='$pid' LIMIT 1";
$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
while($row = mysqli_fetch_assoc($result)) {
$makerid = $row['makerid'];
$name = $row['name'];
$title = $row['title'];
$perkdescription = $row['perkdescription'];
$image = $row['image'];
$perktype = $row['perktype'];
$restrictions = $row['restrictions'];
}
I think you should use PHP mysqli_real_escape_string
/*Escape input variable:*/
$pid = mysqli_real_escape_string($connection, $pid);
/*Run query with escaped string:*/
$query = "SELECT * FROM makerperk WHERE pid='$pid' LIMIT 1";
$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
while($row = mysqli_fetch_assoc($result)) {
$makerid = $row['makerid'];
$name = $row['name'];
$title = $row['title'];
$perkdescription = $row['perkdescription'];
$image = $row['image'];
$perktype = $row['perktype'];
$restrictions = $row['restrictions'];
}

Php code returns empty page. tried all other solutions

I am trying to learn php. I wrote code to insert post to database and get posts to display on the home page. I wrote pagination code as well and tried to run it. but as a result php is returning an empty page with no code and no error.
Tried every thing. Went to through most of the answers here. I still can figure out the error.
<?php
$con = mysqli_connect("localhost","root","password","social") or die ("Connection was not established");
//function for getting topics
function getTopics() {
global $con;
$get_topics = "select * from topics";
$run_topics = mysqli_query($con,$get_topics);
while($row=mysqli_fetch_array($run_topics)) {
$topic_id = $row['topic_id'];
$topic_title = $row['topic_title'];
echo "<option value='$topic_id'>$topic_title</option>";
}
}
//function for insert posts to database
function insertPost() {
if(isset($_POST['sub'])) {
global $con;
$title = $_POST['title'];
$content = $_POST['content'];
$topic = $_POST['topic'];
$user = $_SESSION['user_email'];
$get_user = "SELECT * FROM users WHERE user_email = '$user'";
$run_user = mysqli_query($con,$get_user);
$row=mysqli_fetch_array($run_user);
$user_id = $row['user_id'];
$insert = "INSERT INTO posts (user_id,topic_id,post_title,post_content,post_date) VALUES ('$user_id','$topic','$title','$content',NOW())";
$run = mysqli_query($con,$insert);
if($run) {
echo "<h3>Posted to timeline. Looks great.</h3>";
$update = "Update users set posts='yes' where user_id='$user_id'";
$run_update = mysqli_query($con,$update);
}
}
}
//function to get posts
function get_posts() {
global $con;
$per_page=5;
if (isset($_GET['page'])) {
$page = $_GET['page'];
}
else {
$page=1;
}
$start_from = ($page-1)*$per_page;
$get_posts = "SELECT * FROM posts ORDER by 1 DESC LIMIT $start_from, $per_page";
$run_posts = mysqli_query($con,$get_posts);
while($row_posts=mysqli_fetch_array($run_posts)) {
$post_id = $row_posts['post_id'];
$user_id = $row_posts['user_id'];
$post_title = $row_posts['post_title'];
$content = $row_posts['post_content'];
$post_date = $row_posts['post_date'];
//gettin the user who posted the thread
$user = "SELECT * FROM users WHERE user_id='$user_id' AND posts='yes'";
$run_user = mysqli_query($con,$user);
$row_user = mysqli_fetch_array($run_user);
$user_name = $row_user['user_name'];
$user_image = $row_user['user_image'];
//displaying all at once.
echo "<div id='posts'>
<p><img src='user_images/$user_image' width='50' height='50'</p>
<h3><a href='user_profile.php?luser_id=$user_id'>$user_name</h3>
<h3>$post_title</h3>
<p>$post_date</p>
<a href='single.php?post_id=$post_id' style='float:right'><button>See replies</button></a>
</div>";
}
include("pagination.php");
}
?>
pagination code goes like this.
<?php
$query = "SELECT * FROM posts";
$result = mysqli_query($con,$query);
//count the total records
$total_posts = mysqli_num_rows($result);
//using ceil function to divide the total records per page
$total_pages = ceil($total_posts / $per_page);
//going to first page
echo "
<center>
<div id='pagination'>
<a href='welcome.php?page=1'>First Page</a>
";
for ($i=1; $i=$total_pages; $i++) {
echo "<a href='welcome.php?page=$i'>$i</a>";
}
//going to last page
echo "<a href='welcome.php?page=$total_pages'>Last Page</a></center>";
?>

Problems updating correct row in databse with php

I'm trying to create a voting system for artists played on my radio station. I'm using the source code from: http://dl.howcode.org/download/97ff383c7d4dc9939c65c9e6fab2a5dc
The problem I have found is that the votes update using the number from the first row in the database no matter which option is selected, thus if for instance the first row has 3 votes in and the user tries to vote on someone with 0 votes, it will change the votes for the correct artist to 4 instead of 1... I hope that makes sense?
The code I have is:
[EDIT] I have changed the queries to fetch assoc to make it easier to understand.
<?php
$voteID = $_GET['voteID'];
$connect = mysqli_connect('xxx', 'xxx', 'xxx', 'xxx');
$query = "SELECT * FROM listenervotes WHERE voteID='$voteID'" ;
$q = mysqli_query($connect, $query);
while($row = mysqli_fetch_assoc($q)){
$id = $row["id"];
$voteTitle = $row["voteTitle"];
$voteID = $row["voteID"];
$ipaddress = $row["ipAddress"];
echo "<h3>$voteTitle</h3>";
?>
<table>
<form action="" method="POST">
<?php
$artists = "SELECT * FROM artists WHERE voteID='$voteID'" ;
$q2 = mysqli_query($connect, $artists);
while($r = mysqli_fetch_assoc($q2)){
$artist = $r["artistName"];
$votes = $r["votes"];
$genre = $r["genre"];
$ip = $_SERVER['REMOTE_ADDR'];
$newIpAddress = $ipaddress."$ip, ";
$newVotes = $votes + 1;
if (isset($_POST['vote'])) {
$voteOption = $_POST['voteOption'];
if ($voteOption == ""){
die("You haven't selected anyone!");
}else{
$ipaddressE = explode(",", $ipaddress);
if(in_array($ip, $ipaddressE)){
die("You have already voted!");
}else{
mysqli_query($connect, "UPDATE artists SET votes='$newVotes' WHERE voteID='$voteID' AND artistName='$voteOption'");
mysqli_query($connect, "UPDATE listenervotes SET ipaddress='$newIpAddress' WHERE voteID='$voteID'");
die('You voted successfully!<br><tr><td>'.$artist.'</td><td>'.$genre.'</td><td>'.$votes.' Votes</td></tr>');
}
}
}
echo '<tr><td>'.$artist.'</td><td>'.$genre.'</td><td><input type="radio" name="voteOption" value="'.$artist.'"</td></tr>';
}
}
?>
I could be missing something obvious, in my mind I'm thinking that I somehow need to iterate through the rows before setting the new value, if so, how and where?
It looks like you are always looping over all rows and updating the relevant row with the first value found. Adding a check on the ID should do:
<?php
$voteID = $_GET['voteID'];
$connect = mysqli_connect('xxx', 'xxx', 'xxx', 'xxx');
$query = "SELECT * FROM listenervotes WHERE voteID='$voteID'" ;
$q = mysqli_query($connect, $query);
while($row = mysqli_fetch_assoc($q)){
$id = $row["id"];
$voteTitle = $row["voteTitle"];
$voteID = $row["voteID"];
$ipaddress = $row["ipAddress"];
echo "<h3>$voteTitle</h3>";
?>
<table>
<form action="" method="POST">
<?php
$artists = "SELECT * FROM artists WHERE voteID='$voteID'" ;
$q2 = mysqli_query($connect, $artists);
while($r = mysqli_fetch_assoc($q2)){
$artist = $r["artistName"];
$votes = $r["votes"];
$genre = $r["genre"];
$ip = $_SERVER['REMOTE_ADDR'];
$newIpAddress = $ipaddress."$ip, ";
$newVotes = $votes + 1;
if (isset($_POST['vote'])) {
$voteOption = $_POST['voteOption'];
if ($voteOption == ""){
die("You haven't selected anyone!");
}else{
$ipaddressE = explode(",", $ipaddress);
if(in_array($ip, $ipaddressE)){
die("You have already voted!");
}elseif ($voteOption === $artist) { // Don't run UPDATE when we're on the wrong row.
mysqli_query($connect, "UPDATE artists SET votes='$newVotes' WHERE voteID='$voteID' AND artistName='$voteOption'");
mysqli_query($connect, "UPDATE listenervotes SET ipaddress='$newIpAddress' WHERE voteID='$voteID'");
die('You voted successfully!<br><tr><td>'.$artist.'</td><td>'.$genre.'</td><td>'.$votes.' Votes</td></tr>');
}
}
}
echo '<tr><td>'.$artist.'</td><td>'.$genre.'</td><td><input type="radio" name="voteOption" value="'.$artist.'"</td></tr>';
}
}
?>

Not picking the right ID from the database

I am trying to build a CMS system where an admin inserts data in a template. There can be as many pages created with that template as the admin wants. The pages should then be accessed in a menu with links and be displayed with the respective data according the link you just clicked.
Everything is working as expected except the system is not picking up the data from the id that the link had. Instead the system is picking up the data from the last id on the database.
Example: If I click on the link Page#2, I will have the URL http://www.website/page.php?pid=2 but the content that is loaded is the content from the last id on the database and not the 2.
Code to make and display the links:
if (!$_GET['pid']) {
$pageid = '1';
} else {
$pageid = preg_replace('/[^0-9]/', "", $_GET['pid']); // filter everything but numbers for security
}
$sqlCommand = "SELECT id, linklabel FROM pages WHERE showing='1' ORDER BY id ASC";
$query = mysqli_query($myConnection, $sqlCommand) or die('Error: ' . mysqli_error($myConnection));
$listadeavatars = '';
while ($row = mysqli_fetch_array($query)) {
$pid = $row["id"];
$avatar = html_entity_decode($row["linklabel"]);
}
$sqlCommand = "SELECT id, linklabel FROM pages WHERE showing='1' ORDER BY id ASC";
$query = mysqli_query($myConnection, $sqlCommand) or die (mysqli_error());
$menuDisplay = '';
while ($row = mysqli_fetch_array($query)) {
$pid = $row["id"];
$linklabel = $row["linklabel"];
$avatar = html_entity_decode($row["linklabel"]);
$menuDisplay .= '<li>' . $avatar . '</li>';
}
mysqli_free_result($query);
Code to display the data on page.php according to the ID
if (!$_GET['pid']) {
$pageid = '1';
} else {
$pageid = ereg_replace("[^0-9]", "", $_GET['pid']); // filter everything but numbers for security
}
$sqlCommand = "SELECT pagetitle, linklabel, evenemang, presentation, producent, pagebody, mapa FROM pages WHERE id='$pid' LIMIT 1";
$query = mysqli_query($myConnection, $sqlCommand) or die (mysqli_error());
while ($row = mysqli_fetch_array($query)) {
$pagetitle = $row["pagetitle"];
$linklabel = $row["linklabel"];
$evenemang = $row["evenemang"];
$presentation = $row["presentation"];
$producent = $row["producent"];
$pagebody = $row["pagebody"];
$mapa = $row["mapa"];
$avatar = html_entity_decode($row["linklabel"]);
}
mysqli_free_result($query);
Please do let me know if I need to explain better! Any suggestions to solve this issue? Cheers!
On page.php, change WHERE id='$pid'
$sqlCommand = "SELECT pagetitle, linklabel, evenemang, presentation, producent, pagebody, mapa FROM pages WHERE id='$pid' LIMIT 1";
to WHERE id='$pageid'
$sqlCommand = "SELECT pagetitle, linklabel, evenemang, presentation, producent, pagebody, mapa FROM pages WHERE id='$pageid' LIMIT 1";

Undefined variable, unsure why

<?php
$tid = $_GET['tid'];
$id = $_SESSION['userid'];
$sql1 = "SELECT * FROM topics WHERE id='$tid' LIMIT 1";
$res1 = mysqli_query($connect, $sql1) or die(mysqli_error($connect));
while ($row = mysqli_fetch_array($res1, MYSQLI_ASSOC)) {
$title = $row['topic_title'];
$creator = $row['topic_creator'];
}
$sql = "SELECT * FROM users WHERE id='$creator' LIMIT 1";
$user_query = mysqli_query($connect, $sql) or die(mysqli_error($connect));
while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$name = $row["first"].$row["last"];
}
echo $name;
?>
I'm a little new to PHP, but I've done things exactly like this, but this time I'm getting an error. Everything here works except for $name. I checked my SQL tables and made sure users exist and that there's first and a last area. I don't see what else could be wrong.
Notice: Undefined variable: name in * on line **
Thank you.
Try this code on for size:
<?php
$tid = $_GET['tid'];
$id = $_SESSION['userid'];
$tid = mysqli_escape_string($connect, $tid);
$sql1 = "SELECT * FROM topics WHERE id='{$tid}' LIMIT 1";
$res1 = mysqli_query($connect, $sql1) or die(mysqli_error($connect));
// Check for rows first.
if($res1 and mysqli_num_rows($res1)){
// Use if as while is pointless on LIMIT 1
if($row = mysqli_fetch_array($res1, MYSQLI_ASSOC)) {
$title = $row['topic_title'];
$creator = $row['topic_creator'];
$creator = mysqli_escape_string($connect, $creator);
$sql = "SELECT * FROM users WHERE id='{$creator}' LIMIT 1";
$user_query = mysqli_query($connect, $sql) or die(mysqli_error($connect));
// Check for rows first.
if($user_query and mysqli_num_rows($user_query)){
// Use if as while is pointless on LIMIT 1
if ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$name = $row["first"].$row["last"]; // NO HIT!
}
echo $name;
}else{
echo 'no rows found (query 2).';
}
}
}else{
echo 'no rows found (query 1).';
}
?>
Variable $name is undefined because the $name = ...; line is not reached. So make sure you $sql query actually returns results. It has to in order to define $name.

Categories