I have a simple form set up in HTML to pass values to PHP and put them in a MYSQL database. I just can't fathom why nothing is happening when I click the submit button. Previously it was saying 'failed' but now nothing. I have checked the values from the form - fine. I've checked the database connection - fine. I've checked the SQL statement - well, I can't see any errors.
This is my main HTML page
<p class="subtitle">Let me know what you think</p>
<form action="db_insert.php">
<input name="username" placeholder="Name">
<br>
<textarea name="comments" placeholder="Please type your comments here"
cols=120 rows=5></textarea>
<br>
<input type="button" name="submit" value="submit">
<br>
<p id="commTitle">Comments</p>
<br>
<p id="comment"></p>
This is the PHP
<?php
include 'db_connection.php';
//create database connection
$conn = OpenCon();
$username = htmlspecialchars($_POST['username']);
$comment = htmlspecialchars($_POST['comment']);
$sql = 'INSERT INTO sitecomments(username, comment) VALUES(:username,:comment)';
$stmt = $conn -> prepare($sql);
$stmt -> bindValue(':username', $username);
$stmt -> bindValue(':comment', $comment);
$q_result = $stmt -> execute();
if($q_result){
echo 'Comment Inserted Successfully';
}
else{
echo 'Failed';
}
db_connection.php looks like this (with credentials removed.
<?php
function OpenCon(){
//pass the database details to variables
$host = "localhost";
$dbuser = "*****";
$dbpass = "*****";
$dbname = "*****";
// combine host and db name in to single variable
$dbhost = "mysql:host=$host;dbname=$dbname";
//create PDO from database information
$dbconn = new PDO($dbhost, $dbuser, $dbpass);
return $dbconn;
}
?>
As I said, I've checked the database connection and all is fine so where on earth am I going wrong? My database has 3 fields but one is autoincremented so I haven't included it in the query. I tried the query in MyPHPAdmin and it passed ok.
The first thing I notice is that the input has name of "comments" rather than the $_POST variable you're accessing called comment:
<textarea name="comments" placeholder="Please type your comments here" cols=120 rows=5></textarea>
$comment = htmlspecialchars($_POST['comment']);
Try changing that and see if it fixes the issue.
It would be helpful to handle errors within your code. In your current example if something goes wrong you will have a hard time finding out where the problem is.
You can try all of the following examples from the PHP Docs on PDO error handling and PDO::errorInfo:
Assert your connection is valid:
try {
$dbh = new PDO($dsn, $user, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}
Assert your SQL is valid
/* Provoke an error -- bogus SQL syntax */
$stmt = $dbh->prepare('bogus sql');
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());
}
As usual the error is a pebcak error, and you need to utilize proper debugging tools to find out where your mistakes are. Good luck!
Related
I am trying to test a very simple PHP form that inserts input into an SQL database. The connection works fine, but the data does not appear in the database when I refresh it. I have only two files, an index.html and a process.php.
index.html:
<html>
<head>Testing</head>
<body>
<div id="frm">
<form action="process.php" method=POST>
<p>
<label>Username</label>
<input type="text" id="stuff" name="stuff">
</p>
<p>
<input type="submit" id="btn" value="Login">
</p>
</form>
</div>
</body>
</html>
Process.php:
<?php
$userinput = $_POST['stuff'];
$servername = "localhost";
$username = "root";
$password = "";
$database = "testing";
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error)
{
die("connection failed: " . $conn->connect_error);
}
else
{
echo "Connected successfully ";
echo $userinput;
$sql = "INSERT INTO `entries`(`input`) VALUES ('$userinput')";
}
?>
The problem is that you're not actually running the query. You just assigned the query string to a variable, so it's not being executed in MySQL.
Your code is vulnerable to SQL injection, so I'm proposing a solution:
<?php
$userinput = $_POST['stuff'];
$servername = "localhost";
$username = "root";
$password = "";
$database = "testing";
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error)
{
die("connection failed: " . $conn->connect_error);
}
else
{
echo "Connected successfully ";
echo $userinput;
$sql = "INSERT INTO `entries` (`input`) VALUES (?)";
if ($stmt = $conn->prepare($sql)) { // Prepare statement
$stmt->bind_param("s", $userinput); //Bind the string (s), with the content from $userinput to the statement marker (?)
$stmt->execute(); // Run (execute) the query
$stmt->close(); //clean up
}
This code should work and also keep you secure from SQL injections.
Haven't tested it fully but I fixed your query.
$sql = mysqli_query($conn, "INSERT INTO entries (input) VALUES ('$userinput')");
also change the post part to: <form action="process.php" method="POST">
That should fix the problem for you
Also make sure you use the function: mysqli_real_escape_string to escape malicious user input to prevent SQL injection.
Another thing: you could change localhost to 127.0.0.1. I think this is more reliable although it's the same in most cases.
Your code is not submitting the query to the database, it is opening the connection but not submitting the query, see below to the submit query request if you use mysqli in PHP
... else {
# this submits the query
$conn -> query ($sql);
}
you need to take function mysqli_query of mysqli that will take parameter as connection object like $conn and 2nd parameter will be sql query to execute.
like this
$sql = mysqli_query($conn, "INSERT INTO entries (input) VALUES ('$userinput')");
to prevent from sql injection you must use PDO because PDO use paramBind to protect injection .
<form action="signup.php" method="POST" id="newsletter">
<h4>Join Our Newsletter</h4>
<input id="email" type="text" value="Enter Email Address Here For Updates" onBlur="javascript:if(this.value==''){this.value=this.defaultValue;}" onFocus="javascript:if(this.value==this.defaultValue){this.value='';}">
<input type="submit" value="Sign up" class="btn2">
</form>
<?php
$dsn = "mysql:dbname=test_db";
$DBusername = "test";
$DBpassword = "test";
try {
$conn = new PDO($dsn, $DBusername, $DBpassword);
}
catch(PDOException $e) {
}
$email = $_POST["email"];
$sql = "INSERT INTO contacts (email) VALUES (:email)";
$pdoQuery = $conn->prepare($sql);
$pdoQuery->bindValue(":email", $email, PDO::PARAM_STR);
$pdoQuery->execute();
setcookie("success", "You have successfully signed up for the newsletter.", 0, "/");
header("Location: index.php");
?>
These are both on separate pages, and I can't seem to figure out why they won't work. Any help would be greatly appreciated! Nothing posts to the database at all. The cookie is working though.
Your connection is probably failing. You don't have a host in your DSN
$dsn = "mysql:host=localhost;dbname=test_db";
Not sure if it is localhost, but hope this shows what it should be. It would also probably help that when you catch the exception, that you output something.
even...
catch(PDOException $e) {
echo "error - ".$e->getMessage().PHP_EOL;
exit;
}
I have a form on an HTML webpage that sends a user's comment and name to a MySQL database table, where it is stored, and then included back onto the page. The problem is, if the user's name has an apostrophe in it, the server (I pay for hosting, it's not my server and I can't change the configuration on it) is sending them to a error page that says:
"The requested URL was rejected. If you think this is an error, please contact the webmaster.
Your support ID is: 13509873612934211694"
UPDATE:
I just completely rewrote the page using a different php format. Now the apostrophe issue and the server error is fixed. However, the page is sending blank entries to the database on every page load. Any ideas?
<?php
$servername = "my_server";
$username = "my_username";
$password = "my_password";
$dbname = "my_database";
$users_name = htmlentities($_POST['name'], ENT_QUOTES, 'UTF-8');
$users_request = $_POST['requests'];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
}
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,
$password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->beginTransaction();
$conn->exec("INSERT INTO submissions (requests, name)
VALUES ('$users_request', '$users_name')");
$conn->commit();
header("Location: clv3.php");
}
catch(PDOException $e)
{
$conn->rollback();
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
<form method="POST" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Make A Request:<br>
<textarea name='requests' id='requests'></textarea> <br>
Your Name (a-z only):<br>
<input type='text' name='name' id='name'/><br>
<input type='submit' value='Send' class='button'>
</form>
Ever heard of SQL injection? This is one you create...
Always escape your data! You are now pushing data given by user directly into database.
$name = mysqli_real_escape_string($conn, $_POST['name']);
$comments = mysqli_real_escape_string($conn, $_POST['comments']);
Also you can encode special chars before insert, and decode when showing
Did you perhaps try:
encodeURI(yourString)
Then on php side you do:
url_decode($_POST['myVariable'])
I have a form field for an update - where I have given the administrators the ability to make changes to comments:
<form method="post" action="form_action.php?job_numb=<?=$job_numb;?>" enctype="multipart/form-data">
<textarea class="form-control"
rows="10"
name="comments"
maxlength="5000">
<!--This is grabbing the previous $comments from the database-->
<?php echo html_entity_decode($comments);?>
</textarea>
</form>
I was wondering why text seemed truncated or cut-off, thinking it had to do with character limit it did not. How do you make sure the special characters don't stop the SQL from breaking?
The SQL row is set to text.
I have since learned that I just needed prepared statements, and that "cleaning" the data was not necessary at all.
See code below
<?php
$servername = "localhost";
$username = "XXXXX";
$password = "XXXXX";
try {
$conn = new PDO("mysql:host=$servername;dbname=**YOURDATABASE**", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
if(isset($_POST['submit']) && !empty($_POST['submit'])) {
$job_name = htmlspecialchars($_POST['job_name'], ENT_QUOTES, 'UTF-8');
$comments = htmlspecialchars($_POST['comments'], ENT_QUOTES, 'UTF-8');
}
$conn->exec($sql);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$conn = null;
$sql = "UPDATE `jobs_canjobs` SET
`job_name`='$job_name',
`comments`='$comments'
WHERE job_numb = '$job_numb'";
?>
There is no need for a second variable, and although the previous method worked - it was just an extra step.
I got it all working, thanks for all your help and pointing me in the right direction.
i have a web host, which has MySQL, and phpMyAdmin. The code below shows the PHP in my .php file. When i submit the form, the data does not store in the SQL database.
My database is a table called 'Logins'. It has three fields: 'userID' which is an autoincrement type,'email' which is a VARCHAR, and 'password' which is also a VARCHAR.
I have tested my connection, and it does work, meaning something in the code is wrong, but i can't find it. I would be grateful if you guys could help me.
This is my code:
<form action="index.php" method="post">
<p>Email Address:</p>
<input type="text" name="email" required autofocus pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$" placeholder="Please enter your email">
<p>Password:</p>
<input type="text" name="password" required placeholder="Enter your password">
<p>Confirm Password:</p>
<input type="text" name="confirmpassword" required placeholder="Confirm your password">
<br>
<input class="button" type="submit" value="Register">
</form>
<?php
if($_POST['submit']=="Submit")
{
$email = cleanData($_POST['email']);
$password = cleanData($_POST['password']);
$message = "wrong answer";
addData($email, $pasword);
}
function cleanData($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
$data = strip_tags($data);
return $data;
}
function addData ($email, $password)
{
//include("dbinfo.php");
$dbhost = 'mysql11.000webhost.com';
$dbuser = '************'; //censored for security
$dbpass = '******'; //censored for security
$conn = mysql_connect("$dbhost", "$dbuser", "$dbpass");
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql="INSERT INTO Logins ('userID','email','password') VALUES (null, '$email', '$password')";
$result=mysql_query($sql) or die(mysql_error());
}
?>
The sql insert field names should not be in quotes and you mentioned that userID is autoincrementing so no need to include it unless you want to set it to a specific value.
$sql="INSERT INTO Logins (email, password) VALUES ('$email', '$password')";
You should also consider changing to mysqli since mysql is depreciated.
Edit: Your mysql_connect is missing the database select variable in the code you provided.
You will find debugging mysql queries much easier if you make use of the return values of each mysqli function. The below code checks for, and returns, any errors relating to database connection, query prepare, parameter binding, and execution.
This procedure makes it much easier to identify problems if they occur and with modification can be used to log errors, and report errors to the user even in production.
function addData ($email, $password)
{
//include("dbinfo.php");
$dbhost = 'mysql11.000webhost.com';
$dbuser = '************'; //censored for security
$dbpass = '******'; //censored for security
$dbname = ''; // this is currently missing
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
/* check connection */
if ($mysqli->connect_errno) {
die("Connect failed: ".$mysqli->connect_error);
}
// define the query
$sql="INSERT INTO Logins (email, password) VALUES (?, ?)";
// prepare the query
if (!$stmt = $mysqli->prepare($sql)) {
// failed to prepare query;
die("Prepare failed: ".$stmt->error);
}
// bind the parameters
if (!$res = $stmt->bind_param('ss', $email, $password)) {
// failed to bind
die("Bind failed: ".$stmt->error);
}
// execute
if (!$res = $stmt->execute()) {
// failed to execute
die("Execute failed: ".$stmt->error);
}
echo "Rows inserted: ".$stmt->affected_rows;
}
change if($_POST['submit']=="Submit")
to if(!empty($_POST['email']) && !empty($_POST['password']))
you must replace the line :if($_POST['submit']=="Submit")
By if(!empty($_POST['submit']))
Or by if($_POST['submit']=="Register")
Try to connect with wrong password and wrong login want to know if
it display the message