For example I have a html file like below:
<html>
<form action="insert.php" method="post">
Name:<input type="text" name="txtname" />
<input type="submit" name="but" value="Submit" />
</form>
</html>
and a php file like below:
<?php
if(isset($_POST['but']))
{
mysqli_query($con,"insert into student(Name) values(".$_POST["txtname"].")");
}
?>
My question is that if I can write $name=$post['txtname'] and I use $name in values part then dot
is not used but if I write directly post in values part then dot is used, why this dot used?
You have two possibilitys to do this...
First:
mysqli_query($con,"insert into student(Name) values(" . $_POST['txtname'] . ")");
// using single quotes instead of double quotes
Second
mysqli_query($con,"insert into student(Name) values({$_POST['txtname']})");
//dont use any dots but single quotes and simply add it to the string
Also you should care about some singlequotes to the content...
"... values('{$_POST['txtname']}')"
so it should be
mysqli_query($con,"insert into student(Name) values('{$_POST['txtname']}')");
and as in the comments pointed... you have injection problems and consider to solve this.
Your PHP
<?php
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'foobar');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $mysqli->prepare("INSERT INTO students ( Name ) VALUES ( ? )");
$stmt->bind_param('s', $_POST['txtname']);
/* execute prepared statement */
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
/* close statement and connection */
$stmt->close();
/* close connection */
$mysqli->close();
?>
You can use $name with and without dots, but $_POST['something'] is different in the way that the index has quotes. It will break your query.
It is not related to $_POST it is related to arrays
You could also write it like
mysqli_query($con,"insert into student(Name) values('{$_POST['txtname']}')");
On another note, you should not insert form input directly into the database.
Do some validation first.
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);
?>
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..
My php code doesn't seem to be working. Was functioning yesterday but I must have changed something and now it isn't. As far as I can tell it's the if($word) that's causing the problem. The else part functions and it's connecting with the mysql db but that one if statement does nothing.
Here's the php:
<?php
require('connect.php');
$word=$_POST['word'];
$submit=$_POST['submit'];
if($submit){
if($word){
mysql_query("INSERT INTO words (word) VALUES ($word)");
}
else{
echo "Enter a word.";
}
}
?>
and this is the html form:
<form name="form" id="form" method="post" action="index.php">
<p><label>Label</label></p>
<p><input type="text" name="word" id="word" maxlength="16"/></p>
<p><input type="submit" name="submit" id="submit" value="Save"/></p>
</form>
You should immediately stop using this code. It is vulnerable to SQL injection. You need to learn how to bind parameters to prevent this as well as use a non-deprecated API. I would also recommend that you check REQUEST_METHOD rather than if $_POST['word'] is set as it can be empty.
Since you don't have any type of error catch functions, it is difficult to tell what could be the problem. If I had to guess, it's probably because you're missing single quotes around your posted variable:
...INSERT INTO words (word) VALUES ('$word')...
Using parameters:
<?php
if( $_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['submit']) ) {
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'world');
/* check connection */
if (!$link) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = mysqli_prepare($link, "INSERT INTO words (word) VALUES (?)");
mysqli_stmt_bind_param($stmt, 's', $_POST['word']);
/* execute prepared statement */
mysqli_stmt_execute($stmt);
printf("%d Row inserted.\n", mysqli_stmt_affected_rows($stmt));
/* close statement and connection */
mysqli_stmt_close($stmt);
/* close connection */
mysqli_close($link);
}
?>
The documentation is a good place to start.
You most likely need to quote your $word value...
INSERT INTO words (word) VALUES ('$word')
As mentioned in the comments...
Why shouldn't I use mysql_* functions in PHP?
And don't forget about input sanitization.
How can I prevent SQL injection in PHP?
I'm using the following script which takes the data from a html form and stores in a Postgres DB. There is this pg_escape_string function which stores the value from the form to the php variable. Searching the web throughout, I found that pg_escape_string escapes a string for insertion into the database. I'm not much clear on this. What does it actually escaping? What actually happens when its said that a string is escaped?
<html>
<head></head>
<body>
<?php
if ($_POST['submit']) {
// attempt a connection
$dbh = pg_connect("host=localhost dbname=test user=postgres");
if (!$dbh) {
die("Error in connection: " . pg_last_error());
}
// escape strings in input data
$code = pg_escape_string($_POST['ccode']);
$name = pg_escape_string($_POST['cname']);
// execute query
$sql = "INSERT INTO Countries (CountryID, CountryName) VALUES('$code', '$name')";
$result = pg_query($dbh, $sql);
if (!$result) {
die("Error in SQL query: " . pg_last_error());
}
echo "Data successfully inserted!";
// free memory
pg_free_result($result);
// close connection
pg_close($dbh);
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Country code: <br> <input type="text" name="ccode" size="2">
<p>
Country name: <br> <input type="text" name="cname">
<p>
<input type="submit" name="submit">
</form>
</body>
</html>
Consider the following code:
$sql = "INSERT INTO airports (name) VALUES ('$name')";
Now suppose that $name is "Chicago O'Hare". When you do the string interpolation, you get this SQL code:
INSERT INTO airports (name) VALUES ('Chicago O'Hare')
which is ill-formed, because the apostrophe is interpreted as a SQL quote mark, and your query will error.
Worse things can happen, too. In fact, SQL injection was ranked #1 Most Dangerous Software Error of 2011 by MITRE.
But you should never be creating SQL queries using string interpolation anyway. Use queries with parameters instead.
$sql = 'INSERT INTO airports (name) VALUES ($1)';
$result = pg_query_params($db, $sql, array("Chicago O'Hare"));
pg_escape_string() prevent sql injection in your code