PHP SQL Insert To DB - php

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

Related

POST method not inserting data into database table

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

When added 3 fields to the MySQL it didn't show some fields

I have added 3 fields to MySQL, but it have shown only "feedback" value, other were empty.
Here is my code:
$name = $_POST['name'];
$email = $_POST['email'];
$feedback = $_POST['feedback'];
if (mysql_query("INSERT INTO `feedback` (`name`, `email`, `feedback`) VALUES ('".mysql_real_escape_string($name)."','".mysql_real_escape_string($email)."','".mysql_real_escape_string($feedback)."')")) {
echo 'Success!';
} else {
echo mysql_error();
exit;
}
<form action="ajax.php" method="post" class="postcard">
<textarea type="text" value="" id="theMessage" name="feedback" required></textarea>
<input type="text" id="input2" name="name">
<input type="text" id="input3" name="email">
</form>
Got my name field - TEXT(30), email and feedback - VARCHAR
You can try this code:
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$feedback =mysql_real_escape_string($_POST['feedback']);
if (mysql_query("INSERT INTO `feedback` (`name`, `email`, `feedback`) VALUES ('$name','$email', '$feedback')")) {
echo 'Success!';
} else {
echo mysql_error();
exit;
}
Also you check your field length. If your value length more than field length may be fail to insert.
Try without quotation marks.
"INSERT INTO `feedback` (name, email, feedback) VALUES ('".mysql_real_escape_string($name)."','".mysql_real_escape_string($email)."','".mysql_real_escape_string($feedback)."')"))

Undefined index form error

i read all answer about undefined index error but not help full for me because i'm already using isset function to check plz how to slove this problem..
<?php
$con=mysqli_connect("localhost","root","","contact");
if (mysqli_connect_errno())
{
echo "failed".mysqli_connect_error();
}
checking for submited data
if(isset($_POST['submit']))
{
$name=$_POST['name'];
$website=$_POST['website'];
$gender=$_POST['gender'];
$comment=$_POST['comment'];
}
$sql="insert into form(name,website,gender,comment) Values('$_POST[name]','$_POST[website]','$_POST[gender]','$_POST[comment]')";
if(!mysqli_query($con,$sql))
{
die('error:'.mysqli_error($con));
}
else "added";
mysqli_close($con);
?>
<html>
<body>
<form method=post action="<?php echo $_SERVER['PHP_SELF']; ?>">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
Website: <input type="text" name="website"><br>
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male<br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<input type=submit name="submit"><br>
</form>
</body>
these errors comes
Notice: Undefined index: name in H:\Wamp\Xamp\htdocs\form.php on line 15
Notice: Undefined index: website in H:\Wamp\Xamp\htdocs\form.php on line 15
Notice: Undefined index: gender in H:\Wamp\Xamp\htdocs\form.php on line 15
Notice: Undefined index: comment in H:\Wamp\Xamp\htdocs\form.php on line 15
Please try the following corrected code :
if(isset($_POST['submit']))
{
$name=isset($_POST['name']) ? $_POST['name'] : '';
$website=isset($_POST['website']) ? $_POST['website'] : '';
$gender=isset($_POST['gender']) ? $_POST['gender'] : '';
$comment=isset($_POST['comment']) ? $_POST['comment'] : '';
$sql="insert into form(name,website,gender,comment) Values('$name','$website','$gender','$comment')";
// Open the database connection here
// aka, mysqli_connect()
if(!mysqli_query($con,$sql))
{
die('error:'.mysqli_error($con));
}
else "added";
mysqli_close($con);
}
?>
<html>
<body>
<form method=post action="<?php echo $_SERVER['PHP_SELF']; ?>">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
Website: <input type="text" name="website"><br>
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male<br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<input type=submit name="submit"><br>
</form>
</body>
What I did is added validation to check if those fields are set, and if so, then set the value, if not, then set the variable (aka $name) to ''. You should probably add some further validation in the event of required fields being = '' (equal to blank).
I also adjusted your query to not use the $_POST vars, instead it uses the variables that you are assigning the $_POST values to, so you know they exist for sure.
And lastly, I moved the mysql connection code and query itself into the if(isset(submit)) statement so it does not try to process those on regular page load where the form has not been submitted yet.
Update this insert query,
$sql="insert into form(name,website,gender,comment) values('". $name ."','". $website ."','". $gender ."','". $comment ."')";
Hope this help you!
Change
if(isset($_POST['submit']))
{
$name=$_POST['name'];
$website=$_POST['website'];
$gender=$_POST['gender'];
$comment=$_POST['comment'];
}
$sql="insert into form(name,website,gender,comment) Values('$_POST[name]','$_POST[website]','$_POST[gender]','$_POST[comment]')";
if(!mysqli_query($con,$sql))
{
die('error:'.mysqli_error($con));
}
else "added";
mysqli_close($con);
?>
to
if(isset($_POST['submit']))
{
$name=$_POST['name'];
$website=$_POST['website'];
$gender=$_POST['gender'];
$comment=$_POST['comment'];
$sql="insert into form(name,website,gender,comment) values ('$name','$website','$gender','$comment')";
if(!mysqli_query($con,$sql))
{
die('error:'.mysqli_error($con));
}
else "added";
mysqli_close($con);
}?>
than friends problem is slove
What wrong?
if(isset($_POST['submit']))
{
$name=$_POST['name'];
$website=$_POST['website'];
$gender=$_POST['gender'];
$comment=$_POST['comment'];
$sql="insert into form(name,website,gender,comment) Values('". $name . "','" . $website . "','" . $gender . "','" . $comment . "')";
//these also in if(isset()) Block
if(!mysqli_query($con,$sql))
{
die('error:'.mysqli_error($con));
}
else "added";
}
thanx to all

PHP Insert INTO Not Inserting Data

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);

Input not being added to my mysql server?

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>

Categories