The problem is I think in function viewNews(), so I made that function to get the articles/news from database. Well, I tried to put function showCommentsArea() inside viewNews() function, but it shows me same comments in every article, I want like separated comments for every article, like on Facebook, I mean, when you enter someone's post (in this case article), you can publish a comment only for that post (article).
I tried putting showCommentsArea() function inside viewNews() function, right after displaying timestamp of that article.
# Function for viewing news. #
function viewNews()
{
global $db;
$query = "SELECT * FROM newsmodule ORDER BY timestamp";
$result = #mysqli_query($db, $query);
if (!$result)
{
echo "Error selecting headline from database.";
exit();
}
if (mysqli_num_rows($result) > 0)
{
echo "<div style='margin-left: 0; width: 100%;' class='jumbotron'>";
while ($row = mysqli_fetch_object($result))
{
echo "<h1><br>" . $row->headline . "</h1>";
echo "<hr>";
echo "<p>" . $row->storyline . "</p>";
echo "<hr>";
echo "<h5 class='pull-right'>" . $row->username . "</h5>";
echo "<p>" . $row->timestamp . "</p>";
echo "<hr>";
echo showCommentArea();
echo "<a data-target='#postComment' class='text-white dropdown-toggle btn btn-danger' data-toggle='modal' type='button'>";
echo "Publish a Comment";
echo "</a>";
}
echo "</div>";
}
else
{
echo "No headlines in database.";
}
}
function showCommentArea()
{
global $db, $errors, $username;
if(count($errors) == 0)
{
$query = "SELECT comment, name FROM comments
JOIN newsmodule ON comments.articlecID=newsmodule.id WHERE newsmodule.id=comments.articlecID";
$result = #mysqli_query($db, $query);
if(!$result)
{
echo "SQL Query ERROR: !ERR_SQL_QUERY_01";
exit();
}
if (mysqli_num_rows($result) > 0) {
echo "<div>";
echo "<h4>";
echo "Comments:";
echo "</h4>";
echo "<br>";
while ($row = mysqli_fetch_object($result)) {
echo "<p class='text-danger' style='font-weight: bold;'>" . $row->name . "</p>";
echo "<p>" . $row->comment . "</p>";
}
echo "</div>";
}
}
}
So, I expect to have one individual comments section for one individual post, you see I tried to add it with JOINING tables, but it shows me entire table 'comments'
Problem is while loop always showing last inserted row result. I've tried this below code to follow/unfollow button option. For example I'm a user id=1. I have already followed user id=4. Now, I want to follow user id=5. When i click follow button(id=5) it turns into Unfollow properly. But, I have already followed user id=4. That turns into Follow. This is my problem.
Then I tried echo $following;. it Prints 5555. That means last inserted data. But I want 45. I'm sure I've made a mistake in my while loop. But I don't know what I should change?
<?php
try
{
$stmt = $conn->prepare("SELECT * FROM users ORDER BY Autoid");
$stmt->errorInfo();
$stmt->execute();
$sth = $conn->prepare("SELECT * FROM followers ORDER BY Autoid");
$sth->errorInfo();
$sth->execute();
while($follow_row = $sth->fetch(PDO::FETCH_ASSOC))
{
$following = $follow_row['Following'];
$follower = $follow_row['Follower'];
}
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo "<tr>";
echo "<td>". $row['Autoid'] ."</td>";
echo "<td>". $row['Name'] ."</td>";
// echo $row['Following'];
if($_SESSION['sesuname'] == $row['Username'])
{
echo "<td class='itsyou' >Its You ". $_SESSION['sesuname'] ."</td>";
}
else
{
if(($follower == $_SESSION['sesid']) AND ($following != $row['Autoid']))
{
//echo "<td>true</td>";
echo $following;
echo "<td>";
echo "<form id='jsform' method='post' action='subscribe.php'>";
echo "<input type='hidden' name='id' value=" . $row['Autoid'] . " />";
echo "<button class='follow' >Follow</button>";
echo "</form>";
echo "</td>";
}
else
{
//echo "<td>false</td>";
echo "<td>";
echo "<form id='ufform' method='post' action='unsubscribe.php'>";
echo "<input type='hidden' name='uid' value=" . $row['Autoid'] . " />";
echo "<button class='follow' >UnFollow</button>";
echo "</form>";
echo "</td>";
}
}
echo "</tr>";
}
} catch (PDOException $e) {
'Database Error : ' .$e->getMessage();
}
?>
This code:
while($follow_row = $sth->fetch(PDO::FETCH_ASSOC))
{
$following = $follow_row['Following'];
$follower = $follow_row['Follower'];
}
Simply OVERWRITES $following and $follower every time you fetch a row, leaving you with the LAST row fetched in the variables. Perhaps you want something more like
$following[] = $follow_row['Following'];
$follower[] = $follow_row['Follower'];
^^--- append new row value to an array.
Below is the code from catalog page with the data which has to be inserted to the database. It has some problem and i cant insert that data to the database table, and i think i have not ported variables correctly.
My catalogue page has this code (it is for purchasing photographs):
while ($row=mysql_fetch_assoc($result))
{
echo "<tr><td width=100><img src=".$row['FilePath']." /></td>";
echo "<td width=100 padding=25>".$row['Title']."</td>"; $hour = time() + 3600; setcookie('titlecookie', $row['Title'], $hour);
echo "<td width=100 padding=25>".$row['Cost']."</td>";
echo "<td width=100>".$row['FileSize']."</td>";
echo "<td width=100>".$row['CaptureDate']."</td>";
echo "<td width=100>".$row['Resolution']."</td>";
echo "<td width=100><input type=checkbox name=checked[] value=select />Purchase</td></tr>";
}
echo "</table><input type=submit name=submit value=Purchase></form></center>";
}
else
{
echo "Query not successful";
}
The code for my purchase page appears as follows:
$username = "COOKIE['ID_my_site']";
$title = "COOKIE['titlecookie']";
$Custid = mysql_query("SELECT Custid from Customer Where Username=$username");
$Money = $_POST['Cost'];
$Photoid = mysql_query("SELECT Photoid from Photograph Where Title = $row[Title]");
foreach ($_POST['checked'] as $select) {
if(mysql_query('INSERT INTO Transaction (Money, Custid)
VALUES ($Money, $Custid)'))
{
echo "successfully added to Transaction";
}
else
{
echo "Problems adding data to Transaction";
}
if(mysql_query("INSERT INTO TransPhoto (Photoid, Transid)
VALUES ('$Photoid', '$Transid')"))
{
echo "successfully added to Transphoto";
}
else
{
echo "Problems adding data to Transphoto";
}
}
Could you possible assist me with fixing this code? I am relatively new to this but have searched and could not find an effective solution. Thanks
I have a Reports page with 2 tables, one show items in stock the other shows Items sold.
I made a delete option for them which provides a button at the right end side of the table to delete rows out of my table.
The Issue that I am having is that the Code works perfectly for the 1st table but for the second table, the code will execute but the data does not get deleted from the DB.
I think what is happening is that due to me using the same Code to delete from both tables, that only 1 works. ( I think I am not sure)
After looking at it for a while trying to find potential errors I made and trying to see what else might be the issue, I decided to ask u for help!
Here the code:
<?php
$config['conn'] = array(
'host' => 'localhost',
'username' => 'root',
'password' => '',
'dbname' => 'inventarisdb'
);
$conn = new PDO('mysql:host=' . $config['conn']['host'] . ';dbname=' . $config['conn']['dbname'], $config['conn']['username'], $config['conn']['password']);
$action = isset($_GET['action']) ? $_GET['action']: "";
if($action=='delete'){ //if the user clicked ok, run our delete query
try {
$query = "DELETE FROM BCD WHERE id = ?";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $_GET['id']);
$result = $stmt->execute();
echo "<div>Record was deleted.</div>";
}catch(PDOException $exception){ //to handle error
echo "Error: " . $exception->getMessage();
}
}
//select all data
$query = "SELECT ID, Categorie, SerieNummer, MacAdress, ProductCode, Prijs, RekNummer, PaletNummer, Hoeveelheid, Aantekeningen FROM BCD";
$stmt = $conn->prepare( $query );
$stmt->execute();
//this is how to get number of rows returned
$num = $stmt->rowCount();
if($num>0){ //check if more than 0 record found
echo "<table border='1'>";//start table
//creating our table heading
echo "<tr>";
echo "<th>Categorie</th>";
echo "<th>SerieNummer</th>";
echo "<th>MacAdress</th>";
echo "<th>ProductCode</th>";
echo "<th>Prijs</th>";
echo "<th>RekNummer</th>";
echo "<th>PaletNummer</th>";
echo "<th>Hoeveelheid</th>";
echo "<th>Aantekeningen</th>";
echo "</tr>";
//retrieve our table contents
//fetch() is faster than fetchAll()
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
//extract row
//this will make $row['firstname'] to
//just $firstname only
extract($row);
//creating new table row per record
echo "<tr>";
echo "<td>{$Categorie}</td>";
echo "<td>{$SerieNummer}</td>";
echo "<td>{$MacAdress}</td>";
echo "<td>{$ProductCode}</td>";
echo "<td>{$Prijs}</td>";
echo "<td>{$RekNummer}</td>";
echo "<td>{$PaletNummer}</td>";
echo "<td>{$Hoeveelheid}</td>";
echo "<td>{$Aantekeningen}</td>";
echo "<td>";
//we will use this links on next part of this post
echo "<a href='#' onclick='delete_user( {$ID} );'>Delete</a>";
echo "</td>";
echo "</tr>";
}
echo "</table>";//end table
}else{ //if no records found
echo "No records found.";
}
?>
<script type='text/javascript'>
function delete_user( id ){
var answer = confirm('Are you sure?');
if ( answer ){ //if user clicked ok
//redirect to url with action as delete and id to the record to be deleted
window.location = 'Remove.php?action=delete&id=' + id;
}
}
</script>
<br/><br/><br/><br/><br/><br/><br/><br/><br/>
<?php
$config['conn'] = array(
'host' => 'localhost',
'username' => 'root',
'password' => '',
'dbname' => 'inventarisdb2'
);
$conn = new PDO('mysql:host=' . $config['conn']['host'] . ';dbname=' . $config['conn']['dbname'], $config['conn']['username'], $config['conn']['password']);
$action = isset($_GET['action']) ? $_GET['action']: "";
if($action=='delete'){ //if the user clicked ok, run our delete query
try {
$query = "DELETE FROM CDE WHERE id = ?";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $_GET['id']);
$result = $stmt->execute();
echo "<div>Record was deleted.</div>";
}catch(PDOException $exception){ //to handle error
echo "Error: " . $exception->getMessage();
}
}
//select all data
$query = "SELECT ID2, Klant, Categorie1, SerieNummer1, MacAdress1, ProductCode1, Prijs1, Hoeveelheid1, Aantekeningen1 FROM CDE";
$stmt = $conn->prepare( $query );
$stmt->execute();
//this is how to get number of rows returned
$num = $stmt->rowCount();
if($num>0){ //check if more than 0 record found
echo "<table border='1'>";//start table
//creating our table heading
echo "<tr>";
echo "<th>Klant</th>";
echo "<th>Categorie1</th>";
echo "<th>SerieNummer1</th>";
echo "<th>MacAdress1</th>";
echo "<th>ProductCode1</th>";
echo "<th>Prijs1</th>";
echo "<th>Hoeveelheid1</th>";
echo "<th>Aantekeningen1</th>";
echo "</tr>";
//retrieve our table contents
//fetch() is faster than fetchAll()
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
//extract row
//this will make $row['firstname'] to
//just $firstname only
extract($row);
//creating new table row per record
echo "<tr>";
echo "<td>{$Klant}</td>";
echo "<td>{$Categorie1}</td>";
echo "<td>{$SerieNummer1}</td>";
echo "<td>{$MacAdress1}</td>";
echo "<td>{$ProductCode1}</td>";
echo "<td>{$Prijs1}</td>";
echo "<td>{$Hoeveelheid1}</td>";
echo "<td>{$Aantekeningen1}</td>";
echo "<td>";
//we will use this links on next part of this post
echo "<a href='#' onclick='delete_user( {$ID2} );'>Delete</a>";
echo "</td>";
echo "</tr>";
}
echo "</table>";//end table
}else{ //if no records found
echo "No records found.";
}
?>
<script type='text/javascript'>
function delete_user( id ){
var answer = confirm('Are you sure?');
if ( answer ){ //if user clicked ok
//redirect to url with action as delete and id to the record to be deleted
window.location = 'Remove.php?action=delete&id=' + id;
}
}
</script>
So in short: 1st Table: everything works, all data gets deleted
2nd Table: Appears to be working but after confirming the Delete, the data is still there and didn't get removed from my DB.
The Code for Table 2 is exactly the same as the code for Table 1 exepct for the Names of DB and Table etc.
I am hoping you can go over my code see if you notice anything that might be causing this.
Maybe if u agree with what I was thinking, that the same code will not work for both tables on the same page, that you can give an example or a link to how I can tackle this issue?
Sorry for the Long code!
Thank you in advanced!
You shouldn't mix the delete's because you might have an instance when one id be the same as the other, so you'll delete the wrong thing. But I don't believe that is your primary problem:
Your select is
SELECT ID2, Klant, Categorie1, SerieNummer1, MacAdress1, ProductCode1, Prijs1, Hoeveelheid1, Aantekeningen1 FROM CDE
But your delete is:
DELETE FROM CDE WHERE id = ?";
You're delete should probably be:
DELETE FROM CDE WHERE ID2 = ?";
To Prevent Deleting the wrong thing:
The easiest thing to do here, is change you're delete user JavaScript to accept an action parameter and specify which delete you want to perform, because both delete attempts are running right now.
JavaScript
You don't need the JavaScript twice on the same page. Just have it one time in your HEAD or right before the end of the body.
<script type='text/javascript'>
function delete_user( action, id ){
var answer = confirm('Are you sure?');
if ( answer ){ //if user clicked ok
//redirect to url with action as delete and id to the record to be deleted
window.location = 'Remove.php?action=' + action + '&id=' + id;
}
}
</script>
Checking Action
if ($action=='delete_BCD') {
// or
if ($action=='delete_CDE') {
Rendering Rows
echo "<a href='#' onclick='delete_user( \"delete_BCD\", {$ID2} );'>Delete</a>";
// or
echo "<a href='#' onclick='delete_user( \"delete_CDE\", {$ID2} );'>Delete</a>";
I have a form I'm using to send multiple fields with a similar name but using square brackets to send them as an array with the key being 'id'. I am able to loop through successfully using a foreach loop but my insert query fails to make any changes in the db.any clues as to why?
here is the code from the form:
$artist = mysql_fetch_array($allartists);
$allmusic = get_music_for_artist($artist_id);
$id = $music['id'];
while ($music = mysql_fetch_array($allmusic)) {
echo "<td class=\"td20 tdblue\">
<input name=\"song_title[" . $id . "]\" type=\"text\" value=\"" . $music['song_title'] . "\" />
</td>";
}
and here is the code on my form processor
foreach ($_POST['song_title'] as $id => $song) {
$query = "UPDATE music SET
song_title = '{$song}'
WHERE id = $id ";
if (mysql_query($query, $connection)) {
//Success
header("Location: yourmusic.php?pid=3");
exit;
} else {
//Display error message
echo "update did not succeed";
echo "<p>" . mysql_error() . "</p>";
}
}
Try this.
Also watch for security http://www.phptherightway.com/#data_filtering
foreach ($_POST['song_title'] as $id => $song) {
$id = (int) $id;
$song = mysql_real_escape_string($song);
$query = "UPDATE music SET
song_title = '$song'
WHERE id = $id LIMIT 1;";
if (mysql_query($query, $connection)) {
//Success
header("Location: yourmusic.php?pid=3");
exit;
} else {
//Display error message
echo "update did not succeed";
echo "<p>" . mysql_error() . "</p>";
}
}