I started to learn PHP and I need your help because I'm trying to write on my MySQL database. The script seems fine (for me :D) and it doesn't give me errors. But when I submit the query the data doesn't appear inside my MySQL database. Could you help me, please?
This is my HTML/PHP code:
<?php
session_start();
$_SESSION['message'] = '';
//connection variables
$host = '127.0.0.1';
$user = 'root';
$password = 'MyPassword';
$database= 'test';
$port= '3306';
//create mysql connection
$mysqli = new mysqli($host, $user, $password,$database,$port);
if ($mysqli->connect_errno) {
printf("Connection failed: %s\n", $mysqli->connect_error);
die();
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $mysqli->real_escape_string($_POST['name']);
$email = $mysqli->real_escape_string($_POST['email']);
if ($mysqli->query("INSERT INTO 'contatti' ('name', 'email') VALUES ('$name','$email')") == true) {
$_SESSION['message'] = "registration succesfull! Added $name to the database";
} else {
$_SESSION['message'] = "User can't be added to the database";
}
}
?>
<!DOCTYPE html>
<html>
<center>
<h1>Inputs</h1>
<form class="form" action="welcome.php" method="post" autocomplete="off">
<div class="alert alert-error"><?= $_SESSION['message'] ?></div>
<input type="text" name="name" placeholder="Insert your name" /> <br>
<input type="email" name="email" placeholder="Insert your email"/><br>
<input type="submit" name="submit" placeholder="Submit"/>
</form>
</center>
</html>
This is the database:
[Table structure]
[]1
[Database info]
Please use preapared statements and bind parameters instead: http://php.net/manual/en/mysqli-stmt.bind-param.php
You can also debug your mysql server response with error_list:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$stmt = $mysqli->prepare("INSERT INTO `contatti` (`name`, `email`) VALUES (?,?)");
$stmt->bind_param('ss', $name, $email);
if ($stmt->execute()) {
/* ... */
}
else {
$errors = $stmt->error_list;
/* ... */
}
}
You should use prepared statements for MYSQL and PHP, if possible, at least to protect yourself from SQL injection (SO Ref).
That said, when you read this line :
if ($mysqli->query("INSERT INTO 'contatti' ('name', 'email') VALUES ($name,$email)") == true)
You are concatening strings into your SQL query without quotes, and the query string look like (with $name = 'test', $email = 'test#test' :
INSERT INTO 'contatti' ('name', 'email') VALUES (test,test#test) : incorrect syntax
You must escape strings on SQL :
if ($mysqli->query("INSERT INTO 'contatti' ('name', 'email') VALUES ('$name', '$email' )") == true)
The resulting query should look like : INSERT INTO 'contatti' ('name', 'email') VALUES ('test','test#test')
Edit : please note that the table (contatti) and the fields name (name, email) are supposed to be surrounded by backticks, not single quotes (I cannot escape backticks in a quote), and variables $name and $email by single quotes
You have a syntax error in your query, try to change the INSERT query inside the if condition here:
if ($mysqli->query("INSERT INTO 'contatti' ('name', 'email') VALUES ('$name','$email')") == true) {
$_SESSION['message'] = "registration succesfull! Added $name to the database";
} else {
$_SESSION['message'] = "User can't be added to the database";
}
To be like this:
if ($mysqli->query("INSERT INTO contatti (name, email)
VALUES('$name', '$email')") == true) {
$_SESSION['message'] = "registration succesfull! Added $name to the database";
} else {
$_SESSION['message'] = "User can't be added to the database";
}
Related
I am getting into PHP/MySQL code and I've searched all over for a solution to this problem but no answers match my issue.
My code is very simple but I can't find whats causing this error
<?php
$servername = "localhost";
$username = "langalungalangalunga";
$password = "langalungalangalunga";
$dbname = "user_main";
$client_username = $client_password = $client_email = "";
$usernameErr = $passwordErr = $emailErr = "";
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!empty($_POST['username'])) {
$client_username = test_input($_POST['username']);
} else {
$usernameErr = "No input on UserName";
}
if (!empty($_POST['password'])) {
$client_password = test_input($_POST['password']);
} else {
$passwordErr = "No input on Password";
}
if (!empty($_POST['email'])) {
$client_email = test_input($_POST['email']);
} else {
$emailErr = "No input on Email";
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO user_main (UserName, Password, Email)
VALUES ($client_username, $client_password, $client_email)";
// use exec() because no results are returned
$conn->exec($sql);
echo "<script> alert('Success!');</script>";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
?>
The error points at line 2 of the email part
check the manual that corresponds to your MySQL server version for the right syntax to use near ' , email#email.com)' at line 2
<form class="" action='<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>' method="post">
<label for="username">Username</label>
<input type="text" name="username" value="<?php echo htmlspecialchars($_SERVER['username']) ?>">
<label for="password">Password</label>
<input type="password" name="password" value="">
<label for="email">Email</label>
<input type="email" name="email" value="">
<button type="submit" name="button">Register</button>
</form>
I am sorry if it's my mistake somewhere but I am new to PHP all together so I dont really have a feel for the syntax
$sql = "INSERT INTO user_main (`UserName`, `Password`, `Email`)
VALUES ('$client_username', '$client_password', '$client_email')";
$conn->query($sql);
The above code is vulnerable to SQL injection. Use prepared statements as
$stmt = $conn->prepare("INSERT INTO user_main (`UserName`, `Password`, `Email`)
VALUES (:UserName, :Password, :Email)");//placeholders
$stmt->bindParam(':UserName', $client_username);//you do not need to escape inputs
$stmt->bindParam(':Password', $client_password);
$stmt->bindParam(':Email', $client_email);
if($stmt->execute() == true){
//all good
echo'Data successfully saved Securely!';
} else {
print_r($stmt->errorInfo());
exit;
}
An extra tip. Do not store your passwords in plain text. Use password_hash
$hashedPassword = password_hash($client_password, PASSWORD_DEFAULT);
On checking if the password matches the hash, use password_verify
if(password_verify($client_password, $hashedPassword)){// do this when logging in or during some other authentication
//all good
echo 'Password is Correct';
} else {
echo 'Password is InCorrect.Sorry';
}
change you insert sql code like below:
Try this:
$sql = "INSERT INTO user_main (UserName, Password, Email)
VALUES ('".$client_username."', '".$client_password."', '".$client_email."')";
I am trying to insert form data into mysql database but it is not inserted into table and there is no error!
Here is my code
<?php
$con = mysqli_connect('localhost', 'root', '', 'register');
if (isset($_POST['submit'])) {
$shop = $_POST['shopname'];
$name = $_POST['name'];
$user = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$repassword = $_POST['repassword'];
$phone = $_POST['phone'];
$sql = "INSERT INTO registration (shop_name,name,username,email,password,repassword,phone) VALUES ('$shop','$name''$user','$email','$password','$repassword','$phone')";
if (mysqli_query($con, $sql)) {
echo "Signup Sucessfull";
} else {
echo mysqli_error();
}
}
?>
How can I resolve this problem?
Turns out you forgot to mention a comma after the name.
'$name''$user' // Missing comma in between
Also, it should be mysqli_error($con) instead of mysqli_error()
Try some debugging:
$sql = "INSERT INTO registration (shop_name,name,username,email,password,repassword,phone) VALUES ('".$shop."','".$name."', '".$user."','".$email."','".$password."','".$repassword."','".$phone."')";
mysqli_query($con, $sql) or die(mysqli_error($con));
You seems to miss "," between the insert values. This code will work fine.
<?php
$con = mysqli_connect('localhost', 'root', '', 'register');
if (isset($_POST['submit'])) {
$shop = $_POST['shopname'];
$name = $_POST['name'];
$user = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$repassword = $_POST['repassword'];
$phone = $_POST['phone'];
$sql = "INSERT INTO registration (shop_name,name,username,email,password,repassword,phone) VALUES ('".$shop."','".$name."','".$user."','".$email."','".$password."','".$repassword."','".$phone."')";
if (mysqli_query($con, $sql)) {
echo "Signup Sucessfull";
} else {
die(mysqli_error($con));
}
}
?>
Yes, As already #ObjectManipulator pointed your silly mistake
near '$name''$user'.
I will strongly recommend you to use mysqli_prepare to avoid SQL Injection.
<?php
$con = mysqli_connect('localhost', 'root', '', 'register');
if (isset($_POST['submit'])) {
$stmt = mysqli_prepare($con, "INSERT INTO registration (shop_name,name,username,email,password,repassword,phone) VALUES (?, ?, ?, ?,?, ?, ?)");
mysqli_stmt_bind_param($stmt, 'sssssss',$_POST['shopname'],$_POST['name'],$_POST['username'],$_POST['email'],$_POST['password'],$_POST['repassword'],$_POST['phone']);
if (mysqli_stmt_execute($stmt)) {
echo "Signup Sucessfull";
} else {
echo mysqli_error($con);
}
}
?>
And, as #JonStirling suggested not to store password in plain text
and use any Password API to encrypt password.
There are many ways to encrypt your password. Use anyone of them. Right now, I illustrated with md5().
And, Why to store password and repassword in database table. While storing user data into database table, check there itself if password & repassword matches or not.
Just a suggestion. It's upto you to choose.
<?php
$con = mysqli_connect('localhost', 'root', '', 'register');
if (isset($_POST['submit'])) {
if(isset($_POST['password']) && isset($_POST['repassword']) && ($_POST['password'] == $_POST['repassword'])){
$stmt = mysqli_prepare($con, "INSERT INTO registration (shop_name,name,username,email,password,phone) VALUES (?, ?, ?, ?, ?, ?)");
mysqli_stmt_bind_param($stmt, 'ssssss',$_POST['shopname'],$_POST['name'],$_POST['username'],$_POST['email'],md5($_POST['password']),$_POST['phone']);
if (mysqli_stmt_execute($stmt)) {
echo "Signup Sucessfull";
} else {
echo mysqli_error();
}
} else {
echo "Password must match.";
}
}
?>
else {
echo mysqli_error($con);
}
Problem solved. You forgot the connection details $con for your MySQL error output. This will now correctly output your MySQL Syntax mistakes from your query.
Other Notes:
Use Prepared statements for MySQLi (link)
Use a proper Password hashing algorithm such as Password_hash. Do not use MD5 (it's too fast and has too many collisions) and NEVER store passwords as plaintext.
Use the various filter_Var on your POSTed variables to clean them and make sure you catch any invalid data (such as improper email addresses)
Put comma in your sql query as below
$sql = "INSERT INTO registration (shop_name,name,username,email,password,repassword,phone)VALUES
('$shop','$name','$user','$email','$password','$repassword','$phone')";
I am trying to insert some records but I dont know how to check required fields and form controls.Can you show me how can i check required fields?
I am new in php. Thank you.
if(isset($_POST['submitted']) == 1) {
$ad = mysqli_real_escape_string($dbc, $_POST['name']);
$soyad = mysqli_real_escape_string($dbc, $_POST['surname']);
$email = mysqli_real_escape_string($dbc, $_POST['email']);
$q = "INSERT INTO db (name, surname,email) VALUES ('$name', '$surname', '$email')";
$r = mysqli_query($dbc, $q);
if($r){
$message = '<p>Message Added!</p>';
} else {
$message = '<p>Could not add because: '.mysqli_errno($dbc);
$message .= '<p>'.$q.'<p>';
}
}
Your form and php code will not be aware of the limitation set on your database table. You can ask the database how a table looks using the describe keyword followed by the table name. (http://dev.mysql.com/doc/refman/5.7/en/describe.html). The response will tell you which if a field's allowed to be null or not. Based on that you can create your form to take this into consideration.
In your html You can add <input type="text" placeholder="username" name="username" required="required"
/>
The required="required" makes that field required.
And in your php you can check if that field is empty or not like this
if(isset($_POST['username']) && $_POST['username']!="" ){
$uname=$_POST['username'];
if(strlen($uname)>=4){
//use your sql insert query .I'll show you how to do it using pdo
$sql=$conn->prepare("INSERT INTO `yourtable` (uname) VALUES (:u)");
//$conn is your sql connection variable.
$sql->execute(array(":u"=>$uname));
}
else {
echo "please Insert a valid username";
}
}
else {
echo "Please insert an username";
}
Trying to build an email list in a database. I made this code, but it's not working and i'm not getting any errors. Am I on the right track?
HTML:
<div id="signup">
<h1>Sign-Up For Our Newsletter!</h1>
<form method="post" action="scripts/php/addSubscription.php">
<label for="email">E-mail: </label><input type="email" name="email" size="75"> <input type="submit">
</form>
</div>
PHP:
require('settings/globalVariables.php');
require('settings/mysqli_connect.php');
mysqli_select_db($conn,"newsletterlist");
$email = mysqli_real_escape_string($conn, $_POST['email']);
$sql = "INSERT INTO newsletterusers (email) VALUES ($email)";
if (mysqli_query($conn, $sql)) {
echo 'You have successfully subscribed!';
}
else {
echo 'Sorry, An error occured. Please try again.';
}
mysqli_close($conn);
$conn is a variable in mysqli_connect.php
Adding contents of mysqli_connect.php just for reference:
<?php
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASS);
?>
I use this on several databases and it connects each time.
EDIT:
Updated code per answers/comments and still nothing is happening.
require('settings/globalVariables.php');
require('settings/mysqli_connect.php');
mysqli_select_db($conn,"newsletterlist");
$email = mysqli_real_escape_string($conn, $_POST['email']);
$sql = "INSERT INTO newsletterusers (email) VALUES ('$email')";
if (mysqli_query($conn, $sql)) {
echo 'You have successfully subscribed!';
}
else {
echo "Error: ".mysqli_error($conn);
}
mysqli_close($conn);
SOLVED:
require('/home/jollyrogerpcs/public_html/settings/globalVariables.php');
require('/home/jollyrogerpcs/public_html/settings/mysqli_connect.php');
mysqli_select_db($conn,"newsletterlist");
$email = mysqli_real_escape_string($conn, $_POST['email']);
$sql = "INSERT INTO newsletterusers (email) VALUES ('$email')";
if (mysqli_query($conn, $sql)) {
echo 'You have successfully subscribed!';
}
else {
echo "Error: ".mysqli_error($conn);
}
mysqli_close($conn);
You are currently getting an error but your code doesn't show you. Print the error for a start:
if (mysqli_query($conn, $sql)) {
echo 'You have successfully subscribed!';
}
else {
echo "Error: ".mysqli_error($conn);
}
The real error you are getting is a syntax error. This is how your generated SQL looks like:
INSERT INTO newsletterusers (email) VALUES (hello#email.com)
Note that there are no quotes around it, you can fix it by surrounding $email with quotes:
$sql = "INSERT INTO newsletterusers (email) VALUES ('$email')";
I've been reluctant to come back to Stackoverflow to ask this question. It's definitely been asked many times over, but every answer hasn't been able to fix the problem. I've attempted the Header() fix: https://stackoverflow.com/a/18820079/3831297 to no avail and now I have been trying to instead just validate and submit from the same page.
When I was using the Header redirect nothing would happen, no redirect to the next page while also not giving any errors for a reason. Which leaves me with the method below.. A mess of code that I've spent 60+ hours on trying to get to work from answers found on here as well as other websites.
What I've been trying to do with this version is validate with:
if(empty()) {
display error
}else{
variable = true
if(variable = true){
post to database
}
I apologize for the repeated question as well as for my complete lack of knowledge. I am learning as I go with these hands-on projects.
<?php
if (mysqli_connect_errno()) {
echo "Connection to the database failed! Submitting a story will not work! Try again in a few minutes!" . mysqli_connect_error();
}else{
echo "<br>";
echo "<h4>" . "Database connected successfully... It is safe to submit a story!" . "</h4>";
}
$TitleErr = $StoryErr = $AuthorErr = $DateErr = "";
$Title = $Story = $Author = $Date = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Title"])) {
$TitleErr = "Title is required!";
}else{
$valid1 == true;
}
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Story"])) {
$StoryErr = "Story is required!";
}else{
$valid2 == true;
}
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Author"])) {
$AuthorErr = "Author is required!";
}else{
$valid3 == true;
}
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST["Date"])) {
$DateErr = "Date is required!";
}else{
$valid4 == true;
}
}
if ($valid1 = $valid2 = $valid3 = $valid4 = true) {
$Title = mysqli_real_escape_string($con, $_POST['Title']);
$Date = mysqli_real_escape_string($con, $_POST['Date']);
$Author = mysqli_real_escape_string($con, $_POST['Author']);
$Story = mysqli_real_escape_string($con, $_POST['Story']);
$sql="INSERT INTO Moderate (Title, Story, Author, Date)
VALUES ('$Title', '$Story', '$Author', '$Date')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}else{
echo "<br>";
echo "Story submitted for moderation!";
}
}
mysqli_close($con);
//Insert into database
//$sql="INSERT INTO Moderate (Title, Story, Author, Date)
//VALUES ('$Title', '$Story', '$Author', '$Date')";
?>
<h2>Submit News</h2>
<?php// echo htmlspecialchars($_SERVER["PHP_SELF"]);?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<span class="error">* <?php echo $TitleErr;?></span>
Title: <input type="text" name="Title">
<span class="error">* <?php echo $AuthorErr;?></span>
Author: <input type="text" name="Author">
<span class="error">* <?php echo $DateErr;?></span>
Date: <input type="date" name="Date">
<input type="submit"><br>
<span class="error">* <?php echo $StoryErr;?></span>
Story: <br><textarea type="textarea" rows="40" cols="100" name="Story" method="post"></textarea>
</form>
</div>
<?php
//// escape variables for security
//$Title = mysqli_real_escape_string($con, $_POST['Title']);
//$Story = mysqli_real_escape_string($con, $_POST['Story']);
//$Author = mysqli_real_escape_string($con, $_POST['Author']);
//$Date = mysqli_real_escape_string($con, $_POST['Date']);
//Insert into database
?>
I'm going to hazard an answer. Main thing I see is you are using == as assignment and = as comparison. This is backwards.
$valid4 == true; should be $valid4 = true;
if ($valid1 = $valid2 = $valid3 = $valid4 = true) should be if ($valid1 == $valid2 == $valid3 == $valid4 == true) or not really, since it actually has to be:
if ($valid1==true && $valid2==true && $valid3==true && $valid4==true)
With assignment you can stack up the operator, but with boolean comparison, combine the compares with and (&&).
Just some advise, don't make pages submit to themselves. Make a separate page to handle the form from the one that displays the form. That way if you ever want to upgrade to using Ajax, its much easier. Also after doing a db update like this you always need to redirect to another page to prevent double submit (unless using ajax). The page doing the db update should not print anything out but just do the db update and redirect, unless there's a validation error.
Change your PHP to this:
if (isset($_POST['Title'],$_POST['Date'], $_POST['Author'], $_POST['Story'] )){
$con = mysqli_connect("localhost", "my_user", "my_password", "db");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$title = $_POST['Title'];
$date = $_POST['Date'];
$author = $_POST['Author'];
$story = $_POST['Story'];
$query = "INSERT INTO Moderate (Title, Story, Author, Date)
VALUES (?, ?, ?, ?)"
/* create a prepared statement */
if ($stmt = mysqli_prepare($con, $query)) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "ssss", $city);
/* execute query */
mysqli_stmt_execute($stmt);
/* close statement */
mysqli_stmt_close($stmt);
}
/* close connection */
mysqli_close($con);
}