I'm trying to use the code below for a comment system. It doesn't work. The info I'm trying to insert into the MySQL table "comment" isn't getting put there. Any idea(s) why it is not working?
Thanks in advance,
John
On comments.php:
echo '<form action="http://www...com/sandbox/comments/comments2.php" method="post">
<input type="hidden" value="'.$_SESSION['loginid'].'" name="uid">
<input type="hidden" value="'.$submissionid.'" name="submissionid">
<label class="addacomment" for="title">Add a comment:</label>
<input class="commentsubfield" name="comment" type="title" id="comment" maxlength="1000">
<div class="commentsubbutton"><input name="submit" type="submit" value="Submit"></div>
</form>
';
On comments2.php:
$comment = $_POST['comment'];
$uid = $_POST['uid'];
$subid = $_POST['submissionid'];
mysql_query("INSERT INTO comment VALUES (NULL, '$uid', '$subid', '$comment', NULL, NULL)");
try
$query = sprintf("INSERT INTO comment VALUES (NULL, '%s', '%s', '%s', NULL, NULL)", $uid, $subid, $comment);
mysql_query($query);
If mysql_query() fails it returns false and mysql_error() can tell you why.
Also take a look at http://docs.php.net/security.database.sql-injection and either use mysql_real_escape_string() or prepared statements.
if ( !isset($_POST['comment'], $_POST['uid'], $_POST['submissionid']) ) {
echo '<pre>Debug: Something is missing. _POST=',
htmlspecialchars( print_r($_POST, 1) ),
'</pre>';
die;
}
$comment = mysql_real_escape_string($_POST['comment'], $mysql);
$uid = mysql_real_escape_string($_POST['uid'], $mysql);
$subid = mysql_real_escape_string($_POST['submissionid'], $mysql);
$query = "
INSERT INTO
comment
VALUES
(NULL, '$uid', '$subid', '$comment', NULL, NULL)
";
echo '<pre>Debug query=', htmlspecialchars($query), '</pre>';
$rc=mysql_query($query, $mysql);
if ( !$rc ) {
die( htmlspecialchars(mysql_error()) );
}
Try this self-contained example (only an example, don't code it this way ;-))
<?php
session_start();
if ( !isset($_SESSION['loginid']) ) {
login();
}
else if ( !isset($_POST['comment']) ) {
showForm();
}
else {
saveComment();
}
function saveComment() {
if ( !isset($_POST['comment'], $_POST['uid'], $_POST['submissionid']) ) {
echo '<pre>Debug: Something is missing. _POST=',
htmlspecialchars( print_r($_POST, 1) ),
'</pre>';
die;
}
// insert correct values here:
$mysql = mysql_connect('localhost', 'localonly', 'localonly') or die(mysql_error());
mysql_select_db('test', $mysql) or die(mysql_error());
$comment = mysql_real_escape_string($_POST['comment'], $mysql);
$uid = mysql_real_escape_string($_POST['uid'], $mysql);
$subid = mysql_real_escape_string($_POST['submissionid'], $mysql);
$query = "
INSERT INTO
comment
VALUES
(NULL, '$uid', '$subid', '$comment', NULL, NULL)
";
echo '<pre>Debug query=', htmlspecialchars($query), '</pre>';
//$rc=mysql_query($query, $mysql);
//if ( !$rc ) {
//die( htmlspecialchars(mysql_error()) );
//}
}
function login() {
$_SESSION['loginid'] = rand(1, 100);
echo 'Your new loginid is ', $_SESSION['loginid'],'<br />
Continue
';
}
function showForm() {
$submissionid = rand(1000, 9999);
echo '<div>submissionid=', $submissionid, '</div>';
echo '<div>loginid=', $_SESSION['loginid'], '</div>';
echo '<form action="?" method="post">
<input type="hidden" value="'.$_SESSION['loginid'].'" name="uid">
<input type="hidden" value="'.$submissionid.'" name="submissionid">
<label class="addacomment" for="title">Add a comment:</label>
<input class="commentsubfield" name="comment" type="title" id="comment" maxlength="1000">
<div class="commentsubbutton"><input name="submit" type="submit" value="Submit"></div>
</form>
';
}
if this "works" compare it to your real application and find the (essential) differences.
Valid return values from yourform
Does
$comment = $_POST['comment'];
$uid = $_POST['uid'];
$subid = $_POST['submissionid'];
contain valid data?
SQL query valid
http://www.w3schools.com/sql/sql_insert.asp
What does mysql_query return
<?php
$result = mysql_query('SELECT * WHERE 1=1');
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>
what mysql_error do you get for your query.
Use PDO instead of mysql_query()
I would advise you to have a look at PDO which does a lot of heavy lifting for you. It for example makes sure that your SQL query is safe because even if the comments was added to your database it could(would) not be safe at all.
PHP security
You should always validate your users input to prevent SQL injection. Luckily when using PDO(using prepared statements which will also give you a speed boost)right this will be done for you behind the seens. Still I would advise you to read these quick security tips from PHP creator to secure your site.
Hopefully this tips will help you in any way.
You need the field names for any INSERT statement. As I don't know the exact ones for your table, I'll make some guesses.
mysql_query("INSERT INTO comment(uid,subid,comment) VALUES($uid, $subid, $comment)");
Related
This is a form within a PHP file saved as single.php
<form action="comments.php" method="post" >
<?php include(ROOT_PATH . "/app/helpers/formErrors.php"); ?>
<input type= "hidden" name="id" value= <?php echo $id; ?> >
<textarea rows="4" name="comment"class="text-input contact-input" placeholder="Comment here....."></textarea>
<button type='submit' name="postcomment" value="comment" class="btn"> Add Comment</button>
</form>
This is also the php file that is receiving the form. comments.php
<?php
include(ROOT_PATH . "/app/helpers/validateComment.php");
$errors = array();
if(isset($_POST['postcomment'])){
$errors = validateComment($_POST);
//USE MYSQLI_REAL_ESCAPE_STRING() TO ESCAPE SINGLE QUOTES
// AND AGAINST SQL INJECTION
$userid = mysqli_real_escape_string($conn, $_SESSION['id']);
$username = mysqli_real_escape_string($conn,$_SESSION['username']);
$postid = mysqli_real_escape_string($conn,$_POST['id']);
$comment = mysqli_real_escape_string($conn,$_POST['comment']);
//prepared statement
$sql = $conn->stmt_init();
$query = "INSERT INTO comments (user_id, post_id, username, comment)
VALUES (?,?,?,?)";
if($sql->prepare($query)){
$sql->bind_param('ssss',$userid,$postid,$username,$comment);
$sql->execute();
header("Location:single.php?id=" . $postid); }
}
?>
and lastly my validatecomment.php
<?php
function validateComment($comments)
{
$errors = array();
if (empty($comments['comment'])){
array_push($errors, 'Comment is required!' );
}
if(!isset($_SESSION['username'])){
array_push($errors, "Sign UP first!");
}
return $errors;
}
?>
I don't understand why the validation is not working. Any help to get this working will highly be appreciated.
Right now, you're creating an error array, and doing nothing with it. Basically, you're letting in anyone who knocks whether you want them in or not. What you need to do is actually decide what to do if there are any errors.
$errors = validateComment($_POST);
if(!empty($errors)) {
// Insert code here to redirect, print out errors, whatever you want
} else {
// And here is where you would put all of your database stuff
$sql = $conn->stmt_init();
$query = "INSERT INTO comments (user_id, post_id, username, comment)
VALUES (?,?,?,?)";
if($sql->prepare($query)){
$sql->bind_param('ssss',$userid,$postid,$username,$comment);
$sql->execute();
header("Location:single.php?id=" . $postid); }
}
}
Note that I did not use the real_escape_string functions. They are unnecessary when you're using prepared statements.
I am trying to be clever, possibly too clever in creating a set of forms that will dynamically insert their data into the database based on their input names.
I have it so it builds the query correctly, however when I attempt to insert it fails as to say it is a malformed query, is there a better way of doing what I am trying to achieve, but similarly?
<form method="post">
<input type="text" name="form_array['text']" />
<button name="insert">Go</button>
</form>
Here is my query generation, on submit of the form:
$setup['table'] = "table1";
if(isset($_POST['insert'])){
$inserts = "";
$values = "";
foreach($_POST['form_array'] as $form_id => $form_data){
if(!empty($form_data)){
if(!isset($first_run)){
$first_run = 1;
$inserts .= $form_id;
$values .= "'".$form_data."'";
} else {
$inserts .= ", ".$form_id;
$values .= ", '".$form_data."'";
}
} else {
die('error');
}
}
die("INSERT INTO '".$setup['table']."' ($inserts) VALUES ($values)");
}
Thanks.
Aside from all the fixes that was commented to you; this can be simplified, try it;
<form method="post">
<input type="text" name="form_array[column1]" />
<input type="text" name="form_array[column2]" />
<button name="insert">Go</button>
</form>
<?php
if(isset($_POST['insert'])){
$table = 'table';
$handler = 'form_array';
$keys = array_keys($_POST[$handler]);
$sql = "INSERT INTO `{$table}` (`".implode('`, `', $keys)."`) VALUES ('".implode("', '", $_POST[$handler])."')";
echo $sql;
}
Output:
INSERT INTO `table` (`column1`, `column2`) VALUES ('value1', 'value2')
Getting an error of
"Error: 1
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 '1' at line 1"
Please help guys, Many thanks in advance.
Code:
<?php
include('head.php');
if(isset($_POST['submit']))
{
$userid = trim($_POST['userid']);
$email = trim($_POST['email']);
$mobile = trim($_POST['mobile']);
$sql = mysqli_query($conn,"INSERT INTO forgot(userid,email,mobile)VALUES ('$userid','$email','$mobile')");
if (mysqli_query($conn,$sql))
{
echo "We will Contact you Soon.<br>";
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>******</title>
<link href="forum-styles.css" rel="stylesheet" type="text/css">
</head>
<style type="text/css">
.txtField {
padding: 5px;
border:#fedc4d 1px solid;
border-radius:4px;
}
</style>
<body background="img/gold-and-money.jpg">
<form action="" method="post" class="basic-grey">
<h1>****** Forgot Password
<span>Please let us know your UserId, We will reset password and inform you.</span> </h1>
<label>
<span>User Id :</span>
<input type="text" name="userid" required />
</label>
<label>
<span>Mobile N. :</span>
<input type="text" name="mobile" required/>
</label>
<label>
<span>Email Id :</span>
<input type="text" name="email" required/>
</label>
<label>
<div align="right"><span> </span>
<input type="submit" class="button" value="Submit" name="submit"/>
</div>
</label>
</form>
</body>
</html>
$sql = mysqli_query($conn,"INSERT INTO forgot(userid,email,mobile)VALUES ('$userid','$email','$mobile')");
if (mysqli_query($conn,$sql))
{
echo "We will Contact you Soon.<br>";
}
You've got two calls here to mysqli_query. The first time, you're making the query and assigning the return value to $sql; the second time, you're running $sql as a query.
To fix the immediate problem, do something along the lines of:
$sql = "INSERT INTO forgot(userid,email,mobile)VALUES ('$userid','$email','$mobile')";
if (mysqli_query($conn,$sql))
{
echo "We will Contact you Soon.<br>";
}
You're assigning your query to a string, and then using that in your query. This makes debugging things easier, as you can now output your generated query to check what you're producing.
However
You're also passing user-generated data directly into an SQL query, without escaping it. This is very bad - at best, you're going to have a problem if some of the data contains apostrophes. At worst, your database will get hacked. One solution here is to use escaping, as Fred suggested, using mysqli_real_escape_string:
$userid = mysqli_real_escape_string($conn, $_POST['userid']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$mobile = mysqli_real_escape_string($conn, $_POST['mobile']);
I'd suggest also looking at using bound parameters and a prepared statement instead, for added extra security.
Use prepared statements, or PDO with prepared statements, they're much safer.
#andrewsi answered correct: "You're running your query twice. The first time, you're assigning the result to $sql; the second time, you're trying to run that result as a query."
#andrewsi, you r running your query twice and your your query contains variables which you have make them as literals. so code would be like this:
$sql ="INSERT INTO forgot(userid,email,mobile)VALUES ($userid,$email,$mobile)";
if (mysqli_query($conn,$sql))
{
echo "We will Contact you Soon.<br>";
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
I hope this will help you.
Here is a basic example. Check where you have a turn. Always keep follow the standard way of coding.
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$mysqli->query("CREATE TABLE myCity LIKE City");
$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);
printf ("New Record has id %d.\n", $mysqli->insert_id);
/* drop table */
$mysqli->query("DROP TABLE myCity");
/* close connection */
$mysqli->close();
?>
Ankit, their are few things to take care of while coding the queries, instead of explaining them, I will try to rewrite the query:
$query = sprintf("INSERT INTO forgot('userid','email','mobile')
VALUES ('%s', '%s', '%s')"
, mysqli_real_escape_string( $con, $_POST['userid'] )
, mysqli_real_escape_string( $con, $_POST['email'] )
, mysqli_real_escape_string( $con, $_POST['mobile'] ));
if (mysqli_query($dbConnection, $query)) {
echo "Successfully inserted" . mysqli_affected_rows($conn) . " row";
} else {
echo "Error occurred: " . mysqli_error($dbConnection);
}
if in case, userid is the integer, convert the userid to int as follows before creating the $query:
$userid = (int)$_POST['userid'];
$sql = "INSERT INTO forgot(userid,email,mobile)VALUES ('$userid','$email','$mobile')";
if (mysqli_query($conn,$sql))
{
echo "We will Contact you Soon.<br>";
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
It will work.
<html><head>
<title>Add record to my_database/my_table</title></head>
<body>
<?php
$self = $_SERVER['PHP_SELF'];
$id = $_POST['id'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
?>
<form action="<?php echo( $self ); ?>" method="post">
ID: <input type="text" name="id" size="3">
First Name: <input type="text" name="fname" size="8">
Last Name: <input type="text" name="lname" size="8"><br>
<input type="submit" value="Submit">
</form>
<?php
if( $id and $fname and $lname)
{
$conn=#mysql_connect( "localhost", "root", "" ) or die( "Err:Conn" );
select the specified database
$rs = #mysql_select_db( "add_record", $conn) or die( "Err:Db" );
create the query
$sql = "insert into my_table ( id, first_name, last_name ) values ( $id, \"$fname\", \"$lname\" )";
execute query
$rs = mysql_query( $sql, $conn );
if( $rs )
{
echo( "Record added:$id $fname $lname" );
}
}
?>
</body></html>
here am getting erro as undefined index id,fname,lastname and when i enter values in this am getting db error
At first when your page load $_POST['id'] value is empty because u ve'nt posted any value in $_POST[];
if(isset($_POST['submit'])){
//all your php code here like below
$self = mysql_real_escape_string($_SERVER['PHP_SELF']);
$id = mysql_real_escape_string($_POST['id']);
$fname = mysql_real_escape_string($_POST['fname']);
$lname = mysql_real_escape_string($_POST['lname']);
}
AND
$sql = "insert into my_table ( id, first_name, last_name ) values ( '$id', '$fname', '$lname' )";
By the way what is your db error??
Those POST values will only be set when the form is POSTed. You can use isset()
$id = isset($_POST['id'])? $_POST['id'] : NULL;
Same for others.
This happens because you have no conditions on that PHP code that will prevent it from executing the first time when the form is loaded. They should only execute when the form is submitted. You can wrap that PHP with
if(isset($_POST))
{
// Your existing database code here
}
Neglecting the obvious security flaws of mysql and nor sql escape strings, does anybody know why my sql tables are getting filled up with empty msgs on page reload.
Every sinngle time the page reloads a form submits. I'm confused as to why this is happening, and how do i stop it?
<?php
ob_start();
session_start();
$con = mysql_connect("localhost","username","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$dates = date('Y-m-d H:i:s');
$uid = $_SESSION['user_id'];
$msg_id = (int) $_GET['msg_id'];
mysql_select_db("db_table", $con);
$result = mysql_query("SELECT users.first_name, users.last_name , intro.intro, intro.outro FROM intro INNER JOIN users ON intro.user_id = users.user_id WHERE intro.message_id = {$msg_id}");
while($row = mysql_fetch_array($result))
{
echo "<div id=\"start\"><div class=\"namedate\"><h1>". $row['first_name'] ." ". $row['last_name'] . "</h1><h2>test</h2></div><div id=\"holdmsg\"><div class=\"cent\"><strong>" . $row['intro'] . "</strong><br><i>" . $row['outro'] ."</i></div></div></div> " ;
}
PART RELEVANT TO THE FORM is this part and also the $_GET, at the top of the page.
<form action="" method="post">
<?php
$sql="INSERT INTO messages (user_id, intro_id , msg, date ) VALUES (('$uid'), {$msg_id} ,'$_POST[msg]', ('$dates'))";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
mysql_close($con);
?>
<textarea rows="2"style="float:left" name="msg" type="text"placeholder="Elaborate on your idea..."></textarea>
<input id="togz2" style="float:right; "type="submit" value="SUBMIT" name="submit" class="butts">
</div></div>
</form>
Why not do it like this?
if (mysql_query($sql,$con))
{
header('location:yourpage.php');
}else{
die('Error: ' . mysql_error());
}
Also I dont see any such statement above your insert query
Like
if(isset($_REQUEST['submit'])){ //to check if posted
$sql="INSERT ......
}
Beside that you should also validate your data before inserting into a database.
Here is good example how to prevent duplicate entry on page load
Please refer link http://www.webhostingtalk.com/showthread.php?t=700175.
<?php
session_start();
$faction = $_REQUEST['faction'] ;
if (!is_array($_SESSION['serials'])) $_SESSION['serials'] = array ();
if ($_REQUEST['serial']){
if ( in_array ($_REQUEST['serial'] , $_SESSION['serials'] ) ){
// duplicate submition, nullify it
$faction = '';
}else{
$_SESSION['serials'][] = $_REQUEST['serial'] ;
}
}
if ($faction) { // form submited
// if faction is not set completely ignore submition
}
?>
<form>
<input type="hidden" name="faction" value="42">
<input type="hidden" name="serial" value="<?=rand(1000000 , 9999999)?;>">
....
the rest of the form is here
....
</form>
Another Solution:-
You should re-direct to a new page after successful insertion.