I currently have an HTML form with various feilds one for example is :
Please Enter First Name: <input type ="text" name="First_Name" /> <br />
I am trying to get the information from this form into my database. But it does not seem input anything into the database. Code is as follows.
<?php
$dbname='ecig';
$dbhost='localhost';
$dbpass='password';
$dbuser='eciguser';
$dbhandle = mysql_connect($dbhost, $dbuser, $dbpass)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with
$selected = mysql_select_db("ecig",$dbhandle)
or die("Could not select examples");
$res=mysql_query("INSERT INTO Persons (First_Name, Second_Name) VALUES('$_POST[First_Name]', yes)");
mysql_close();
if (array_key_exists ('check_submit', $_POST ))
echo "Your Name is : {$_POST['First_Name']}<br />";
echo "Your Second Name is : {$_POST['Second_Name']}<br />";
echo "Your Email Address is : {$_POST['Email_Address']}<br />";
echo "Your Password Is : {$_POST['Password']}<br />";
?>
The question is as this is having no impact on my database, is there something i am missing and need to add to my SQL code so that the php and the SQL interact with each other and input the data?
Or am i missing something from the INSERT INTO statement?
Anyway help would be appreciated, Thanks.
There's an error in your query, 'yes' at the end must have quotes.
Try running your query first directly against MySQL to determine if your syntax is correctly, then just replace the values you want.
Should look like this for your example:
$res=mysql_query("INSERT INTO Persons (First_Name, Second_Name) VALUES ('$_POST[First_Name]', 'yes')");
A bit of advice, sanitize your input if you are receiving data from the user, or you will be vulnerable to a SQL injection attack.
And use mysqli_ functions since mysql_ functions are officially deprecated by now. You can read more about those in almost any site, like w3schools.com
Full example of insert with mysqli_ : http://www.w3schools.com/php/php_mysql_insert.asp
Good luck
Use mysql_real_escape_string()
$res=mysql_query("INSERT INTO Persons (First_Name, Second_Name) VALUES ('".mysql_real_escape_string($_POST['First_Name'])."', '".mysql_real_escape_string($_POST[Second_Name])."')");
Related
I got a little form:
<form id="plannerform" action="save.php" method="post">
<input id="plannername" placeholder=" " type="text" autocomplete="off" name="plannername">
<input id="plannersubmit" type="submit" value="eintragen">
</form>
As you can see there is the action="save.php" and method="post" on the text-input there is name="plannername".
And thats my php:
$con = mysql_connect("myHost","myUser","myPW");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("myDB", $con);
$sql="INSERT INTO anmeldungen (FR_PM)
VALUES ('$_POST[plannername]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
The FR_PM is one column of my table. But when I press submit, not even a new row gets created. Nothing happens.
But when I call my php with "mywebsite.com/save.php" it adds a new row in my table (with no value at "FR_PM", what's pretty obvious)
What do I do wrong?
one of the things that you need to learn if you are a beginner, you should try by all means to stay away from using mysql_* function this is depreciated and its no longer supported in php. instead use mysqli_* with prepared statements, or use PDO prepared statements.
prepared statments make you code looks clean and its easy to debug.
this is you example with prepared statements.
<form id="plannerform" action="save.php" method="post">
<input id="plannername" placeholder=" " type="text" autocomplete="off" name="plannername">
<input id="plannersubmit" type="submit" value="eintragen" name="submit">
</form>
save.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['submit'])) {
if (empty($_POST['plannername'])) {
die("Enter plannername");
} else {
// prepare and bind
$stmt = $conn->prepare("INSERT INTO anmeldungen (FR_PM) VALUES (?)");
$stmt->bind_param("s", $_POST['plannername']);
if ($stmt->execute()) {
echo "New records created successfully";
} else {
echo "Could not insert record";
}
$stmt->close();
}
}
?>
The reason I used prepared statements :
Prepared statements reduces parsing time as the preparation on the
query is done only once (although the statement is executed multiple
times)
Bound parameters minimize bandwidth to the server as you need send
only the parameters each time, and not the whole query
Prepared statements are very useful against SQL injections, because
parameter values, which are transmitted later using a different
protocol, need not be correctly escaped. If the original statement
template is not derived from external input, SQL injection cannot
occur.
But when I call my php with "mywebsite.com/save.php" it adds a new row
in my table (with no value at "FR_PM", what's pretty obvious)
What do I do wrong?
Well do prevent that from happening you need to check if the form was submitted before you can actual process any thing.
Note: If we want to insert any data from external sources (like user input from a form ), it is very important that the data is sanitized
and validated. always treat input from a form as if its from a very
dangerous hacker
change your insert query:
$sql="INSERT INTO anmeldungen (FR_PM) VALUES ('".$_POST["plannername"]."')";
Or
$plannername = $_POST["plannername"];
$sql="INSERT INTO anmeldungen (FR_PM) VALUES ('".$plannername."')";
Also, use "name"= and not "id"= in the HTML form.
This is usually misleading when working with forms and HTTP POST method.
you may try
$value = $_POST['plannername'];
$sql="INSERT INTO anmeldungen (FR_PM) VALUES ('{$value}')";
I want import a data (from a form) in my database but i've this error :
Parse error: syntax error, unexpected ';' in /homepages/38/htdocs/index2.php on line 7
and the script is
<?php
//Connecting to sql db.
$connect = mysqli_connect("","","","");
//Sending form data to sql db.
mysqli_query($connect,"INSERT INTO posts (email, pseudo)
VALUES ('$_POST[email]', '$_POST[pseudo]')";
?>
What is the error ?
Thank you
Solution
You have not concatenated the $_POST[] variable correctly.
You have been missing the close brace for the mysqli_query opening.
It is advised to have a separate query and then to execute the mysqli_query().
Necessary Checks:
Ensure that you have given the name for the input type in the form attributes.
Have a check that whether you have called the name what you have given in the form at the PHP code while insert.
(E.g) - Input Attribute needs to be like this
<input type="email" name="email" value="" />
Like this you have to provide for all the Input types.
PHP Code
Usage of the mysqli::real_escape_string is better if you use it avoids SQL Injection.
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$email=mysqli_real_escape_string($con,$_POST['email']);
$pseudo=mysqli_real_escape_string($con,$_POST['pseudo']);
$stmt = "INSERT INTO posts (`email`, `pseudo`)VALUES('".$email."','".$pseudo."')";
$query = mysqli_query($con,$stmt);
if($query)
{
echo "Inserted Successfully";
}
else
{
// Handle Error over here.
}
?>
$email=$_POST['email'];
$pseudo=$_POST['pseudo'];
mysqli_query($connect,"INSERT INTO `posts` (`email`, `pseudo`) VALUES ('$email', '$pseudo');");
You have missed quote inside POST .Check below code
<?php
//Connecting to sql db.
$connect = mysqli_connect("","","","");
$sql ="INSERT INTO posts (email, pseudo)VALUES('".$_POST['email']."','".$_POST['pseudo']."')";
//Sending form data to sql db.
mysqli_query($connect,$sql);
?>
I'm trying to make my first registration script using PHP/SQL. Part of my code isn't working:
if(!$errors){
$query = "INSERT INTO users (email, password) VALUES ($registerEmail, $registerPassword)";
if(mysqli_query($dbSelected, $query)){
$success['register'] = 'Successfully registered.';
}else{
$errors['register'] = 'Registration did not succeed.';
}
}
When I test my code I get the error 'Registration did not succeed.' For reference, $errors and $success are arrays. Is there anything wrong with this part of my script?
$dbSelected is:
$dbLink = mysqli_connect('localhost', 'root', 'PASSWORD');
if (!$dbLink) {
die('Can\'t connect to the database: ' . \mysqli_error());
}
$dbSelected = mysqli_select_db($dbLink, 'devDatabase');
if (!$dbSelected) {
die('Connected database, but cannot select
devDatabase: ' . \mysqli_error());
}
I'm sure I am connecting and selecting the database.
Any help would be greatly appreciated! I am very new to PHP/SQL so forgive me for any noob mistakes.
Quote the string like below
$query = "INSERT INTO users (email, password) VALUES ('$registerEmail', '$registerPassword')";
You can also do
echo $query;
and take the output on the browser, copy and paste into PHPMyAdmin and execute it from there. It should tell you what is wrong with the query.
I suggest you to use prepared statement as using string concatenation in SQL Statement is prone to SQL injection attack. Refer the example PHP mysqli prepare
First off, PHP is deprecating mysql_ functions, you should migrate to PDO instead.
Also, make sure since you're using the older mysql_ functions to sanitize your entries using mysql_real_escape_string
Also, your entries need to be quoted. Here's a redo of your query string:
$query = "INSERT INTO users (email, password) VALUES ('{$registerEmail}', '{$registerPassword}')";
I am not sure what I am doing wrong, can anybody tell me?
I have one variable - $tally5 - that I want to insert into database jdixon_WC14 table called PREDICTIONS - the field is called TOTAL_POINTS (int 11 with 0 as the default)
Here is the code I am using. I have made sure that the variable $tally5 is being calculated correctly, but the database won't update. I got the following from an online tutorial after trying one that used mysqli, but that left me a scary error I didn't understand at all :)
if(! get_magic_quotes_gpc() )
{
$points = addslashes ($tally5);
}
else
{
$points = $tally5;
}
$sql = "INSERT INTO PREDICTIONS ".
"(TOTAL_POINTS) ".
"VALUES('$points', NOW())";
mysql_select_db('jdixon_WC14');
I amended it to suit my variable name, but I am sure I have really botched this up!
help! :)
I think you just need to learn more about PHP and its relation with MYSQL. I will share a simple example of insertion into a mysql database.
<?php
$con=mysqli_connect("localhost","peter","abc123","my_db");
// Check for errors in connection to database.
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Peter', 'Griffin',35)";
mysqli_query($con, $query);
mysqli_close($con); //Close connection
?>
First, you need to connect to the database with the mysqli_connect function. Then you can do the query and close the connection
Briefly,
For every PHP function you use, look it up here first.
(You will learn that it is better to go with mysqli).
http://www.php.net/manual/en/ <---use the search feature
Try working on the SQL statement first. If you have the INSERT process down, proceed.
You need to use mysql_connect() before using mysql_select_db()
Once you have a connection and have selected a database, now you my run a query
with mysql_query()
When you get more advanced, you'll learn how to integrate error checking and response into the connection, database selection, and query routines. Convert to mysqli or other solutions that are not going to be deprecated soon (it is all in the PHP manual). Good luck!
if(! get_magic_quotes_gpc() )
{
$points = addslashes ($tally5);
}
else
{
$points = $tally5;
}
mysql_select_db('jdixon_WC14');
$sql = "INSERT INTO PREDICTIONS (TOTAL_POINTS,DATE) ". //write your date field name instead "DATE"
"VALUES('$points', NOW())";
mysql_query($sql);
The problem is I simply want to insert the fullname/address. I created a users table with the following columns: id (primary), fullname (unique), address (unique).
Here's the code:
<?php $username = "root";
$password = "artislife23";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
//select a database to work with
$selected = mysql_select_db("test",$dbhandle)
or die("Could not select examples");?>
<body>
<div class="container">
<div class="content">
<h1><?php if(($selected!=null)){
echo "Database is on lock.";}
if(($dbhandle!=null)){
echo "Connected to MySQL<br>";
}?></h1>
<form method="post" action="input.php">
<tr><td>Name</td><td><input type="text" name="fullname" size="20"></td></tr>
<tr><td>Address</td><td><input type="text" name="address" size="40"></td></tr>
<tr><td></td><td align="right"><input type="submit" value="Submit"></td>
Here's input.php
<?php
$postr="INSERT INTO users
(fullname, address) VALUES('$_POST[fullname]','$_POST[address]')";
$result = mysql_query($postr);
echo "$result";?>
All that I can see that's happening is a single blank entry was inserted into the table. Am I doing something wrong here? All I want is to successfully insert the form data into my users table here.
$_POST['fullname']
you are missing quotes in your POSTs.
The reason why it doesn't work is that PHP doesn't expand arrays in strings the same way it does variables without some weird syntax I can never remember. Change:
$postr="INSERT INTO users (fullname, address) VALUES('$_POST[fullname]','$_POST[address]')";
To:
$postr="INSERT INTO users (fullname, address) VALUES('".$_POST['fullname']."','".$_POST['address']."')";
You were also missing the quotes on the array keys.
Additional notes:
Your code is wide open to SQL injection, if I entered my name as Bobby'; DROP TABLE users;-- guess what would happen?
mysql_*() functions are deprecated, take the time to learn PDO or MySQLi. They have neat thigns called 'parameterized queries' that allow you to easily avoid SQL injection like I've noted above.
Assuming that either a person's full name or address to be unique to them is a design mistake, don't do this in a 'real-world' project.
Edit
Alternate syntax for embedding arrays in strings:
$string = "Fee fie {$foo['bar']}.";