php + mysql comment system - php

I'm pretty new to php, and for that matter server scripting in general (so go easy on me)
But regardless of that I managed to create this, the first half of a comment system:
<html>
<body>
<form name="Comment" action="InsertComment.php" method="POST">
Name: <input type="text" name="name" /><br>
Comment: <br><textarea style="height: 100px; width: 600px;" name="comment"></textarea><br>
<input id="Special_ID" name="id" value="<?php $unixtime = time(); echo $unixtime; ?>">
<!--^Gathers a unique id^-->
<input type="submit" />
</form>
</body>
</html>
Once submitted -->
<?php
$con = mysql_connect("Blaa", "Blaa", "Blaa");
if(!$con) {
die('Could not connect ' . mysql_error());
}
sql_select_db("Comments", $con);
$sql = "INSERT INTO Posts (Name, Comment, ID)
VALUES('$_POST[name]', '$_POST[comment]', '$_POST[id]')";
?>
This is exactly what I wanted, a user puts in their name, a comment, and a unique post id (time stamp) is generated, then it is all sent to mysql.
But now I'm dumb found as to how I can post this to another page..
I assumed something like:
if(ID == [the id of that post]) {
//$_GET the mysql stuff
//Post inside a specially made div or something
}
Along the lines of that, but I have no clue how to put that into practise :/
Any ideas?
Oh and Please don't suggest an echo type post, I've done that and it's not at all what I want.
**Also this is just the basic code, I don't need suggestions on how to touch it up just yet, also errors in this is only due to my sleep deprivation, the code does work.

As #Marc B has said, you'll first want to fix your SQL injection holes using mysql_real_escape_string. Change your insert statement to
$sql = "INSERT INTO Posts (Name, Comment, ID)
VALUES('" . mysql_real_escape_string($_POST['name']) . "', '" . mysql_real_escape_string($_POST['comment']) . "', '" . mysql_real_escape_string($_POST['id']) . "')";
To display your comment, try this
$sql = "SELECT Name, Comment, ID
FROM Posts
WHERE ID = '" . mysql_real_escape_string($_GET['PostID']) . "'";
$query = mysql_query($sql);
echo "<div id=\"comments_container\">";
while ($row = mysql_fetch_assoc($query))
{
echo "<div class=\"comment\">";
echo "<div class=\"name\">" . $row['Name'] . "</div>";
echo "<div class=\"comment_body\">" . $row['Comment'] . "</div>";
echo "</div>"
}
echo "</div>";
Then CSS style your DIVs using IDs and classes.

Just an example using mysql_fetch_object
Please sanitize your $_GET data before inserting to MySQL, this is a huge injection security flaw.
$sql = "SELECT * FROM Posts WHERE id={$id}"
$result = mysql_query($sql);
$obj = mysql_fetch_object($result)
if(is_object($obj))
{
echo "Welcome " . $obj->Name;
}

A full length example is given here:
http://manzur-ashraf.com/code/auto_commenting_system/Automatic_Commenting_System_and_Email_notification_using_PHP_and_MYSQL.htm
In addition to using a MYSQL database to store the comments, you can also post email to the admin about new comments.

Related

PHP loop generated buttons - only last one works?

