I'm learning to put values into my db from php.
this is my simple form i wrote to test (its in a table)
<form action="connect2db.php" method="post">
<table width="500" border="0">
<tr>
<td width="200">first name:</td>
<td><input type="text" width="258" name="fname" id="fname"/></td>
</tr>
<tr>
<td width="200">last name:</td>
<td><input type="text" width="258" name="lname" id="lname"/></td>
</tr>
<tr>
<td>
your email address:
</td>
<td>
<input type="text" width="258" name="email" id="email"/>
</td>
</tr>
<tr>
<td width="200">Your message:</td>
<td><textarea rows="5" cols="45" name="mssg" id="mssg" ></textarea></td>
</tr>
<tr>
<td><input type="submit"></td>
</tr>
</table>
</form>
everything works as far as page 1 sending the values to page 2, and echoing them out. but
when its time to insert them into the db table. its not working.
this is the php code:
when i do a SELECT * FROM myTableNameHere, it says "empty set", when i enter the values manually via terminal to test, i get the values fine.
here is my simple code:
<?php
$connection = mysql_connect("127.0.0.1","root","passhere");
if(!$connection) {
die("database connection failed you fool!: FIX IT!" . mysql_error()); }
$db_select = mysql_select_db("storeemail",$connection);
if(!$db_select){
die("database selection failed." . mysql_error()); }
else{ echo "connection made ";
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
</head>
<body>
<?php
$to = 'email#gmail.com';
$subject = 'test from my email php script';
$email = $_POST['email'];
$name = $_POST['fname'];
$lastname = $_POST['lname'];
$mssg = $_POST['mssg'];
$insertData = mysql_query("INSERT into myusers(firstname, lastname)
VALUES ('$name', '$lastname', '$email', '$mssg');");
mysql_close($connection)
?><br/>
your first name is - <?php echo $name; ?><br/>
your last name is - <?php echo $lastname ; ?><br/>
your message to send is - <?php echo $mssg; ?> <br/>
</body>
</html>
$insertData = mysql_query("INSERT into myusers(firstname, lastname)
VALUES ('$name', '$lastname', '$email', '$mssg');");
above you have specified 2 columns and giving values for four variables
myusers(firstname, lastname) gets interpreted as function. Separate myusers from paranthesis.
myusers (firstname, lastname) You also need to specify two more columns since you insert four values. And omit the trailing semi-colon withing the query string.
$insertData = mysql_query("INSERT into myusers (firstname, lastname, email, mssg) VALUES ('$name', '$lastname', '$email', '$mssg')");
Your code is also vulnerable to SQL Injections. Put you $_POST call within a mysql_real_escape_string() function call.
$email = mysql_real_escape_string($_POST['email']);
for what i can see, you are only specifying 2 columns for the insert (firstname, lastname) and 4 values (name, lastname, email, msg), so the column count does not match (either insert 2 or 4 values, and specify all of them accordingly).
after the insert, issue a mysql_error($connection) to see any errors that may arise with your queries
Here is a good article on this matter to prevent further similar questions. It covers all basic operations with MySQL tables with PHP. Isn't it's easier to ask such questions on Google first?
Related
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 5 years ago.
<?php
session_start();
$host="localhost";
$username="root";
$password="";
$db_name="registrering";
$tbl_name="users";
$conn = mysqli_connect($host, $username, $password, $db_name);
if(!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>
<html>
<head>
<title>user registration system using php and PHP and Mysq</title>
<!---<link rel="stylesheet" type="text/css" href="style.css">-->
</head>
<body>
<div style="float:right; width:70%">
<table width="150px" border="0" cellpadding="3" cellspacing="1">
<h2>Registrer<h2/>
<form method="post" action=" ">
<br>
<tr>
<td>Brugernavn</td>
<td>:</td>
<td><input type="text" name="Brugernavn"> </td>
</tr>
<br>
<tr>
<td>Email</td>
<td>:</td>
<td><input type="text" name="Email"> </td>
</tr>
<br>
<tr>
<td>Password</td>
<td>:</td>
<td><input type="password" name="Password"></td>
</tr>
<input type="submit" name="registrer" value="Registrer">
<p>
Allerede medlem? Log ind
</p>
</form>
</div>
</table>
</body>
</html>
<?php
if (isset($_POST["registrer"]))
{
$my_username=$_POST["Brugernavn"];
$my_email=$_POST["Email"];
$my_password=$_POST["Password"];
$sql = "INSERT INTO 'users'(`username`, `email`, `password`) VALUES ('$my_username','$my_email','$my_password')";
$resultat = mysqli_query($conn, $sql);
}
?>
It needs to connect to a database, but it doesn't. It's on a localhost and we can't insert data into a database. The database consists of a username, email and password.
We are using varchar(65) and utf8_general_ci.
Assuming the connection is working - the insert should have back ticks around the user name, not normal quotes.
$sql = "INSERT INTO `users`(`username`, `email`, `password`) VALUES ('$my_username','$my_email','$my_password')";
I would also recommend looking into prepared statements and bind parameters, not forgetting to NOT store passwords as plane text.
Just a tip. Try using die() to print out the mysql error every time you run a mysql query. Hope it will save you a lot of effort and time in the debugging process. Also use back-ticks users near insert statement.
How do I alter the following code to allow me to extract data from another table (data2), and post it as I did the others(name,position,bio). Basically I want another form field that I can search from to find an item from another table, and add into this one.
<?php
require 'db/connect.php';
$error = ""; //variable to hold our form error message
$success = ""; //variable to hold our success message
if(isset($_POST['create'])){
$name = trim($_POST['name']);
$position = trim($_POST['position']);
$bio = trim($_POST['bio']);
if(empty($name) && empty($position) && empty($bio)){
$error = "You must fill all fields.";
}else{
$insert = $db->prepare("INSERT INTO staff (name, position, bio, joined) VALUES (?, ?, ?, NOW())");
$insert->bind_param(sss, $name, $position, $bio);
if($insert->execute()){
//$success = "Staff added successfully!";
header("location:index.php");
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="wrapper">
<h1>Create New Staff</h1>
<span class="error"><?php if(isset($error)) echo $error;?></span>
<span class="success"><?php if(isset($success)) echo $success;?> </span>
<form action="" method="post">
<table class="table">
<tr>
<td><label for="name">Name:</label></td>
<td><input type="text" id="name" name="name"></td>
</tr>
<tr>
<td><label for="position">Position:</label></td>
<td><input type="text" id="position" name="position"></td>
</tr>
<tr>
<td><label for="bio">Bio:</label></td>
<td><textarea id="bio" name="bio"></textarea></td>
</tr>
<tr>
<td></td>
<td><button type="submit" class="create" name="create">CREATE</button> <a class="btn" href="index.php">BACK</a></td>
</tr>
</table>
</form>
</div>
</body>
</html>
Well you could have in the table that the form submits to a location_id that is a key linked to the locations table.
Then all you need to do is do an sql query where you select values using LIKE (see MySQL LIKE - I think w3schools covers this well)
You could call this function in Ajax to check every key press.
Alternatively load all the locations to a hidden element and when the input is focused they appear and as you type you use JavaScript to hide those that don't match.
I would write an example but I'm on my phone. Hope this helps a little.
Hi everybody i have a problem with data input from html form throu php to mysql the connection has been done i test it and its working but i cant figure out why data isn't imputed ive double checked the database and its as should be
registration form
<form action="register.php" method="post">
<table>
<tr>
<td>UserName</td>
<td><input type="text" name="username"></td>
<tr>
<td>Password</td>
<td>
<input type="password" name="password">
</td>
<tr>
<td>
First Name
</td>
<td>
<input type="text" name="fname">
</td>
</tr>
<tr>
<td>
Last Name
</td>
<td>
<input type="text" value="" name="lname">
</td>
</tr>
<tr>
<td>
E-Mail
</td>
<td>
<input type="email" name="mail">
</td>
<tr>
<td>
<input type="submit" value="Done!!!">
</td>
</tr>
</table>
database conntection
<?php
$db_adress="localhost";
$db_username="root";
$db_password="******";
$db_name="accounts";
#mysql_connect("$db_adress","$db_username","$db_password") or die ("Could not connect the DATABASE for more infos go kill yourself");
#mysql_select_db("$db_name") or die ("No Database");
?>
data input code
$username = $_POST['username'];
$password = $_POST['password'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$mail = $_POST['mail'];
$insert=("INSERT INTO 'register'(Username, Password, FirstName, LastName, email) VALUES (""'.$username.'", "'.$password '", "'.$fname.'", "'.$lname.'" ,"'.$mail.'")");
mysql_query($insert);
echo "Done";
I am glad for any help!
For the record, you accepted the wrong answer, syntax-wise.
Table and column names are not to be wrapped in quotes, but either use no quotes or use backticks.
$insert=("INSERT INTO register (Username, Password, FirstName, LastName, email)
VALUES ('".$username."', '".$password "', '".$fname."', '".$lname."' ,'".$mail."')");
or:
$insert=("INSERT INTO `register` (Username, Password, FirstName, LastName, email) VALUES
('".$username."', '".$password "', '".$fname."', '".$lname."' ,'".$mail."')");
I also recommend you sanitize your inputs:
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$fname = mysql_real_escape_string($_POST['fname']);
$lname = mysql_real_escape_string($_POST['lname']);
$mail = mysql_real_escape_string($_POST['mail']);
mysql_* functions are deprecated and will be removed from future PHP releases.
Use mysqli_* functions. (which I recommend you use and with prepared statements, or PDO)
http://www.php.net/manual/en/intro.mysql.php
This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
I also noticed that you are storing passwords in plain text. This is not recommended.
Use one of the following:
crypt()
bcrypt()
scrypt()
PBKDF2
PHP 5.5's password_hash() function.
Try this:
I think your syntax of query is wrong. Try given below.
$insert=("INSERT INTO 'register'(Username, Password, FirstName, LastName, email) VALUES ('".$username."', '".$password "', '".$fname."', '".$lname."' ,'".$mail."')");
The problem is the way you are concating. try this-
$insert=('INSERT INTO register(Username, Password, FirstName, LastName, email) VALUES ("'.$username.'", "'.$password '", "'.$fname.'", "'.$lname.'" ,"'.$mail.'")');
It's because of Single quotes and double quotes.
Try below code.
$insert=("INSERT INTO 'register'(Username, Password, FirstName, LastName, email) VALUES ('".$username."', '".$password "', '".$fname."', '".$lname."' ,'".$mail."')");
Your insert query is not properly enclosed in quotes. Try this
$insert= "INSERT INTO 'register'(Username, Password, FirstName, LastName, email) VALUES ('".$username."', '".$password "', '".$fname."', '".$lname."' ,'".$mail."')";
I am having an issue with my php not writing the values it is getting from my ajax script into my MySQL database. I know that the php script is getting the values because they are being echoed in my browser. but when i check my database, only two out of the five values are being inputted. I am sure this isn't a nuance, but I can't seem to crack this.
==============EDIT=============
The values that aren't being written are first name, last name, and job. ($fname, $lname, and $job respectively)
==============EDIT=============
PHP
<?php
//db connecting variables
$hostname = "foobase";
$username = "foobase";
$dbname = "contactformbase";
$password = "password";
$con = new mysqli($hostname, $username, $password, $dbname);
$tbl_name = "client_base";
//Connecting to your database
if ($con->connect_error) {
die('Connect error (' . mysqli_connect_errno() . ')' . mysqli_connect_errno());
}
echo 'success!...' . $con->host_info . "\n";
print_r($_POST);
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$address = $_POST['address'];
$job = $_POST['job'];
$message = $_POST['message'];
//adding values into the database.
$sql="INSERT INTO $tbl_name (First Name, Last Name, Email, Address, Job)VALUES('POST_['first_name']', '$lname', '$address', '$email')";
$result = mysqli_query($con, $sql);
if($result){
echo "success";
}
else {
echo "error";
}
Javascript
<script type="text/javascript">
$("#submit").click(function(e) {
e.preventDefault();
var data_string = $("form#contact").serializeArray();
alert(data_string);
$.ajax({
type: "POST",
url: "database.php",
data: data_string,
success: function(){
alert(data_string);
}
});
return false;
</script>
HTML
<form action="" method="POST" id="contact">
<table>
<tbody>
<tr>
<td><h2>First Name: </h2></td>
<td><h2>Last Name: </td>
<td><h2>Email Address: </td>
</tr>
<tr>
<td><input type="text" name="first_name" placeholder="Johnny"></td>
<td><input type="text" name="last_name" placeholder="Appleseed"></td>
<td><input type="text" name="email" placeholder="johnny#email.com"></td>
</tr>
<tr>
<td><h2>Street Address:</h2></td>
<td><h2>What's Dirty?</h2></td>
</tr>
<tr>
<td><input type="text" name="address" placeholder="123 Applegrove Rd. Appletown, VA 12345"></td>
<td>
<select name="job" form="contact">
<option value="house">House</option>
<option value="roof">Roof</option>
<option value="garage-shed">Garage/shed</option>
<option value="other">Other</option>
</select>
</td>
</tr>
<tr>
<td><h2>Message: </h2></td>
</tr>
</tbody>
</table>
<textarea name="message">
</form>
You have the wrong field names in your PHP.
Change...
$fname = $_POST['fname'];
$lname = $_POST['lname'];
to
$fname = $_POST['first_name'];
$lname = $_POST['last_name'];
Also check the insert statement. It has wrong values against the fields - Address for Email, Eamil for Address.
$sql="INSERT INTO". $tbl_name ."(First Name, Last Name, Email, Address, Job) VALUES('". $_POST['first_name'] ."', '". $_POST['last_name'] ."', '". $_POST['adress'] ."', '". $_POST['email'] ."')";
You are using strange variables POST_['first_name'].
Try this query:
(Note: you have to use the quotes (' ') for the fields because you have a space in field names or use PDO to prepare and execute query.)
$sql="INSERT INTO $tbl_name (First Name, Last Name, Email, Address, Job)
VALUES('$fname', '$lname', '$address', '$email')";
Other issue is the POST array, you send first_name instead of fname and last_name instead of lname:
<tr>
<td><input type="text" name="first_name" placeholder="Johnny"></td>
<td><input type="text" name="last_name" placeholder="Appleseed"></td>
<td><input type="text" name="email" placeholder="johnny#email.com"></td>
</tr>
This will return:
$_POST = array(
"first_name" => "Johnny",
"last_name" => "Appleseed",
"email" => "johnny#email.com"
);
As you see you don't have $_POST['fname'] and $_POST['lname']
so you have to change:
$fname = $_POST['first_name'];
$lname = $_POST['last_name'];
About job, you just didn't add it in INSERT statement:
$sql="INSERT INTO $tbl_name (First Name, Last Name, Email, Address, Job)
VALUES('$fname', '$lname', '$address', '$email', '$job')";
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>