So here I am trying to create a logbook with some simple php.
The problem is that nothing is being added to the database I created. Whenever I check the database I just keep getting an empty dataset after adding and submitting text on the guestbook form.
Can anybody see any problems with my code?
<?php
$sql = mysql_connect("localhost" , "root") or die(mysql_error);
mysql_select_db("guestbook" , $sql);
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$query = mysql_query("INSERT INTO message (name , email) VALUES ('$name' , '$email')");
echo ("Message succesfully added.");
}
?>
<html>
<head>
<title>Guestbook</title>
</head>
<form action="index.php" method="post">
Name: <input type="text" name="name"/><br>
Email: <input type="text" name="email"/><br>
<input type="submit" value="Post!"/>
</form>
</html>
<?php
$result = mysql_query("SELECT * FROM message ORDER BY id DESC");
while($row = mysql_fetch_array($result))
{
?>
<table>
<tr>
<td>Name:</td>
<td><?php echo $row['name'] ?></td>
</tr>
<tr>
<td>Message:</td>
<td><?php echo $row['email'] ?></td>
</tr>
</table>
<?php
}
?>
Replace
mysql_query("INSERT INTO message (name , email) VALUES ('$name' , '$email'");
With
mysql_query("INSERT INTO message (name , email) VALUES ('$name' , '$email')");
I think that name is a reserved word in mysql isn't it?
you might have to modify your inset script as follows:
$query = mysql_query("INSERT INTO message (`name` , email) VALUES ('$name', '$email')");
Having said that, your script is WIDE open to an injection attack. You should be using PDO and also verifying data before you go sticking it into an SQL statement. What do you do when your user enters bob;drop table users; as his name and your query runs?
Edit: Also, you had a bracket missing.
Edit 2: If you are still getting an error run this and let us know what you see:
$sql = "INSERT INTO message (`name` , email) VALUES ('$name', '$email')";
echo $sql;
There is a good chance you see that one of the variables is empty.
Edit 3:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
if(!empty($name) && !empty($email))
{
$query = mysql_query("INSERT INTO message (name , email) VALUES ('$name' , '$email')");
echo ("Message succesfully added.");
}
else
{
echo "It seems that either name or email was empty, so not inserting data.<br>";
}
}
?>
Edit 4 - aka Goodness me!
I also noticed that I failed to add the extra bracket to the code that I copied from your question. I have edited it to include it from now on.
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$username = mysql_real_escape_string($_POST['username']);
$username = mysql_real_escape_string($_POST['useremail']);
if(!empty($name) && !empty($email))
{
$query = mysql_query("INSERT INTO message (name , email) VALUES ('$username', '$useremail')");
echo ("Message succesfully added.");
}
else
{
echo "It seems that either name or email was empty, so not inserting data.<br>";
}
}
<html>
<head>
<title>Guestbook</title>
</head>
<form action="index.php" method="post">
Name: <input type="text" name="username"/><br>
Email: <input type="text" name="useremail"/><br>
<input type="submit" value="Post!"/>
</form>
?>
// Make sure you stick this </html> at the BOTTOM of you php file.
</html>
Related
The problem is; I'm trying to fix the sign-up validation but still, it still saved in our database even if it's empty hopefully someone can provide explicit information as to were wrong in coding.
even if one of input box is empty it is still saved to our database table
<!DOCTYPE html>
<html>`enter code here`
<head>
<title>Sample Registration Form</title>
</head>
<body>
<form action="submit.php" method="POST">
<input type="text" name="userid" placeholder="USER ID"><br>
<input type="text" name="firstname" placeholder="FIRST NAME"><br>
<input type="text" name="lastname" placeholder="LAST NAME"><br>
<input type="text" name="email" placeholder="EMAIL"><br>
<input type="password" name="password" placeholder="PASSWORD"><br>
<button tabindex="submit" name="submit">Sign up</button>
</form>
<a href='login.php'><button type='submit' name='submit'>Proceed to Login</button></a>
</body>
</html>
the code above is the sign-up page
<!DOCTYPE html>
<html>
<head>
<title>Submit </title>
</head>
<body>
<?php
$dbservername = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "blogfinal";
$connect = mysqli_connect($dbservername, $dbusername, $dbpassword, $dbname);
if(isset($_POST['submit'])) {
$userid = $_POST['userid'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$password = $_POST['password'];
$checker = array("userid", "firstname", "lastname", "email", "password");
$Error = true;
foreach ($checker as $values) {
if(empty($_POST[$values])) {
echo "Error";
$Error = true;
} else {
$sql = "INSERT INTO userinformation
(userid, firstname, lastname, email, password)
VALUES ('$userid', '$firstname', '$lastname',
'$email', '$password');";
}
if(mysqli_query($connect, $sql)) {
echo "Saved Successfully<br>";
echo "<a href='login.php'><button type='submit' name='submit'>Proceed to Login</button></a>";
} else {
echo "Error Description: " . mysqli_error($connect);
}
}
}
?>
</body>
</html>
the code above is the submit function.
the problem is when we hit the sign-up even if the input-box is empty and it is still functioning and saved to our database, instead of a password, email, user, or first name is required.
[if you leave it empty then proceed to submit it show saved even there's no data on it.][1]
[the image after we hit the submit button.][2]
[hence, if we at least insert 1 data required and proceed to submit it still saved to our database, instead of showing that the other data is required][3]
[1]: https://i.stack.imgur.com/gVc0i.png
[2]: https://i.stack.imgur.com/Aizjl.png
[3]: https://i.stack.imgur.com/A04c0.png
The problem is that you're checking if each value is empty withif(empty($_POST[$values])) within a foreach loop. This if has an else that is running every time.
So even if one of the fields in empty, the query will always execute if there's at least 1 field that is not empty.
You should change the logic to make that even if just one field is empty, then the query doesn't run.
Here's a quick fix:
$Error = false;
// Check if all fields are not empty
foreach ($checker as $values) {
if(empty($_POST[$values])) {
echo "Error";
$Error = true; // If even just one field is empty, the $Error variable will be true
break;
}
}
if(!$Error) { // Check if I got an error
$sql = 'INSERT INTO userinformation,(userid, firstname, lastname, email, password) VALUES ("?", "?", "?", "?", "?");';
$stmt = $connect->prepare($sql)
$stmt->bind_param('sssss', $userid, $firstname, $lastname, $email, $password);
if($stmt->execute())
// The rest of your query
}
Furthermore please refer to the comment by #RiggsFolly to your question as your code has security issues connected to SQL Injection.
I'm trying to play around with databases and inserting data dynamically with php.
At the moment I have a form with 'post' method and everything seems logical to me but it isn't inserting the data into the table.
Code is attached below, would appreciate if someone could point me into the right direction.
index.php:
<form action="index.php" method="post">
<label for="name">Name</label>
<input type="text" name="name" required>
<label for="breed">Breed</label>
<input type="text" name="breed">
<label for="age">Age</label>
<input type="text" name="age">
<input type="submit" name="submit" value="Submit">
</form>
<?php
require "connect.php";
if('submit') {
$name = $_POST['name'];
$breed = $_POST['breed'];
$age = $_POST['age'];
$newdog = mysqli_query('INSERT INTO `dogs`(`name`, `breed`, `age`) VALUES ([$name],[$breed],[$age)');
if ($newdog) {
echo "$name has been added to the database";
} else {
echo "$name has not been added to database.";
};
};
?>
connect.php:
<?php
$connect = mysqli_connect('localhost', 'max', 'password', 'db_test');
?>
<?php
require "connect.php";
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$breed = $_POST['breed'];
$age = $_POST['age'];
$newdog = mysqli_query($connect, 'INSERT INTO dogs(name, breed, age) VALUES ("'.$name.'","'.$breed.'","'.$age.'")');
if ($newdog) {
echo "$name has been added to the database";
} else {
echo "$name has not been added to database.";
};
};
?>
Change if('submit') {
TO
if(isset($_POST['submit'])){//check if it is set
}
Also change this line:
$newdog = mysqli_query('INSERT INTOdogs(name,breed,age) VALUES ([$name],[$breed],[$age)');
TO
$newdog = mysqli_query($connect, 'INSERT INTOdogs(name,breed,age) VALUES ($name,$breed,$age)');//remove square bracktes and add connection variable
Your code is very well vulnerable to SQL injection
Using prepared statements,
$stmt = $connect->prepare("INSERT INTO dogs (`name`, `breed`, `age`) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $name, $breed, $age);
if($stmt->execute() == true){
echo 'Saved';
} else {
echo 'Error '. $stmt->error;
}
Own answer: Figured it out, I had to configure PHPStorm to use MAMP Apache server instead of the internal server since that one apparently doesn't like $_POST[] requests
Below is my Html and php code both in separate files for my insert query it is trying to insert registration details but it keeps failing, any reasons where i am going wrong.
I have trying using different types of speech marks but it still doesnt work and the textbook i have shows this method. The database can log users in and check if user exists but can not insert data. Thanks.
<?php
include 'db.php';
session_start();
?>
<!DOCTYPE html>
<html>
<head>
</head>
<?php
include 'header.php';
?>
<div id="logincontent">
<div id="registerform" class="loginform-in">
<h1>Registration</h1>
<fieldset>
<form id="myForm" action="registerscript.php" method="POST">
Email: <input type="text" name="username"/><br />
Password: <input type="password" name="pass"/><br />
First Name: <input type="text" name="fname"/><br />
Last Name: <input type="text" name="lname"/><br />
Address 1: <input type="text" name="add1"/><br />
Address 2: <input type="text" name="add2"/><br />
Postcode: <input type="text" name="pcode"/><br />
Telephone: <input type="text" name="phone"/><br />
<button id="submit">Register</button>
</form>
<div id="ack"></div>
</fieldset>
</div>
</div>
</body>
</html>
PHP File
<?php
include('db.php');
$email = mysql_real_escape_string( $_POST["username"] );
$pass = mysql_real_escape_string( md5($_POST["pass"]) );
$firstname = mysql_real_escape_string( $_POST["fname"] );
$surname = mysql_real_escape_string( $_POST["lname"] );
$add1 = mysql_real_escape_string( $_POST["add1"] );
$add2 = mysql_real_escape_string( $_POST["add2"] );
$pcode = mysql_real_escape_string( $_POST["pcode"] );
$phone = mysql_real_escape_string( $_POST["phone"] );
if( empty($email) || empty($pass) )
{
echo "Email and Password are Mandatory";
exit();
}
$res = mysql_query("SELECT email FROM members WHERE email='$email'");
$row = mysql_fetch_row($res);
if( $row > 0 )
echo "The Email $email has already been taken. Click Forgot Password to Retrieve";
else
{
$sql = "INSERT INTO members (memberid, firstname, surname, address1, address2, postcode, telephone, email, password) VALUES (
'',
'$firstname',
'$surname',
'$add1',
'$add2',
'$pcode',
'$phone',
'$email'
'$pass')";
if( mysql_query($sql) )
echo "Registration Successfull";
else
echo "An Error Occured Please Try Again";
}
?>
You missed a comma here
'$phone',
'$email', //<-------------- Here
'$pass')";
Remove memberid from $sql = insert into ... this is probably an auto_increment type value in your mysql database.
BTW you are better off using mysqli or pdo instead of using mysql_. And with prepared statements you would limit the risk for SQL injection.
Add the following to find MySQL Error:
else
echo "An Error Occured Please Try Again";
echo mysql_errno($res) . mysql_error($res);
I have tried a number of different ways of inserting data into my DB I have got a little further it used to just say error but now when you submit the form it loads a blank page, the data from the form isn't added to the table however ;/
<form name="datainsert" method="post" action="dataInsert.php">
<label>Server Name: </label>
<input type="text" name="name" placeholder="Enter Server Name" style="margin-left:90px; width:160px; padding:5px; margin-top:10px;"><br />
<label>Server Location:</label>
<input type="text" name="location" placeholder="Enter Server Location" style="margin-left:71px; width:160px; padding:5px; margin-top:10px;"><br />
<label>Server Operating System:</label>
<input type="text" name="os" placeholder="Enter Server OS" style="margin-left:16px; width:160px; padding:5px; margin-top:10px;"><br/>
<input style="margin-top:10px;" name="submit" value="submit" type="submit">
</form>
<?php
include 'dbconnect.php';
$name = $_POST['name'];
$location = $_POST['location'];
$os = $_POST['os'];
)
mysql_query("INSERT INTO fostvm (name, location, os) VALUES ('$name', '$location', '$os')");
$result=mysql_query($sql);
if($result){
echo "Data Added Successfully";
} else {
echo "Error";
}
?>
Can anyone see a syntax error or where I might be going wrong
thanks!
Try this. your code is Ok just comment this line ($result=mysql_query($sql);). use this code. why you try mysql_qury() two times in your code.
<?php
include 'dbconnect.php';
$name = $_POST['name'];
$location = $_POST['location'];
$os = $_POST['os'];
)
$result = mysql_query("INSERT INTO fostvm (name, location, os) VALUES ('$name', '$location', '$os')");
//$result=mysql_query($sql);
if($result){
echo "Data Added Successfully";
} else {
echo "Error";
}
?>
You have no $sql variable and you are using it mysql_query try this,
<?php
include 'dbconnect.php';
if(isset($_POST['submit'])){ // check for form submit
$name = $_POST['name'];
$location = $_POST['location'];
$os = $_POST['os'];
$result=mysql_query("INSERT INTO fostvm (name, location, os) VALUES ('$name', '$location', '$os')");
if($result){
echo "Data Added Successfully";
} else {
echo "Error";
}
}
?>
Also you should use mysqli as mysql is deprecated
Hey guys i had a similar problem before but i scraped that idea. Now basically my system allows my users to input there data into the fields and if they submit it the information will go to the database. Now for some reason the data does not go and i am presented with the echo that i stored in my else statement which was " echo" try again later" ;"
Now i have gone back into the database and looked at all the fileds and there correct names and placed them into the query but nothing gets stored into the db. Now you may be thinking whats the file on top called connect.inc.php in my code this is its basically a script in php which connects to the server.
here is my code pleas have a look thank you :)
<?php
//require 'core.inc.php';
include 'connect.inc.php';
if(isset($_POST['Username'])&& isset($_POST['Password']) && isset($_POST['PasswordAgain'])&& isset($_POST['Firstname'])&& isset($_POST['Lastname'])){
$username = $_POST['Username'];
$password = $_POST['Password'];
$password_again = $_POST['PasswordAgain'];
$Firstname = $_POST['Firstname'];
$password_hash = md5($password);
$Lastname = $_POST['Lastname'];
if(!empty($username)&& !empty($password) && !empty($password_again) && !empty($Firstname) && !empty($Lastname)){
if ($password !== $password_again) {
echo "passwords do not match";
}
else{
$query = "SELECT username FROM members WHERE username = '$username'";
$query_run = mysql_query($query);
if(mysql_num_rows($query_run )==1){
echo "The username ". $username ." is taken";
}else{
$query = "INSERT INTO members VALUES ('','Firstname','Lastname','Username','Password')";
if ($query_run = mysql_query($query)){
echo "Well done";
}else{
echo "Sorry we couldn't register at this time. Please try again later thank you";
}
}
}
}
else{
echo "Please fill in all the details thank you ";
}
}
?>
<form action="join.inc.php" method="post">
Username: <input type="text" name="Username" value="<?php echo $username; ?>" /><br />
Password: <input type="password" name="Password" /><br />
Password Again: <input type="password" name="PasswordAgain" /><br />
FirstName: <input type="text" name ="Firstname" value="<?php echo $Lastname; ?>" /><br />
LastName: <input type="text" name ="Lastname" value="<?php echo $Firstname ?>" /><br />
<input type="submit" value="SUBMIT" />
</form>
Connect Script
I would recommend explicitly stating the columns used in your INSERT statement.
INSERT INTO members (`field1`, `field2`, ...)
VALUES ('','Firstname','Lastname','Username','Password')
Also, what is the blank value you are trying to insert? If that field is an AUTO_INCREMENT field, you should not include it in the VALUES declaration.
Try this :
INSERT INTO members (`field1`, `field2`, ...)
VALUES ('','$Firstname','$Lastname','$Username','$password_hash')
IF your first field is auto_increment
omit the field1 as shown below
INSERT INTO members (`field2`,`field3`,...)
VALUES ('field2Val','field3Val',...);
password !== $password_again
should be
password != $password_again
enable error_reporting and see whats wrong actually, is the ID first field auto increment?
if that's auto increment your query will execute but if its not auto increment and set to PK only it wont insert records and raise duplicate key error.
hope this helps
Try changing to:
$query = "INSERT INTO members VALUES ('". $Firstname."','". $Lastname. "','" .$username. "','" .$password_hash. "')";
$result = mysql_query($query);
if (!$result){
echo "Sorry we couldn't register at this time. Please try again later thank you";
}else{
echo "Well done";
}
you should use something like this.
$query = "insert into members (id,username) values ('','$username')";