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')
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am new to php and have written the following php script to write from a FORM. However, the database is not updating. I know that the database connection is okay. Any help would be appreciated.
$name = $_POST["name"];
$lastName = $_POST["last_name"];
$email = $_POST["email"];
$location = $_POST["location"];
$timestamp = date("Y-m-d H:i:s");
$sql = "INSERT INTO club.users (name, last_name, email, location, created_at) VALUES ('$name', '$lastName', '$email', '$location', '$timestamp')";
Try this
You have to use the SQL injection for security something like this
$conn->real_escape_string($_POST['name']);
Check your table name.I haven't use table name club.users before because it will display the error like table does't exist. Just use the table name club or users
Time to learn the PHP
https://www.w3schools.com/php/php_mysql_insert.asp
index.php
I hope your HTML code looks like this
<form action="register.php" method="POST" name="register">
<input type="text" name="name" placeholder="Name">
<input type="text" name="lastname" placeholder="Lastname">
<input type="email" name="email" placeholder="Email">
<input type="text" name="location" placeholder="Location">
<input type="submit" name="submit" value="Register">
</form>
Connection.php
If you are working on the local server the used root as username and password should be blank.
$servername = "localhost";
$username = "root";//if you are working on local server
$password = ""; //set blank if you are working on local server
$dbname = "myDB";//your database name
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
register.php
<?php
include('connection.php');// added the connection here
if (isset($_POST['submit'])) {
$name = $conn->real_escape_string($_POST["name"]);
$lastName = $conn->real_escape_string($_POST["lastname"]);
$email =$conn->real_escape_string($_POST["email"]);
$location = $conn->real_escape_string($_POST["location"]);
$timestamp = date("Y-m-d H:i:s");
$sql = "INSERT INTO club (name, lastname, email, location, created_at) VALUES ('$name', '$lastName', '$email', '$location', '$timestamp')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>
First of all define the db server connection in same php page or you may include the connection. Php file for this purpose.
Secondly it you wish to use MySQL db simple use musql_query($sql, $con) then write below lines of after inserting results.
Sorry I posted it from my mobile if you need I can post you entire code sample from my PC.
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.
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'))");
I have installed lamp on Ubuntu and everything is working fine i tried localhost/testphp() that works fine but when I put that code it shows the values if i echo them but it doesnt insert them in the db and it doesnt give error on mysql connection either.
using POST method to send form data
<form action="form.php" method="POST">
<label>Email:</label>
<input type="text" name="name">
<label>Password</label>
<input type="password" name="pass">
</form>
and here is the php code
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
echo "hello I am here !<br/>";
$con=mysqli_connect("localhost","root","123","login");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$name = $_POST['name'];
$password = $_POST['pass'];
echo " Name: ".$name." <br/>Password: ".$password;
mysqli_query($con,"INSERT INTO login_data (username, password) VALUES ('". $name ."', '". $password ."')");
//it doesnt insert the data
//how do i check the error of that query ?
mysqli_close($con);
?>
Help !
$sql="INSERT INTO login_data(username,password) values(".$_POST['name'].",".$_POST['password'].")";
mysqli_query( mysqli $link , string $query)
First connection, then the query. And use mysqli
$a=mysqli_query($con, $sql );
First of all you can enable PHP errors with your php.ini with :
display_errors = on
Or by using a .htaccess file.
Then the sql may be :
$sql = "INSERT INTO login_data(username, password) VALUES ('". $name ."', '". $password ."')";
As Don said, you use mysqli and then mysql. You have to use mysqli_query();
your sql statement is incorrect :
$sql="Insert into login_data(username,password) values("$name","$password")";
It should be
$sql="Insert into login_data(username,password) values("'".$name."'","'".$password."'")";
since $name and $password are predefined, you just need to pass them with proper quotes.