I'm currently trying to create a comment section on my website. The code is almost done but I have run into an issue. When submiting the text, it is not going to my database. Here is the code to take the text and send it to MySQL database.
<?php
include 'dbh.inc.php';
function setComments($conn) {
if(isset($_POST['commentSubmit'])){
$uid = $_POST['uid'];
$date = $_POST['date'];
$message = $_POST['message'];
$sql = "INSERT INTO comments (uid, date, message) VALUES ('$uid,
$date,
$message')";
$result = $conn->query($sql);
}
}
If you could provide me with an answer that would be great.
You have wrong quotation marks around the values. You need to quote around each individual variable in the $sql string.
<?php
include 'dbh.inc.php';
function setComments($conn) {
if(isset($_POST['commentSubmit'])){
$uid = $_POST['uid'];
$date = $_POST['date'];
$message = $_POST['message'];
$sql = "INSERT INTO comments (uid, date, message) VALUES ('$uid',
'$date',
'$message')";
$result = $conn->query($sql);
}
}
NOTE: Use parametrized queries. Read this post about sql injection.
Related
I have three files reg_form.php, dbconnection.php and insert.php.
When submitting the form the data is not inserted into the database. I can't figure out why. Initially I didn't know how to use insert into multiple tables but took the advice of many posts from here. Unfortunately I have still failed to make it work and it is driving me insane. Here is the sql code so far for the insert.
<?php
include ("dbconnection.php");
if(file_exists("dbconnection.php")) {
echo"Connected to database successfully";
} else if(!file_exists("dbconnection.php")){
echo "Connection failed";
}
$forename = "forename";
$surname = "surname";
$address_line1 = "address_line1";
$address_line2 = "address_line2";
$address_line3 = "address_line3";
$city = "city";
$postcode = "postcode";
$phone = "phone";
$email = "email";
$username = "username";
$password = "password";
$cpassword = "cpassword ";
$query = "INSERT INTO users (username,
password)VALUES('$username','$password');";
$query2 = "INSERT INTO users_details (forename, surname,address_line1,
address_line2, address_line3, city, postcode, phone, email)
VALUES('$forename','$surname','$address_line1','$address_line2',
'$address_line3','$city','$postcode','$phone','$email')";
query ($dbconnection,$sql);
?>
Ok problem is solved. I made a stored procedure because I am doing an INSERT INTO multiple tables and then called it like this.
$sql ="CALL add_user('".$username."', '".$password."', 'user',
'".$forename."','".$surname."', '".$address_line1."' ,
'".$address_line2."', '".$address_line3."', '".$city."', '".$postcode."',
'".$phone."', '".$email."','".is_bool($email_contact)."',
'".is_bool($phone_contact)."')";
$query = $con->prepare($sql);
$query->execute();
I have a HTML contact form in which the user is allowed to write whatever he wants in the message input field. This form is being posted using AJAX and being processed in the below PHP.
My problem is that i get an empty row in the MySql Table.
I am simply wondering why $message = $_POST['message']; returns the proper value, when $message = mysql_real_escape_string($_POST['message']); returns empty string!!
What am I missing here??
//posted data
$firstName = mysql_real_escape_string($_POST['firstName']);
$lastName = mysql_real_escape_string($_POST['lastName']);
$name = $firstName. ' ' .$lastName ;
$email = mysql_real_escape_string($_POST['email']);
$phone = mysql_real_escape_string($_POST['phone']);
$subject = mysql_real_escape_string($_POST['subject']);
$hear = mysql_real_escape_string($_POST['hear']);
$message = mysql_real_escape_string($_POST['message']);
$db_server = mysql_connect($db_hostname, $db_username, $db_password)
// Check if is Duplicates
$query_usercheck = " select * from `test` where Name='$name' and Email='$email' and Phone='$phone' and Subject='$subject' and Message='$message' "; //matching all fields
$usercheck = mysql_query($query_usercheck) or die(mysql_error());
$row_usercheck = mysql_fetch_assoc($usercheck);
$totalRows_usercheck = mysql_num_rows($usercheck);
if ( $totalRows_usercheck > 0 ) {
$duplicate = 'Yes';
} else {
$duplicate = 'No';
//adding application data to MySql database
$add = mysql_query("INSERT INTO `test` (`Date`, `Day`, `Time`, `Name`, `Email`, `Phone`, `Subject`, `From`, `Message`)
VALUES ('$date','$day','$time','$name','$email','$phone','$subject','$hear','$message')");
}
// close mysql
mysql_close();
The problem is that you connect to the database after you do mysql_real_escape_string. Please move your connecting to the database before escaping your variables.
Even better, get rid of the deprecated mysql_* functions (there are even gone in PHP7)! Use mysqli or even better: use PDO with prepared statements as even mysql_real_escape_string is not safe.
mysql_real_escape_string requires an active database connection to do its job. You have not established a connection at the point of calling it.
This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 7 years ago.
This is the code in my PHP script on a very basic html page with a form. I have tried every possible variation of single quotes, double, single and double for the values. I didn't get any response at all. I have tested to make sure the connection is made, but nothing is inserted in the DB. I just don't know what I'm doing wrong.
// Check our connection
if (mysqli_connect_errno($con)) {
print_r("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if(isset($_POST["submit"])){
$name = $_POST['name'];
$company = $_POST['company'];
$email = $_POST['email'];
$comment = $_POST['comment'];
// Insert our data
$query = mysqli_query("INSERT INTO 'contacts' ('id','name', 'company', 'email', 'comment') VALUES ('','$name', '$company', '$email', '$comment')", $con);
$result = ($query);
if( $result )
{
print_r('Success');
}
else
{
print_r('Query Failed');
}
mysqli_close($con);
}
Your order is inverted, http://php.net/manual/en/mysqli.query.php.
connection first, then query.
mixed mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )
You also incorrectly used single quotes around the column names; those should be backticks; When to use single quotes, double quotes, and backticks in MySQL.
Additionally you should never pass user input directly to SQL. This is how injections occur. You should look into using prepared statements. How can I prevent SQL injection in PHP?
if (mysqli_connect_errno($con)) {
print_r("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if(isset($_POST["submit"])){
$name = mysqli_real_escape_string($con, $_POST['name']);
$company = mysqli_real_escape_string($con,$_POST['company']);
$email = mysqli_real_escape_string($con,$_POST['email']);
$comment = mysqli_real_escape_string($con,$_POST['comment']);
// Insert our data
$query = mysqli_query($con, "INSERT INTO `contacts` (`name`, `company`, `email`, `comment`) VALUES ('$name', '$company', '$email', '$comment')");
if($query) {
print_r('Success');
} else {
print_r('Query Failed');
}
mysqli_close($con);
}
You don't need to use apostrophe (') for your table and column name. Remove the apostrophe in your contacts table. You can use backticks (`) for column names.
$query = mysqli_query($con, "INSERT INTO contacts (id, name, company, email, comment)
VALUES ('','$name', '$company', '$email', '$comment')");
You are also prone to SQL injections, so use *_real_escape_string.
$name = mysqli_real_escape_string($con, $_POST['name']);
$company = mysqli_real_escape_string($con, $_POST['company']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$comment = mysqli_real_escape_string($con, $_POST['comment']);
While you are at it, using mysqli_* API, you might want to check on prepared statement.
My code is showing -1 Record Inserted error and not inserting the fields to database. Any thoughts of why is it doing this?
<?php
include("dbconnect.php");
$con=new dbconnect();
$con->connect();
error_reporting(E_ALL);
if($_POST) {
$users_name = $_POST['name'];
$users_email = $_POST['email'];
$users_website = $_POST['website'];
$users_comment = $_POST['content'];
$users_name = htmlspecialchars($users_name);
$users_email = htmlspecialchars($users_email);
$users_website = htmlspecialchars($users_website);
$users_comment = htmlspecialchars($users_comment);
$postid = $_GET['id'];
$sSql = "INSERT INTO comments
( post_id, name, email, website,content)
VALUES ($postid, '$users_name',
'$users_email', '$users_website', '$users_comment' )";
mysql_query($sSql);
$update=mysql_affected_rows();
echo "<h2>$update Record Inserted</h2><br />";
echo '<h2> Your Comment is submitted</h2><br />';
}
?>
For some reason, the comments table is not getting updated. I am new to programming in mySQL and PHP. Any suggestions would be of so much help to me. Thanks.
First insert dummy values in your php SQL statement & comment mysql_query statement.
$sSql = "INSERT INTO comments (post_id,name,email,website,content) VALUES (100, 'anoop.pete','anoop.pete#gmail.com', 'www.anooppete.com', 'Nice Website' )";
//mysql_query($sSql);
//$update=mysql_affected_rows();
Print the SQL statement...
print($sSql);
Copy the SQL statement from web browser, Execute the $sSql in MySql
If the row is inserted, in MySQL, uncomment and run the same page again.
mysql_query($sSql);
$update=mysql_affected_rows();
If it runs, try removing htmlspecialchars()
$users_name = $_POST['name'];
$users_email = $_POST['email'];
$users_website = $_POST['website'];
$users_comment = $_POST['content'];
I guess your htmlspecialchars() is returning some invalid characters...
-1 means the query returned an error.
Put this sql query into your sql browser's sql 'querier' and see what the error is:
INSERT INTO
comments
(post_id,
name,
email,
website,
content)
VALUES
(2,
'name',
'email#',
'http://',
'comment')
I'm very new to PHP and am having some trouble. I have a form using HTML which is action=.php method=post
The form is using text boxes and select options, I'm not sure if it makes a difference in sqldatabase. I've tried about 30 different combinations of this script and can only get a connect successfully message but nothing is posted.
<?php
$link = mysql_connect('everybodyslistcom.ipagemysql.com', 'accounts', 'accounts');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_select_db("user");
$FName = $_POST["FName"];
$LName = $_POST["Lname"];
$Phone = $_POST["Phone"];
$EmailAddress = $_POST["EmailAddress"];
$Month = $_POST["Month"];
$Day = $_POST["Day"];
$Year = $_POST["Year"];
$Username = $_POST["Username"];
$Password = $_POST["Password"];
$sql = 'INSERT INTO Members (ID, FName, LName, Phone, EmailAddress, Month, Day, Year, Username, Password) VALUES'
. '(\'\', \'$FName\', \'$LName\', \'$Phone\', \'$EmailAddress\', \'$Month\', \'$Day\', \'$Year\', \'$Username\', \'$Password\')';
mysql_close();
php?>
try to execute your query
mysql_query($sql);
EDIT: I see you are doing this:
$sql = 'SELECT bla bal $variable';
PHP will not parse the variable. The right way:
$sql = "SELECT bla bla $variable"; // valid
$sql = "SELECT bla bla {$variable}"; // also valid
$sql = 'SELECT bla bla '.$variable; // also valid
your closing php tag is not correct, it should be
?>
rather than
php?>
Also u r not executing your query using:
mysql_query('your query here');
this might cause the problem.
Your variables are not interpreted by PHP. If you want variable to be parsed in string, it should be wrapped in double-quote (")
It may fail if any of your posted data contains some quote character, so you must apply mysql_real_escape_string to all of them.
I hope that database connection credentials are not real you posted here? :D
You said that your form contains "action=.php" literally, you have to turn it into :
<form name="form_name" method="post" action="your_script.php">
You need to execute the query too:
mysql_query($sql, $link);
you should also check whether POST was really sent:
if (!empty($_POST)) {
// ... your code here
}
next thing: you don't need closing tag ?> if your *.php file consist only PHP code - end of file is also correct end of PHP block of code - it's "good-to-have" habit, because in some cases it helps you to avoid error: "Cannot add/modify header information - headers already sent by..."
next problem - wrong way of inserting variables into string:
$sql = 'INSERT INTO Members (ID, FName, LName, Phone, EmailAddress, Month, Day, Year, Username, Password) VALUES'
. '(\'\', \'$FName\', \'$LName\', \'$Phone\', \'$EmailAddress\', \'$Month\', \'$Day\', \'$Year\', \'$Username\', \'$Password\')';
correct way:
$sql = "INSERT INTO Members (ID, FName, LName, Phone, EmailAddress, Month, Day, Year, Username, Password) VALUES (null, '$FName', '$LName', '$Phone', '$EmailAddress', '$Month', '$Day', '$Year', '$Username', '$Password')";
more info here
next - as Deniss said, instead of:
$FName = $_POST["FName"];
should be:
$FName = mysql_real_escape_string($_POST["FName"]);
actually you should fist check weather magic quotes gpc are on or off:
if (get_magic_quotes_gpc()) {
if (!empty($_POST)) {
array_walk_recursive($_POST, 'stripslashes_value');
}
}
function stripslashes_value(&$value) {
$value = stripslashes($value);
}
without this you could have problem with double \\ inserted into db (it depends on your server configuration)
and last but not least: as Robert said you miss one more important thing:
mysql_query($sql);
I think your error because your have not call mysql_query function
can try my code edit
<?php
$link = mysql_connect('everybodyslistcom.ipagemysql.com', 'accounts', 'accounts');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_select_db("user",$link);
$FName = $_POST["FName"];
$LName = $_POST["Lname"];
$Phone = $_POST["Phone"];
$EmailAddress = $_POST["EmailAddress"];
$Month = $_POST["Month"];
$Day = $_POST["Day"];
$Year = $_POST["Year"];
$Username = $_POST["Username"];
$Password = $_POST["Password"];
$sql = "INSERT INTO Members SET FName='{$FName}', LName='{$LName}', Phone='{$Phone}', EmailAddress='{$EmailAddress}', Month='{$Month}', Day='{$Day}', Year='{$Year}', Username='{$Username}', Password='{$Password}'";
// Call Function mysql_query insert new record in mysql table
mysql_query($sql,$link);
mysql_close($link);
?>
Comment for me if your have problem :) or notes of apache services
good day