Trying to pass user input into database [duplicate] - php

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 3 years ago.
So I'm working with XAMPP and I was following this tutorial on how to set up a website. Right now the webpage is takes a first name and last name. Once you submit it should place those into the database. I'm getting this error every time I try to test it: Connected "successfullyError: INSERT into 'user'('fname', 'lname') VALUES ('abc','xyz') You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''user'('fname', 'lname') VALUES ('abc','xyz')' at line 1"
Here's what the html looks like:
<!DOCTYPE html>
<html>
<body>
<form action="submit.php" method="post">
First Name:<br>
<input type="text" name="firstname">
<br>
Last Name:<br>
<input type="text" name="lastname">
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
And here is the file that has the php code to connect the page to the database. I am new to php and I tried to locate the syntax error, but to no avail.
<?php
$x = $_POST['firstname'];
$y = $_POST['lastname'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db1";
//create connection
$conn = new mysqli($servername, $username, $password, $dbname);
//Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql = "INSERT into 'user'('fname', 'lname') VALUES ('$x','$y')";
if($conn->query($sql) === TRUE)
{
echo "That's going on your permanent record loser";
}
else { echo "Error: " . $sql . "<br>" . $conn->error; }
$conn->close();
?>

The only problem that I see that you use a single quote ' to your table and column instead of using "`". The single quote are use as string delimiter.
Try changing this part
'user'('fname', 'lname')
into
`user`(`fname`, `lname`)

Related

Trouble inserting data into MySQL database via html and php form [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Reference - What does this error mean in PHP?
(38 answers)
How to enable PHP short tags?
(21 answers)
Closed 4 years ago.
I’m having trouble successfully INSERTing information into a database I created. I tried several different alternatives I found on the internet and I was hoping someone could help. From what I can tell I’m connecting to the database without a problem, the data is just not being submitted into it. I kept it very simple just for testing purposes to no avail. It’s probably something simple that a more experienced programmer could help out easily.
I’m running a server through A2Hosting that is running
“Server version: 10.2.18-MariaDB-cll-lve - MariaDB Server”
“Php version: 5.6.30”
Here is the code I have running(for security I’m substituted in info):
I did the “dummy checks” with data base table and field names, username and case of letters too.
config.php:
<?php
$host = "server.a2hosting.com";
$userName = "username";
$password = "password";
$dbName = "Database";
// Create database connection
$conn = mysql_connect ($host, $userName, $password, $dbName);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
Html file - index.html:
<html><body> <form method="post" action="index.php"> <input type='text' name='first_name' id='first_name'> <input type='text’ name='last_name'> <input type=submit value="Submit"> </form>
</body></html>
Php file - index.php
<? include("config.php");
// has the access info for the DB, how to connect
// create a variable
$first_name=$_POST['first_name'];
$last_name=$_POST['last_name'];
$query = "INSERT INTO Contact_Information (HOW_name, address) VALUES
('$first_name', '$last_name'); "; mysql_query($query); mysql_close();
?>
<html> <head> <meta HTTP-EQUIV="REFRESH" content="0; url=form1.php">
</head> </html>
$query = "INSERT INTO contact_inforamarion(how_name, address) VALUES('$first_name', '$last_name');";
$result = mysqli_query($conn, $query);
Query and result should be like this.

How to use Var Dump to update SQL record using $_POST [duplicate]

This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 5 years ago.
I want to send input data from a form on publish.php to updateCopy.php that will then update the "postCopy" column on my SQL database.
Here's my code so far:
publish.php
<form action="\.\.\updateCopy.php" method="post" id="newCopy">
<input type="text" name="postCopy">
<input type="submit">
</form>
updateCopy.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "main";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE posts SET postCopy= var_dump ($_POST["postCopy"]); WHERE id=123456789";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
When I attempt to run this process I get the following error:
Parse error: syntax error, unexpected '"', expecting '-' or identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING)
Is anyone able to tell me how I can effectivley use var_dump ($_POST["postCopy"]); to include the updated postCopy info and then update my SQL db?
Don't know why are you trying to use var_dump to execute the SQL statement, that makes no sense, and then a ; too that will terminate the sql, if you talk about the error
$sql ="UPDATE posts SET postCopy= var_dump ($_POST["postCopy"]); WHERE id=123456789";
change it to
$sql ="UPDATE posts SET postCopy= '".$_POST['postCopy']."' WHERE id=123456789";
and the error will go away.
Note : This is not the optimal way and an open invite to sql injection, you should use prepared statements and parameterized queries either use PDO or MYSQLI

Validating email for a specific username using php and MYSQL [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
So, I am trying to validate whether username and email entered by a user in an html form are correct according to Database
I have a database called testing and a table called info which has two fields:
name and email.
this is the code
<html>
<body>
<form action="conn.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname="testing";
$name=$_POST['name'];
$mail=$_POST['email'];
// Create connection
$conn1 = new mysqli($servername, $username, $password, $dbname);
$query='select email from info where name= "$name"';
$results = mysqli_query($conn1,$query);
$row= mysqli_fetch_assoc($results);
echo $row["email"];
$email=$row["email"];
if($mail==$email){
echo " correct values";
}
else
echo " incorrect";
//echo $name, $email;
// Check connection
//if ($conn1->connect_error) {
// die("Connection failed: " . $conn1->connect_error);
//}
//echo "Connected successfully";
$conn1->close();
?>
but the result is always incorrect. The values that i enter in the text boxes match the values in the database.
You should use placeholders, the code would be something like this:
$query = 'SELECT emal FROM info WHERE name = ?';
$stmt = mysqli_stmt_prepare($conn1, $query);
mysqli_stmt_bind_param($stmt, 's', $name);
mysqli_stmt_execute($stmt);
$results = mysqli_stmt_get_result($stmt);
For better readable code, read up on the object-oriented mysqli-interface, or better yet use PDO.
alternatively you can use string concatenation like
Update this line
$query='select email from info where name= "$name"';
with
$query='select email from info where name= "'.$name.'" ';
or with
$query="select email from info where name= '".$name."' ";

HTML/PHP form doesn't insert data to MySQL Database [duplicate]

This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 1 year ago.
I am new to PHP, and I have been trying to make a small Homework Organiser Application.
The idea is that you can input a Subject and Description and it will be added to a MySQL Database (that's it for now).
I have created a html form:
<form action="insert.php">
<label for="subj">Subject:</label>
<br>
<input type="text" name="subj">
<br>
<label for="desc">Description:</label>
<br>
<input type="text" name="desc">
<br>
<input type="submit" value="Submit" name="submit">
</form>
and some php code:
<?php
$subject = $_POST['subj'];
$description = $_POST['desc'];
$subject = mysql_real_escape_string($subject);
$description = mysql_real_escape_string($description);
$dbhost = ''; //These are filled in actually
$dbuser = ''; //These are filled in actually
$dbpass = ''; //These are filled in actually
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'INSERT INTO organiser '.
'(subject,description) '.
'VALUES ('$subject', '$description')';
mysql_select_db(''); //These are filled in actually
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
?>
The problem is that the input from the Subject and Description boxes on the HTML form don't go into the MySQL Database.
However, If I set
'VALUES ('$subject', '$description')';
to
'VALUES ("test", "test")';
it works.
Any help is appreciated!
Thanks!
In addition to the answer already given in regards to missing dots for the concatenate:
Form method defaults to a GET method, if the method is omitted from the form tag.
You are using <form action="insert.php"> which is equivalent to doing
<form action="insert.php" method = "get"> which is not what you want nor required.
Change it to
<form action="insert.php" method="post">
since you are using POST variables.
That is the contributing reason why 'VALUES ("test", "test")'; works and not the other way, since both of these variables $subject - $description, are based on your POST variables:
$subject = $_POST['subj'];
$description = $_POST['desc'];
You can either do
$sql = "INSERT INTO organiser (subject,description) VALUES ('$subject', '$description')";
as stated in a comment.
or
$sql = "INSERT INTO organiser (subject,description) VALUES ('".$subject."', '".$description."')";
Add error reporting to the top of your file(s)
error_reporting(E_ALL);
ini_set('display_errors', 1);
which would have signaled errors found in your code.
http://php.net/manual/en/function.error-reporting.php
Yet, your method is open to SQL injection. Use mysqli_* with prepared statements, or PDO with prepared statements.
Use a mysqli prepared statements method; it's safer.
<?php
$DB_HOST = "xxx"; // replace with your own
$DB_NAME = "xxx";
$DB_USER = "xxx";
$DB_PASS = "xxx";
$conn = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($conn->connect_errno > 0) {
die('Connection failed [' . $conn->connect_error . ']');
}
// optional to check for empty fields
// if(isset($_POST['submit']) && !empty($_POST['subj']) && !empty($_POST['desc'])) {
if(isset($_POST['submit'])) {
$subject = stripslashes($_POST['subj']);
$description = stripslashes($_POST['desc']);
$stmt = $conn->prepare("INSERT INTO organiser (`subject`, `description`) VALUES (?, ?)");
$stmt->bind_param('ss', $subject, $description);
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
else{
echo "<h2>Success!</h2>";
}
$stmt->close(); // Statement
$conn->close(); // MySQLi
}
?>
Form: (new)
<form action = "insert.php" method = "post">
<label for="subj">Subject:</label>
<br>
<input type="text" name="subj">
<br>
<label for="desc">Description:</label>
<br>
<input type="text" name="desc">
<br>
<input type="submit" value="Submit" name="submit">
</form>
Your problem is because you are using single quotes in your $sql declaration,
$sql = 'INSERT INTO organiser '.'(subject,description) '.'VALUES ('$subject', '$description')';
When you use single quotes you are telling PHP that you would like everything within the quotes to be taken literally.
$age = 20;
$myAge = 'I am $age years';
echo $myAge;
This would echo I am $age years since you used single quotes.
However, if you used double quotes instead,
$age = 20;
$myAge = "I am $age years";
echo $myAge;
The output would be,
I am 20 years
Thus, your $sql statement should be (I write it on one line instead),
$sql = "INSERT INTO organiser (subject,description) VALUES ('$subject', '$description')";
^ ^
If you echo your $sql it would become something along the lines of,
INSERT INTO organiser (subject,description) VALUES ('Your subject', 'Your description')
Your use of single quotes within your SQL-statement is correct, you can read more about the subject here: When to use single quotes, double quotes and backticks
You forgot the dots around the variables and you can add some double quotes around that depending on the content of your variables :)
'VALUES ("'.$subject.'", "'.$description.'")';

Cannot INSERT data into mysql using php

I have been trying for two days now to figure this one out. I copied verbatim from a tutorial and I still cant insert data into a table. here is my code with form
<font face="Verdana" size="2">
<form method="post" action="Manage_cust.php" >
Customer Name
<font face="Verdana">
<input type="text" name="Company" size="50"></font>
<br>
Customer Type
<font face="Verdana">
<select name="custType" size="1">
<option>Non-Contract</option>
<option>Contract</option>
</select></font>
<br>
Contract Hours
<font face="Verdana">
<input type="text" name="contractHours" value="0"></font>
<br>
<font face="Verdana">
<input type="submit" name="dothis" value="Add Customer"></font>
</form>
</font>
<font face="Verdana" size="2">
<?php
if (isset($_POST['dothis'])) {
$con = mysql_connect ("localhost","root","password");
if (!$con){
die ("Cannot Connect: " . mysql_error());
}
mysql_select_db("averyit_net",$con);
$sql = "INSERT INTO cust_profile (Customer_Name, Customer_Type, Contract_Hours) VALUES
('$_POST[Company]','$_POST[custType]','$_POST[contractHours]')";
mysql_query($sql, $con);
print_r($sql);
mysql_close($con);
}
?>
This is my PHPmyadmin server info:
Server: 127.0.0.1 via TCP/IP
Software: MySQL
Software version: 5.5.27 - MySQL Community Server (GPL)
Protocol version: 10
User: root#localhost
Server charset: UTF-8 Unicode (utf8)
PLEASE tell me why this wont work. when I run the site it puts the info in and it disappears when I push the submit button, but it does not go into the table. There are no error messages that show up. HELP
I have improved a little bit in your SQL statement, stored it in an array and this is to make sure your post data are really set, else it will throw a null value. Please always sanitize your input.
in your Manage_cust.php:
<?php
if (isset($_POST['dothis']))
{
$con = mysql_connect ("localhost","root","password");
if (!$con)
{
die ("Cannot Connect: " . mysql_error());
}
mysql_select_db("averyit_net",$con);
$company = isset($_POST['Company'])?$_POST['Company']:NULL;
$custype = isset($_POST['custType'])?$_POST['custType']:NULL;
$hours = isset($_POST['contractHours'])?$_POST['contractHours']:NULL;
$sql = "INSERT INTO cust_profile(Customer_Name,
Customer_Type,
Contract_Hours)
VALUES('$company',
'$custype',
'$hours')
";
mysql_query($sql, $con);
mysql_close($con);
}
?>
First of all, don't use font tags...ever
Secondly, because of this line:
if (isset($_POST['dothis'])) {
It looks like your HTML and PHP are combined into one script? In which case, you'll need to change the action on the form to something like this:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
Plus, you can kill a bad connection in one line:
$con = mysql_connect("localhost","root","password") or die("I died, sorry." . mysql_error() );
Check your posts with isset() and then assign values to variables.
var $company;
if(isset($_POST['Company']) {
$company = $_POST['Company'];
} else {
$company = null;
}
//so on and so forth for the other fields
Or use ternary operators
Also, using the original mysql PHP API is usually a bad choice. It's even mentioned in the PHP manual for the API
Always better to go with mysqli or PDO so let's convert that:
//your connection
$conn = mysqli_connect("localhost","username","password","averyit_net");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sql = "INSERT INTO cust_profile (Customer_Name, Customer_Type, Contract_Hours)
VALUES ($company,$custType,$contractHours)";
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Assuming you set these
$stmt = mysqli_prepare($conn, $sql);
$stmt->execute();
$stmt->close();
Someone tell me if this is wrong, so I can correct it. I haven't used mysqli in a while.
Change the $sql to this:
$sql = "INSERT INTO cust_profile (Customer_Name, Customer_Type, Contract_Hours) VALUES ('".$_POST[Company]."','".$_POST[custType]."','".$_POST[contractHours]."')

Categories