First time posting, and PHP is not my strongest area, so here goes...
My code below generates a list of buttons depending on how many values are found in my DB Table, then the second piece of code is supposed to trigger when the buttons are clicked. Everything is working except that the second piece of code only works for the last button generated. Any ideas?
<?php
$username = $_SESSION['sess_user'];
$con=mysql_connect('localhost','root','root') or die(mysql_error());
mysql_select_db('user_registration') or die("cannot select DB");
$loop = mysql_query("SELECT * FROM `vaults` WHERE username = '$username' ORDER BY vaultname asc") or die ('Error Getting User Data! <br />' .mysql_error());
$chk = mysql_num_rows($loop);
$myvalue = '';
while ($row = mysql_fetch_assoc($loop)) {
$myvalue = "{$row['vaultname']}";
echo '<form method="post"><input class="text-center" type="submit" name=' . $myvalue . ' value=' . $myvalue . ' id="vaultSelecter"></form>';
}
?>
<?php
if(isset($_POST[$myvalue])){
echo '<script type="text/javascript">window.onload = function() { document.getElementById("instructions").innerHTML = " HELLO WORLD! "; }</script>';}
?>
Thank you all for your replies, I appreciate it. I understand what everyone is saying, but the ID I reference in my getELementByID() is a separate DIV from the buttons, I want to change the content of the single DIV with the ID "instructions", when any of the buttons are clicked, but it only works for the last button created by the loop. Is that still due to the way I have my buttons ID'd?
For example say the above loop creates three buttons, I want each button to change the contents of the following DIV with "Hello Word".
<div id=instructions>
replace this text
</div>
I am guessing I have to store each of the $myvalues created by the loop into an array, so that each value can be assigned separately to each button, I just have no idea how to do that.
You're duplicating IDs in this line:
echo '<form method="post"><input class="text-center" type="submit" name=' . $myvalue . ' value=' . $myvalue . ' id="vaultSelecter"></form>';
and IDs must be unique. Try classes instead. Ex:
var elems = document.getElementsByClassName("text-center");
for (var i = 0; i < elems.length; i++) {
console.log('x')
elems[i].addEventListener('click', function () {
alert('hello');
}, false);
}
You're assigning multiple inputs to the same id, assign them to a class instead since id's have to be unique.
You're also making a form for every button, which seems kind of pointless to me, try this instead:
echo '<form method="post">';
while ($row = mysql_fetch_assoc($loop)) {
$myvalue = "{$row['vaultname']}";
echo '<input class="text-center vaultSelecter" type="submit" name=' . $myvalue . ' value=' . $myvalue . '>';
}
echo '</form>';
The id called vaultSelector is now a class, so can be accessed via getElementByClassName()
Instead of this:
name=' . $myvalue . ' value=' . $myvalue . ' id="vaultSelecter"
Maybe try
name="' . $myvalue . '" value=' . $myvalue . ' id="' . $myvalue . '"
In my opinion it is best to uniquely identify any elements that will be used as a programming element.
Just another piece of unsoliciated opinion. If you can put everything in one form it may make things easier. So when the button submits set a hidden field and continue with the form submit.

php - send variable to next page by link

I need help.
How can I call the variable(within the url) after a successful search result in my index.php to the next page view.php so that I can view the complete data of the variable?
heres my code
"index.php"
<form method="post" action="index.php?go" id="searchform">
<input type="text" name="name" size = "50">
<br/>
<input type="submit" name="submit" value="SEARCH">
<button type="reset" value="Reset">RESET</button>
</form>
<?php
$db=mysql_connect ("localhost", "root", "") or die ('I cannot connect to the database because: ' . mysql_error());
$mydb=mysql_select_db("emp_dbA");
if(isset($_POST['submit'])){
if(isset($_GET['go'])){
if(preg_match("/[A-Z | a-z]+/", $_POST['name'])){
$name=$_POST['name'];
$letter=$_GET['by'];
$sql="SELECT emp_ID, fname, lname,mname FROM emp_tbl WHERE fname LIKE '%" . $name . "%' OR lname LIKE '%" . $name ."%' OR mname LIKE '%" .$name . "%'";
$result=mysql_query($sql);
$numrows=mysql_num_rows($result);
echo "<p>" .$numrows . " results found for " . stripslashes($name) . "</p>";
while($row=mysql_fetch_array($result)){
$fname =$row['fname'];
$mname =$row['mname'];
$lname=$row['lname'];
$ID=$row['emp_ID'];
echo "<ul>\n";
echo "<li>" . "" .$fname . " " . $mname. " " . $lname . "</li>\n";
echo "</ul>";
}
}
else{
echo "<p>Please enter a search query</p>";
}
}
}
?>
You can use GET or POST to send data to the next page.
http://www.tizag.com/phpT/postget.php
By using the reserved variable $_GET
$_GET['id']
REFERENCE
You get the URL parameters with the $_GET environment variable, while the field you did put inside the form (given that you chose post as the form method) will be read like $_POST["name"].
As a little piece of advice, try to resort to the GET method as few times as possible. Parameters received with the GET method are seen in the URL, while parameters received from the POST method aren't.
And, of course, sanitize all your GET/POST data before actually using it.
$_SERVER['PHP_SELF'] might be a good use here if you want to handle this data on your index.php page. If you'd like to pass it to view.php, action should be:
<form action="view.php" method="POST"></form>
Why not use a pagination class? Look this: http://phpsnaps.com/snaps/view/php-pagination-class/ PS. mysql is deprecated, use mysqli.

