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);
?>
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}')";
Perhaps I'm making some obvious beginner mistake, but I just cannot seem to figure out why this happens.
Strangely enough, the code only seems to work properly if I enter a number into the "inputbox". I check this in the myphpadmin panel, and it shows a new record has been created. However, if I attempt to input a string as intended for my purposes (example: "hello") no new record appears in the database...
In short, the database only updates if I put a number into the "inputbox" but not when I enter a string.
Any ideas why this may be happening? It's driving me crazy. If it helps, the data type of the "Company" field is VARCHAR and the collation is set to latin1_swedish_ci
The PHP code is as follows:
<?php
//Retrieve data from 'inputbox' textbox
if (isset($_POST['submitbutton']))
{
$comprating = $_POST['inputbox'];
//Create connection
$con = mysqli_connect("localhost","root","","test_db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Insert data into 'Ratings' table
mysqli_query($con,"INSERT INTO Ratings (Company,Score)
VALUES ($comprating,1)");
mysqli_close($con);
}
?>
The HTML code is:
<form method="post">
<input type="text" name="inputbox">
<input type="submit" name="submitbutton">
</form>
Cheers
Try this query,
mysqli_query($con,"INSERT INTO Ratings (Company,Score)
VALUES ('$comprating',1)");`
^ ^
Note the single quotes that reserves the string value and don't forget to sanitize the input before inserting them to database.
Sample standard escaping:
$comprating = mysqli_real_escape_string($comprating) before executing a query that uses $comprating
Hi here is the objected oriented method and also its secure because data binding is used in mysqli. I recommend to use this.
if (isset($_POST['submitbutton'])) {
$comprating = $_POST['inputbox'];
$mysqli = new mysqli("localhost", "root", "", "test_db");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $mysqli->prepare("INSERT INTO Ratings (Company,Score) VALUES (?, ?)");
$stmt->bind_param($comprating, 1);
/* execute prepared statement */
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
/* close statement and connection */
$mysqli->close();
}
feel free to ask any questions if you have..
I'm making a small project and I'm having some trouble with a php script. Basically, when they enter the text then click 'Enter' It loads to the 'insert.php'. The thing is, if they just visit the insert.php page without going to the main page It enters a plan table which could cause big problems.
Code:
$con=mysqli_connect("localhost","info","info","info");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
Can you help me fix this problem as It could cause a lot of troubles.
First you need to validate your $_POST variables by using isset().
If they are not submitted from a form, $_POST will be empty. Meaning that when a user try to type in the url, there won't be any post data and your SQL queries won't run.
2nd, you are subject to SQL injection since you are not escaping the content.
I'd suggest escaping each variable by using a prepared statement or mysqli_real_escape_string (less secure but better than nothing).`
if ( isset($_POST) && !empty($_POST['firstname']) && !empty($_POST['lastname']) && !empty($_POST['age'])) {
$con=mysqli_connect("localhost","info","info","info");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//simple example of escaping variables - BUT NOT AS SECURE AS PREPARED STATEMENT!!
$firstname = $con->real_escape_string($_POST['firstname']);
$lastname = $con->real_escape_string($_POST['lastname']);
$age = $con->real_escape_string($_POST['age']);
//With MySQLi it is best practice to use `prepere`, `bind_param` and `execute:
//or use PDO.
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$firstname','$lastname','$age')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
}
Lastly, you were missing the single quotes inside your $_POST variables.
Hope this helps!
This is pretty simple.
if(isset($_POST)):
//all of your code here
endif;
You have to check if $_POST exists to trigger your sql request
if (isset($_POST)){
//script
}
One of the first things that I see right off the top of my head is the fact that you are not checking to ensure that something has infact been typed Into your input box that passes the data to your other file. You can try to use isset() or array_key_exist(). Not to mention these are things that you should be doing anyway.
Okay, Here's my problem. I am trying to make a posting script for my website. However this script is not working; the script is below:
<?php
// Make sure the user is logged in before going any further.
if (!isset($_SESSION['user_id'])) {
echo '<p class="login">Please log in to access this page.</p>';
exit();
}
else {
echo('<p class="login">You are logged in as ' . $_SESSION['username'] . '. Log out.</p>');
}
// Connect to the database
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (isset($_POST['submit'])) {
// Grab the profile data from the POST
$post1 = mysqli_real_escape_string($dbc, trim($_POST['post1']));
$query = "INSERT INTO ccp2_posts ('post') VALUES ('$post1')";
$error = false;
mysqli_close($dbc);
?>
<form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<legend>Posting</legend>
<label for="post">POST:</label>
<textarea rows="4" name="post1" id="post" cols="50">Write your post here...</textarea><br />
<input type="submit" value="submit" name="submit" />
</form>
</div>
<?php
include ("include/footer.html");
?>
</body>
</html>
Nothing shows up in the database when I submit the form. Help would be amazing. Thanks.
You haven't executed the query. All you've done is opened a connection, defined the query string and closed the connection.
Add:
if(msyqli_query($dbc, $query)) {
// Successful execution of insert query
} else {
// Log error: mysqli_error($dbc)
}
after this line:
$query = "INSERT INTO ccp2_posts ('post') VALUES ('$post1')";
Update:
Started editing but had to leave... As other answerers have pointed you need to either quote the post column with a backick or remove the single quote that you currently have altogether. The only case where you need to use backticks to escape identifiers that are one of the MySQL Reserved Words.
So the working version of your query would be:
$query = "INSERT INTO ccp2_posts (post) VALUES ('$post1')";
You may have other problems, but your SQL is bad. You can't use single quotes around 'post'. You want backticks or nothing:
INSERT INTO ccp2_posts(post) VALUES ('$post1')
You missed
mysqli_query($dbc,$query);
In your code,
$query = "INSERT INTO ccp2_posts ('post') VALUES ('$post1')";
mysqli_query($dbc,$query);
Your query is not quite right:
$query = "INSERT INTO `ccp2_posts` (`post`) VALUES ('$post1')";
Note that those are backticks `, not single-quotes. This is very important! Backticks are used to name databases, tables and column names, and in particular it means you don't have to remember the extensive list of every single reserved word. You could call your column `12345 once I caught a fish alive!` if you want to!
Anyway, more importantly, you aren't actually running your query!
mysqli_query($dbc,$query);
You are not submiting to the database using, for example, the mysql_query() function.
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])."')");