I have spent the last 2 days trying to create a form to enter data into an SQL database. The database is functional, the tables are made and I can enter data via MYSQL. I'm using 2 files, bidinput.html and bidentry.php
Bidinput.HTML:
<html>
<body>
<form action="bidentry.php" method="post">
Bidder: <input type="text" name="BidderNumber"><br>
Description: <input type="text" name="Description"><br>
Price: <input type="decimal" name="Price"><br>
Quantity: <input type="integer" name="Quantity"><br>
Lot: <input type="text" name="Lot"><br>
<input type ="submit">
</form>
</body>
</html>
bidentry.php:
<?php
######### From bidinput.html
$BidderNumber = $_POST['BidderNumber'];
$Description = $_POST['Description'];
$Price = $_POST['Price'];
$Quantity = $_POST['Quantity'];
$Lot = $_POST['Lot'];
########
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "abcd1234";
$dbname = "auction";
// Create connection
$mysqli = new mysqli($dbhost,$dbuser,$dbpass,$dbname);
// Check connection
if ($mysqli->connect_errno){
echo "Failed to connect to MySQL: " . $mysqli->connect_error;
}
else{
echo "Connected successfully";
$sql = "INSERT INTO Bids (BidderNumber,Description,Price,Quantity,Lot) VALUES ('$BidderNumber','$Description','$Price','$Quantity','$Lot')";
echo "Error: " . $sql . "<br>" . $mysqli->error;
}$mysqli->close();
?>
When I run click the submit button I get the following error:
Connected successfullyError: INSERT INTO Bids (BidderNumber,Description,Price,Quantity,Lot) VALUES ('202','candy','3','1','')
WARNING You need to protect yourself from SQL injection. You should be using prepared statements to shield yourself from SQL injection.
You are not actually running any queries with your current code.
You need to use mysqli query:
$mysqli->query($sql);
Prepared Statement Example
Here is an example of an INSERT with prepared statements based on your code:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli($dbhost,$dbuser,$dbpass,$dbname);
$stmt = $mysqli->prepare("INSERT INTO Bids (BidderNumber, Description, Price, Quantity, Lot) VALUES (?,?,?,?,?)");
$stmt->bind_param("sssss", $_POST['BidderNumber'], $_POST['Description'], $_POST['Price'], $_POST['Quantity'], $_POST['Lot']);
$stmt->execute();
$stmt->close();
Edit: Put this at the top of your PHP file:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
You don't want to display errors in production but in a dev environment it's ok.
You might want to check your PHP.INI file. At the very least log_errors should be on by default and errors would be logged in your apache error log.
Related
I have a problem with my code, I wanted to do that when I click on a checkbox and then on the acceptation button some information will be inserted into my sql database.
There is my code:
<form action="checkboxes.php" method="post">
<input type="checkbox" name="chk1"> 4K </input>
<input type="submit" name="Submit" value="Submit"></input>
</form>
<?php
/* Database connection */
$sDbHost = 'localhost';
$sDbName = 'testowanie';
$sDbUser = 'root';
$sDbPwd = '';
$Conn = mysql_connect ($sDbHost, $sDbUser, $sDbPwd);
mysql_select_db ($sDbName, $Conn)
$checkbox1 = $_POST['chk1'];
if ($_POST["Submit"]=="Submit") {
for ($i=0; $i<sizeof($checkbox1); $i++) {
$query="INSERT INTO cena (name) VALUES ('".$checkbox1[$i]."')";
mysql_query($query) or die (mysql_error() );
}
echo "Record is inserted";
}
?>
But when I click on the button this don't work and a text appears "Table 'testowanie.cena' doesn't exist" but the problem is that the table really exist.
So if someone can help me it will be great.
The name of the table is monitory, cena is a column in the table. There is no name column. So it should be:
$query="INSERT INTO monitory (cena) VALUES ('".mysql_real_escape_string($checkbox1[$i])."')";
You also need to use mysql_real_escape_string() to prevent SQL-injection. But it would be best if you converted to mysqli or PDO and used prepared queries, since the mysql extension is obsolete and has been removed from the current version of PHP.
I have this form:
<form action="contactus.php" method="post">
<select name="formTitle">
<option value="">Select...</option>
<option value="M">Mr</option>
<option value="F">Mrs</option>
</select>
<p><b>Name</b></p>
<input type="text" name="formName" maxlength="50"/>
<p><b>Enquiry</b></p>
<input type="text" name="formEnquiry" maxlength="500"/>
</select>
<p><input type="submit" name="formSubmit" value="Submit"/></p>
And I have a MySQL database (called 'contacts') with a table (called 'enquiries') with three columns; 'Title', 'Name', 'Enquiry'.
The database has no password or anything. It's just a localhost with a 'root' password.
What kind of PHP would I need to send the data from this HTML form to the MySQL database?
I can help you in this problem.
So, just add the following code to your php file contactus.php.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "contacts";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['formSubmit'])) {
$formTitle = $_POST['formTitle'];
$formName = $_POST['formName'];
$formEnquiry = $_POST['formEnquiry'];
$sql = "INSERT INTO enquiries (Title, Name, Enquiry) VALUES ('$formTitle', '$formName', '$formEnquiry')";
$conn->query($sql);
?>
I hope this will solve your problem.
SIMPLE ANSWER: MySQL
A LITTLE BIT MORE DEVELOPED ANSWER:
MySQL is in basic terms the combination of PHP and SQL to create an easy way to do various actions to a database, which include:
Create table
Query table
Update table
and much more
There are variations of MySQL, including MySQLi and MySQL (PDO).
an example of connecting to your database via MySQL (PDO) would be:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$myDB = "databasename";
try {
$conn = new PDO("mysql:host=$servername;dbname=$myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
//insert code there that you want to execute...
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
you mentioned that you don't have a password, so you might just leave the "password" slot empty ("") I suppose, though this is very insecure and I recommend you place a password.
In the code above, there is a comment that says:
//insert code there that you want to execute...
Here you would include code that would probably do actions similar to the ones mentioned above (query table, update table, etc). An example of code similar to that would be:
//htmlspecialchars takes out special characters that might
//exist in the posted information if someone were trying
//to hack your site via sql injection
$formTitle = htmlspecialchars($_POST['formTitle']);
$formName = htmlspecialchars($_POST['formName']);
$formEnquiry = htmlspecialchars($_POST['formEnquiry']);
$sql = "INSERT INTO enquiries (Title, Name, Enquiry) VALUES (formTitleBinded, formNameBinded, formEnquiryBinded)";
$sqlPrepared = $conn->prepare($sql);
$sqlPrepared->bindParam(':formTitleBinded',$formTitle);
$sqlPrepared->bindParam(':formNameBinded',$formName);
$sqlPrepared->bindParam('formEnquiryBinded',$formEnquiry);
$sqlPrepared->execute();
The previous code both sanitizes your input and inserts a row into your table with that information.
Let me know if that helped!
EDITED: My answer has been edited with parameter binding included to prevent SQL Injection.
I've been using php and mysql for my computing project and I've just run into this small problem. I've tried countless numbers of variations to this line of code but I always seem to receive an SQL Error.
Background Information:
HTML Document that contains a form, allowing the Admin to upload an image path, a name for the photo and a comment as well
PHP Document containing SQL that runs the code for this. I've worked out how to insert either an image path, a name or a comment but not all three at once...
Here's the line of code that causes the problem, specifically inserting the data into the database.
$sql="INSERT INTO image_tbl (image, name, comment) VALUES ('{$_POST{[ VALUES GO HERE, WHAT SYNTAX/HOW??? ]}')";
The HTML Form is here (for anyone interested):
<form action="insertTest.php" method="POST" enctype="multipart/form-data">
Image: <input type="text" name="image" /><br>
Name: <input type="text" name="name" /><br>
Comment: <input type="text" name="comment" /><br>
<input type="submit">
</form>
PHP Doc (whole upload file, quite small, changed password for security xD):
<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "admin_db";
// Create connection
$conn = new mysqli($servername = "localhost", $username = "root", $password = "password", $dbname = "admin_db");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql="INSERT INTO image_tbl (image, name, comment) VALUES ('{$_POST{[]}')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
$image = $_POST['image'];
$name = $_POST['name'];
$comment = $_POST['comment'];
$sql="INSERT INTO image_tbl (image, name, comment) VALUES ('$image', '$name', '$comment')";
you can set variables to the associative array (with name from html form) and include each in the sql query. Something like this:
$image = $_POST['image'];
$name = $_POST['name'];
$comment = $_POST['comment'];
$sql="INSERT INTO image_tbl (image, name, comment) VALUES ('$image','$name','$comment')";
Separate your variables $imgpath=$_POST["path"]; $imgname=$_POST["name"]; $imgcomment=$_POST["comment"]; now insert into table.... INSERT INTO imgtable(path,name,comment) VALUES('$imgpath','$imgname','$imgcomment')
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.'")';
I'm having trouble getting a practice signup form to submit data to my database ...
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
$name = $email = $password = "";
?>
<form method="post">
Name: <input type="text" name="name">
<br><br>
E-mail: <input type="text" name="email">
<br><br>
Password: <input type="text" name="password">
<br><br>
<input type="submit" value="Submit" name="submit">
</form>
<?php
if(isset($_POST['submit'])){
$name = fix_input($_POST["name"]);
$email = fix_input($_POST["email"]);
$password = fix_input($_POST["password"]);
mysqli_connect("localhost","username","password","dbname") or die(mysql_error());
mysql_query("INSERT INTO ('username','password') VALUES ('$name', md5('$password'))");
Print "You've been signed up successfully"; }
function fix_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
</body>
</html>
In addition to Ugur's answer, you are mismatching mysqli commands and mysql commands. Here's how to do this in an object oriented fashion:
// create mysqli database object
$mysqli = new mysqli_connect("localhost","username","password","database");
// store your query in a variable. question marks are filled by variables
$sql = "INSERT INTO table_name ('username','password') VALUES (?,?)";
// prepare command uses $sql variable as query
$stmt = mysqli->prepare($sql);
// "ss" means your 2 variables are strings, then you pass your two variables.
$stmt->bind_param("ss",$name,md5($password));
// execute does as it seems, executes the query.
$stmt->execute();
// then print your success message here.
Using prepared statements removes the need to sanitize user input, as harmful input is not substituted into the query directly. For more reading:
http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
There are some good tips for using prepared statements in many different scenarios, as well as towards the bottom, there is an explanation on how prepared statements prevent SQL injection.
Missing table name
mysql_query("INSERT INTO ...... ('username','password') VALUES ('$name', md5('$password'))");
You're mixing mysql_* with mysqli_* functions, i.e.: mysqli_connect and mysql_query and you're wrapping your column names in quotes, plus you're missing the table name to insert into.
Try the following, fixed code:
if(isset($_POST['submit'])){
$name = fix_input($_POST["name"]);
$email = fix_input($_POST["email"]);
$password = fix_input($_POST["password"]);
mysqli_connect("localhost","username","password","dbname") or die(mysql_error());
mysqli_query("INSERT INTO `your_table` (`username`,`password`) VALUES ('$name', md5('$password'))");
Print "You've been signed up successfully"; }
You're also using password storage technology that dates back to 1996. MD5 is no longer considered safe to use.
I suggest you look into PHP's password function: http://php.net/password
And if you're having problems with your fix_input() function, you should consider using the mysqli_real_escape_string() function.
then setting up a DB connection while passing a variable to it.
$DB_HOST = "xxx";
$DB_NAME = "xxx";
$DB_PASS = "xxx";
$DB_USER = "xxx";
$db = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($db->connect_errno > 0) {
die('Connection failed [' . $db->connect_error . ']');
}
and instead of using:
$name = fix_input($_POST["name"]);
use the following:
$name= mysqli_real_escape_string($db, $_POST['name']);
and do the same for the rest.
you don't have table name in your query! also do not use quotation in your column name :)
you have mixed up mysqli and mysql.
Change
mysql_query("INSERT INTO ('username','password') VALUES ('$name', md5('$password'))");
to
mysqli_query("INSERT INTO yoour_table(username',password) VALUES ('$name', md5('$password'))");