What is wrong with my code? Data is not deleted from database

I've updated the code but keep getting new errors.
I'm really hoping that someone can help me and look at my code to see what is wrong.
I have a database table on a webpage and I have one edit button and one delete button on each table row. At the moment I'm just trying to get the delete button to work and it will just not delete the row in the database even though I selected that ID. It looks like it's picking up the correct ID.
Can someone tell what is wrong? Below is the code...
<?php
require 'connect.inc.php';
if (isset($_POST['delete']) && isset($_POST['id'])) {
$id = get_post('id');
$query = "DELETE FROM movies WHERE id='.$id.' LIMIT 1";
if (!mysql_query($query, $db_server))
echo "DELETE failed: $query<br>".
mysql_error() . "<br><br>";
}
$query = "SELECT * FROM movies, categories WHERE movies.genre_id = categories.genre_id";
$result = mysql_query($query);
if (!$result) die ("Database access failed:" .mysql_error()) ;
$rows = mysql_num_rows($result);
echo '<table><tr><th>Title</th><th>Release year</th><th>Genre</th><th>Director</th><th>Update</th><th>Delete</th></tr>';
for ($j = 0 ; $j < $rows ; ++$j) {
$row = mysql_fetch_row($result);
//$id = $row[0];
echo '<tr><td>' .$row[1] . '</td>' ;
echo '<td>' .$row[2] . '</td>' ;
echo '<td>' .$row[3] . '</td>' ;
echo '<td>' .$row[4] . '</td>' ;
echo '<td>'."<a href='edit_movie.php?edit=" . $row[0] . "'>Edit</a>".'</td>';
echo '<td><form action="index.php" method="POST">
<input type="hidden" name="delete" value="yes" />
<input type="hidden" name="id" value="'. $row[0] .'" />
<input type="submit" value="Delete" /></form>
</td></tr>' ;
}
echo '</table>';
include 'add_movie.php';
?>
You forget to close action attribute.
You have echo '<td><form action="index.php method="POST"> change it to
echo '<td><form action="index.php" method="POST">
Just to be clear: 'mysql_query' and accompanying commands is deprecated and should really not be used. The OP however stated that it was required for an assignment. The easiest way to replace them is to use 'mysqli_*' instead. For an example using parameter binding to avoid sql-injection:
http://www.php.net/manual/en/mysqli-stmt.bind-param.php
Shouldn't it be:
if (isset($_POST['delete']) && isset($_POST['id'])) {
$id = mysql_real_escape_string($_POST['id']);
...
See this link for some info on 'get_post':
PHP: Having a problem with get_post
The problem there was that the function 'get_post' was defined on the next page of the course literature, wich the asker hadn't noticed.
The variable $_POST['id'] contains the id-value sent from a form via an HTTP POST-request. You check if that value is set, and then you should assign it to '$id' like i wrote.
Your delete sql has wrong quotes
$query = "DELETE FROM movies WHERE id='.$id.' LIMIT 1";
change to either
$query = "DELETE FROM movies WHERE id=".$id." LIMIT 1";
or
$query = "DELETE FROM movies WHERE id=$id LIMIT 1";
Try changing the form action
'<td><form action="index.php" method="POST">
Also check your database connection is properly established
Perhaps this might help for get_post
PHP: Having a problem with get_post

PHP and MySQL select

Okay so I'm making php that will pull every entry from a data base that matches the name you put in a textbox. so here is a image of the database
http://i.stack.imgur.com/LvmrM.png < screen shot of database
So if i where to put "DigitalNuke" in the textbox and hit the submit button I want only the rows that have "DigitalNuke" as the value in the second column "referrer"
<form ACTION="" METHOD=post>
<div class="input-append">
<input class="span2" id="youruser" type="text" name="youruser" placeholder="Your Username">
<button class="btn btn-success" type="submit">Retrive</button>
</div>
</form>
<?php
require_once 'connect.php';
$name = isset($_POST['youruser']);
$conn= mysqli_connect ($dbhost,$dbuser,$dbpass,$dbname)or die(mysqli_error());
$query1 = "SELECT 'id', 'referrer', 'username', 'brigade', 'faction', 'activity' FROM refmems WHERE referrer='$name";
$result = mysqli_query($conn, $query1)
or die('Error querying the database: ');
echo '<table class="table table-bordered">';
echo '<caption>Your Referred Members</caption>' . '<thead><tr><th>ID</th>' . '<th>Username</th>' . '<th>Brigade</th>' . '<th>Faction</th>' . '<th>Activity</th>' . '</tr></thead>';
while ($row = mysqli_fetch_array($result)) {
echo "<tr class='success'><td>" . $row['id'] . "</td><td>" . $row['username'] . "</td><td>" . $row['brigade'] . "</td><td>" . $row['faction'] . "</td><td>" . $row['activity'] ."</td></tr>";
}
?>
So as of now it doesn't do anything when I hit the submit button. Well it kind of works, except for instead of pulling the data from the table, it just puts id, username, brigade, faction, activity in each row of the generated table.
http://i.stack.imgur.com/XF71h.png < screen shot
Any help would be appreciated, if you need anything else let me know and i'll post it.
$query1 = "SELECT 'id', 'referrer', 'username', 'brigade', 'faction', 'activity' FROM refmems WHERE referrer='$name";
should be:
$query1 = "SELECT `id`, `referrer`, `username`, `brigade`, `faction`, `activity` FROM refmems WHERE referrer='$name'";
Also learn how to use prepared statements for MySQLi. Your code is open to SQL injection.
Your syntax is broken.
"SELECT id, referrer, username, brigade, faction, activity FROM refmems WHERE referrer='$name"
There is no closing single quote after $name, and the fields don't get quoted (or use backticks but it isn't necessary).
Also, you are asking for trouble. You've got user input with no validation/sanitization.

