This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 2 years ago.
I'm attempting to insert some data into a table using mysqli functions.
My connection works fine using the following:
function connectDB(){
// configuration
$dbuser = "root";
$dbpass = "";
// Create connection
$con=mysqli_connect("localhost",$dbuser,$dbpass,"my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return false;
}else{
echo '<br />successfully connected<br />';
return $con;
}
}
But when I attempt to run my insert function I get nothing in the database.
function newUserInsertDB($name,$email,$password){
$con = connectDB();
// Prepare password
$password = hashEncrypt($password);
echo $password . "<br />";
// Perform queries
mysqli_query($con,"SELECT * FROM users");
mysqli_query($con,"INSERT INTO users (name,email,password,isActivated) VALUES ($name,$email,$password,0)");
// insert
mysqli_close($con);
}
I have been looking through the list of mysqli functions for the correct way to give errors but they all seem to be regarding the connection to the DB, not regarding success of an insert (and I can clearly see in my DB that it is not inserting.)
What would be the best way to debug? Which error handling shall I use for my insert?
I've tried using mysqli_sqlstate which gives a response of 42000 but I cannot see any syntax errors in my statement.
As mentioned in my comment, you would be better off using a prepared statement. For example...
$stmt = $con->prepare(
'INSERT INTO users (name, email, password, isActivated) VALUES (?, ?, ?, 0)');
$stmt->bind_param('sss', $name, $email, $password);
$stmt->execute();
Using this, you don't have to worry about escaping values or providing quotes for string types.
All in all, prepared statements are much easier and much safer than attempting to interpolate values into an SQL string.
I'd also advise you to pass the $con variable into your function instead of creating it within. For example...
function newUserInsertDB(mysqli $con, $name, $email, $password) {
// Prepare password
$password = hashEncrypt($password);
// functions that "echo" can cause unwanted side effects
//echo $password . "<br />";
// Perform queries
$stmt = $con->prepare(
'INSERT INTO users (name, email, password, isActivated) VALUES (?, ?, ?, 0)');
$stmt->bind_param('sss', $name, $email, $password);
return $stmt->execute(); // returns TRUE or FALSE based on the success of the query
}
The quotes are missing from the mysql statement from around the values. Also, you should escape the values before inserting them into the query. Do this way:
mysqli_query($con,"INSERT INTO users (name,email,password,isActivated) VALUES ('".
mysqli_real_escape_string($con,$name)."','".
mysqli_real_escape_string($con,$email)."','".
mysqli_real_escape_string($con,$password)."',0)");
Regards
Related
I am trying to insert test data into a MySQL database using the below lines which works fine so far.
1) How can I check whether the email already exists in the database and if, echo a message? I saw references here to the use of WHERE EXISTS or mysqli_num_rows but I am not sure which and how to apply here - in combination with binding parameters.
2) I came across unset($username, $password, $database); to make this query more secure. Is that something that is needed / useful here and if, where should I put it ?
My PHP:
$conn = new mysqli($host, $username, $password, $database);
if($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare("INSERT INTO cust (email, pw) VALUES (?, ?)");
$stmt->bind_param("ss", $email, $hashPw);
$email = "me#mail.com";
$pw = "testpw12345";
$hashPw = password_hash($pw, PASSWORD_DEFAULT);
$stmt->execute();
echo "Success";
$stmt->close();
$conn->close();
An alternative to the solution proposed already.
$stmt = $conn->prepare("SELECT COUNT(1) FROM cust WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$emailExists = $stmt->get_result()->fetch_row()[0];
if ($emailExists) {
echo "This email address is already in use";
} else {
// continue with insert code
}
This approach does not require you to close the statement. Once you execute get_result the statement data is fetched in full.
This solution also has a potential performance benefit. If your table contains many columns with many data, then fetching that data just to check if a record exists is a waste of CPU. Simply fetch COUNT(1) and check the single column of the single returned record. If it is 0, the value is falsish, if it is more than your if statement will evaluate to true and a message will be displayed. I would also strongly recommend to structure your code in such a way that you rarely have to use exit.
To check if the email already exists in the database, just try to select a row with it in:
$stmt = $conn->prepare("SELECT * FROM cust WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
echo "This email address is already in use";
exit;
}
$stmt->close();
// continue with insert code
In terms of your other questions, I don't see any reason to unset variables, and using prepared queries and password_hash gives you about as good protection as you can get.
Please i have a little problem here. the below code i wrote was meant to insert into two tables simultaneously but it those not work. but if i remove the second INSERT the first INSERT will work dont know whats wrong. ITs meant insert in the first table and also collect the last Insert Id of the First table to the Second table. What did i do wrong
<?php
$english_name = $_POST['EnglishName'];
$tel_number = $_POST['TelNumber'];
$email_address = $_POST['EmailAddress'];
$gender = $_POST['Gender'];
$age = $_POST['Age'];
$region = $_POST['Region'];
mysql_connect("localhost", "root", "") or die ('Error: ' . mysql_error());
mysql_select_db("fruitmarket");
$query="INSERT INTO data (english_name, tel_number, email_address, gender, age, region) VALUES (";
$query.="'".$english_name."', ";
$query.="'".$tel_number."', ";
$query.="'".$email_address."', ";
$query.="'".$gender."', ";
$query.="'".$age."', ";
$query.="'".$region."')";
$query .= "INSERT INTO data_category (id, english_name)
VALUES (LAST_INSERT_ID(), '$english_name');";
mysql_query($query) or die ('Error updating database');
echo "Record is inserted.";
?>
its almost 2018, so please stop using depreciated and removed mysql_* functions use PDO/mysqli with prepared statements.
I have re-written your code with prepared statements, please follow these links :
Why shouldn't I use mysql_* functions in PHP?
How can I prevent SQL injection in PHP?
Prepared statements
<?php
$servername = "localhost";
$username = "username";
$password = "";
$dbname = "fruitmarket";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = "INSERT INTO data (english_name,tel_number,email_address,gender,age,region) VALUES(?,?,?,?,?,?)";
$sql = $conn->prepare($stmt);
$sql->bind_param("ssssis", $english_name, $tel_number, $email_address, $gender, $age, $region);
if ($sql->execute()) {
$id = $sql->insert_id;
$insert = $conn->prepare("INSERT INTO data_category (id, english_name) VALUES(?,?)");
$insert->bind_param("is", $id, $english_name);
if ($insert->execute()) {
echo "data inserted successfully";
} else {
printf("Errormessage: %s\n", $mysqli->error);
}
} else {
printf("Errormessage: %s\n", $mysqli->error);
}
A prepared statement is a feature used to execute the same (or similar) SQL statements repeatedly with high efficiency.
Prepared statements basically work like this:
Prepare: An SQL statement template is created and sent to the
database. Certain values are left unspecified, called parameters
(labeled "?"). Example: INSERT INTO myTabvle VALUES(?, ?, ?)
The database parses, compiles, and performs query optimization on
the SQL statement template, and stores the result without executing
it
Execute: At a later time, the application binds the values to the
parameters, and the database executes the statement. The application
may execute the statement as many times as it wants with different
values Compared to executing SQL statements directly, prepared
statements have three main advantages:
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.
I tested the above code and noticed you just need just to add and change some code see my below example
<?php
$english_name = $_POST['EnglishName'];
$tel_number = $_POST['TelNumber'];
$email_address = $_POST['EmailAddress'];
$gender = $_POST['Gender'];
$age = $_POST['Age'];
$region = $_POST['Region'];
mysql_connect("localhost", "root", "") or die ('Error: ' . mysql_error());
mysql_select_db("fruitmarket");
$query="INSERT INTO data (english_name, tel_number, email_address, gender, age, region) VALUES (";
$query.="'".$english_name."', ";
$query.="'".$tel_number."', ";
$query.="'".$email_address."', ";
$query.="'".$gender."', ";
$query.="'".$age."', ";
$query.="'".$region."')";
mysql_query($query) or die ('Error updating database');
echo "Record is inserted.";
$query= "INSERT INTO data_category (id, english_name)
VALUES (LAST_INSERT_ID(), '$english_name');";
mysql_query($query) or die ('Error updating database');
echo "Record is inserted.";
?>
test it to check if it will work
I'm totally PHP beginner, and I'm trying to insert variables in a database in PHP and MySQL.
This is my code:
$link = mysql_connect('localhost','','','onlynews') or die('Cannot connect to the DB');
mysql_select_db('TEST',$link) or die('Cannot select the DB');
$strSQL = "INSERT INTO news(id, title,photo,url,source, at) VALUES('$x','$title','$url','$imgurl ','$source','$at')";
mysql_query($strSQL) or die(mysql_error());
The problem is it is doing: NOTHING! No Entries at all, Nothing changes in the database.
-How can I fix this?
-Do I have to write codes to prevent SQL Injection, even if the variables are coming from an API, not from users?
You have to execute your query using $conn->query($sql);.
However, to avoid SQL injections you should definitely use prepared statements or at least $conn->real_escape_string() to escape the values in your SQL statement.
For example, this is your code using prepared statements:
$servername = "localhost";
$username = "";
$password = "";
$dbname = "onlynews";
$tableName = "news";
$conn = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn->prepare("INSERT INTO news (id, title, photo, url, source, at)
VALUES (?, ?, ?, ?, ?, ?)");
$stmt->bind_param('ssssss', $thetitle, $urlToImage, $theurl, $thesource, $thetime);
$stmt->execute();
$stmt->close();
You should also add some error checking, since $conn->prepare() and $stmt->execute() may fail (and return false). Of course, establishing the connection to the database during the construction of $conn could also fail, which can be checked using $conn->connect_error.
The users enter their name and number in the textfields. The this information is passed then sent to the data.php file where I am trying to get it to write to my database. The data base name is called hello.
<!-- connect to database -->
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "hello";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo "wooo connected";
}
//<!-- post added information to database -->
if ($_POST['name']) {
if ($_POST['number']) {
$sql = "INSERT INTO hello (id, name, number)
VALUES ('', '$_POST['name']', '$_POST['number'')";
if(mysqli_query($conn, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
} ?>
From looking at my code I believe the issue is with this line.
$sql = "INSERT INTO hello (id, name, number)
VALUES ('', '$_POST['name']', '$_POST['number']')";
There is a blank left at the star for the auto incremented id that I have set in phpmyadmin.
I can hard code an entry such as:
$sql = "INSERT INTO hello (id, name, number)
VALUES ('', 'john', '12345)";
These hard coded entries are put into the database but i can't get the user entered data to go in.
Create variables for the $_POST values and add the vars for ease of code understanding:
$name = $_POST['name'];
$number = $_POST['number'];
$sql = "INSERT INTO hello (id, name, number) VALUES ('', $name, $number)";
One reason your code may not be working because you have the single quotes around the $_POST values, then you can also do what Jasbeer Rawal recommended.
UPDATE
Based on the kind comments... I would personally take a different approach to adding the data to your database, instead use prepared statements. I use MySQLi, but you can also use PDO.
Start by creating your connection:
<?php
define("HOST", "localhost");
define("USER", "");
define("PASSWORD", "");
define("DATABASE", "");
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
if ($mysqli->connect_error) {
echo "There was a slight problem, please contact your webmaster before continuing.";
exit();
}
Then when the user submits the form handle it:
if(isset($_POST['submit']
{
$name = $_POST['name'];
$number = $_POST['number'];
if ($stmt = $mysqli->prepare("INSERT hello (name, number) VALUES (?, ?)"))
{
$stmt->bind_param("ss", $name, $number);
$stmt->execute();
$stmt->close();
}
else
{
echo "ERROR: Could not prepare SQL statement.";
}
}
This will add $name and $number and your ID role has to be a primary role and set to auto_increment. IDs will be automatically generated.
You're about to go down a slippery slope using mysqli. I'd recommend trying to learn to use PDO for making queries. Right now, someone could easily put SQL into the name POST data and actually do damage to your database.
Anyways, your problem at hand, you have a missing bracket and one issue:
VALUES ('', '$_POST['name']', '$_POST['number'')";
It won't work as intended with nested single quotes.
VALUES ('', '$_POST[name]', '$_POST[number]')";
Remove single quotes from $_POST['name'] and $_POST['number'] as below
$sql = "INSERT INTO hello (id, name, number)
VALUES ('', $_POST['name'], $_POST['number'])";
Your insert code be like this
$sql = "INSERT INTO hello (id, name, number)
VALUES ('','{$_POST['name']}', '{$_POST['number']}')";
Then your value will be in database
If field id is primary key and auto increment then your insert statement should be like
Try this:
$sql = "INSERT INTO hello ( name, number)
VALUES ('{$_POST['name']}', '{$_POST['number']}')";
I have a database running on my server with phpmyadmin but I can't connect with it. Here is an example:
$user_name = "xxxxx";
$password = "xxxxx";
$database = "xxxxx";
$host = "db.xxxx.nl";
$db_handle = mysql_connect($host, $user_name, $password);
$db_found = mysql_select_db($database);
But this doesn't seem to work. If I try to insert some values into a table it still stays empty.
$sql = "INSERT INTO tbl_forum
(
title,
name,
content,
lastname,
post_image
)
VALUES
(
'{$_POST['contactsubject']}',
'{$_POST['contactname']}',
'{$_POST['contactmessage']}',
'{$_POST['contactlastname']}',
'{$_FILES["contactBrowse"]["name"]}'
)";
Am I doing something wrong?
I'm going to completely rewrite your code. As you are clearly new to databases within PHP, there is absolutely no reason not to use the new mysqli API.
Your connection should look something like this;
$mysqli = new mysqli($host,$user_name,$password,$database);
if ($mysqli->connect_errno) echo "Failed to connect to MySQL: " . $mysqli->connect_error;
This will create a new database object called $mysqli (or you can call it what you like, such as $db).
You can then prepare your SQL statement and execute it. In the code below, we have 5 parameters that are represented in the SQL as ?, and then we bind the variables to those 5 parameters. The first argument in bind_param tells the API the 5 parameters are 5 strings (hence s x5). For integers, use i;
if($query = $mysqli->prepare("INSERT INTO tbl_forum (title,name,content,lastname,post_image) VALUES (?,?,?,?,?)")) {
$query->bind_param('sssss',$_POST['contactsubject'],$_POST['contactname'],$_POST['contactmessage'],$_POST['contactlastname'],$_FILES["contactBrowse"]["name"]);
$query->execute();
}
else {
echo "Could not prepare SQL: " . $mysqli->error;
}
Assuming all your connection information is correct, this will insert your information into the database as required.
Hope this helps.
I think the last value '{$_FILES["contactBrowse"]["name"]}' has some problem. Try this and get the sql after preparing(echo $sql;) to debug by your self.
$file_name = $_FILES["contactBrowse"]["name"];
$sql = "INSERT INTO tbl_forum
(
title,
name,
content,
lastname,
post_image
)
VALUES
(
'{$_POST['contactsubject']}',
'{$_POST['contactname']}',
'{$_POST['contactmessage']}',
'{$_POST['contactlastname']}',
'{$file_name}'
)";