Dynamicly creating and checking checkboxes in php

I am trying to dynamically create php check-boxes linked to an MSSQL-Database. The idea is to List every item in the table, with a check box. From there the user will be able to check the check-boxes and click submit to change the value in 1 field of the Database to "A". I have the database linked to the php and It outputs the check-checkboxes and table values, however I do not know from there how to dynamically check the check-boxes to see if they are checked, or to use it from there.
This is roughly the approach you want to take to dynamically create checkboxes. There are of course prettier ways to accomplish this (i.e. Smarty templates).
<html>
...
<form method="post" action="submit.php">
<?php
// connect to DB here
$result = mysql_query("SELECT l.id, l.name, u.checked FROM List l LEFT JOIN UserAnswers u ON l.id = u.list_id WHERE u.user_id = 5");
while ($row = mysql_fetch_assoc($result))
{
echo '<input type="checkbox" name="cb_' . $row['id'] . '" ' .
'id="cb_' . $row['id'] . '" ';
if($row['checked'])
echo 'checked';
echo " />\n"
echo '<label for="cb_' . $row['id'] . '">' . $row['name'] . "</label><br />\n";
}
?>
<input type="submit" value="Submit" />
</form>
...
</html>
submit.php is a bit trickier. When a checkbox is checked, it will set a post item. However if it's unchecked, you won't get ANYTHING back, so you need to check your database for all the items you'll be expecting.
<?php
// connect to DB here
$result = mysql_query("SELECT id, name, checked FROM things");
$answers = Array();
while ($row = mysql_fetch_assoc($result))
{
$checked = isset($_POST['cb_' + $row['id']]);
$answers[$row['id']] = $checked;
}
// update your database here using $answers
foreach ($answers as $id => $checked)
{
$query = "REPLACE INTO UserAnswers SET user_id=5, list_id=" . $id . ", checked=";
if($checked)
$query .= "1";
else
$query .= "0";
mysql_query($query);
}
This is all off the top of my head, there are better ways to do most of this. It's just a general direction. I make no guarantees about any of this. Oh and it looks quite vulnerable to SQL injection, watch out for that.

Categories