Hi I'm pretty new to mysql and im trying to insert some data into a data base using INSERT the data is received from a HTML form
Inserting data
$q = "INSERT INTO 'customers'('firstname', 'lastname', 'email') VALUES ('$first, '$last', '$email')";
mysqli_query($dbc, $q);
Thats the INSERT function
Selecting data
$q = 'SELECT * FROM customers';
$r = mysqli_query($dbc, $q)
OR die
(mysqli_error());
echo 'customers';
while($row = mysqli_fetch_array ($r, MYSQL_ASSOC))
{
echo '<br />' .$row['firstname']. $row['lastname']. $row['email'];
}
Thats the SELECT function and how I'm displaying the database on a php page
No matter what tutorial or forum i look in i cant seem to work out why i can't add to or show the results!?
Don't use quotes to escape column or table names, use backticks instead. Quotes are string delimiters.
INSERT INTO `customers`(`firstname`, `lastname`, `email`)
VALUES ('$first', '$last', '$email')
And you should really consider using Prepared Statements to prevend SQL injections. But you absolutely must escape your user input. Otherwise your input can produce syntax errors too.
And as pointed out in the other answer - you did miss a quote too in your first parameter.
By enclosing the column and table names quotes you are specifying them in string. Use the code below
$q = "INSERT INTO customers(firstname, lastname, email)
VALUES ('$first', '$last', '$email')";
mysqli_query($dbc, $q);
Hope this helps you
Try with this...you have problem with the $first you have missed quote
$q = "INSERT INTO customers(firstname, lastname, email) VALUES ('$first', '$last', '$email')";
mysqli_query($q);
EDITED
Related
I have the follow php script for registering a user
<?php
require_once "setting.php";
extract($_REQUEST);
$link = mysqli_connect($dbHost, $dbUser, $dbPass, $dbName);
if (mysqli_connect_errno()){
echo "Connection failed".mysqli_connect_error();
}
$initQuery = "SELECT * FROM users WHERE email = ".$email;
$initResult = mysqli_query($link, $initQuery);
$dbResults = mysqli_fetch_array($initResult, MYSQLI_ASSOC);
if($dbResults == null ){
echo('in the if statement');
$userId = uniqid();
echo($userId);
$query = "INSERT INTO users(email, password, userId) VALUES ($email, $password, $userId )";
echo($query);
$addResult = mysqli_query($link, $query);
echo($addResult);
}
mysqli_free_result($initResult);
mysqli_free_result($addResult);
mysqli_close($link);
?>
The second mysqli_query is not adding a user, I've checked the syntax of the sql statement and it works fine. Does anyone have any ideas?
Also I was thinking about maybe trying to write a mysqli_multi_query to run both queries. I've read that the multi_query will return false if the first query fails, is there anyway to have it execute the second query if the first one fails and not execute the second query if the first one succeeds?
For the love of God, at least put the string values inside quotes if not use prepared statements
"INSERT INTO users(email, password, userId) VALUES ($email, $password, $userId)"
Is invalid. Those string values should be inside quotes
"INSERT INTO users(email, password, userId) VALUES ('$email', '$password', '$userId')"
Please read this before you implement the solution given above:
How can I prevent SQL injection in PHP?
At the very least, please escape the values with mysqli_real_escape_string
Use quotes for your values.
$query = "INSERT INTO users(email, password, userId) VALUES ('$email', '$password', '$userId' )";
$addResult = mysqli_query($link, $query);
If you are facing error than use die function to get the error detail.
$addResult = mysqli_query($link, $query) or die(mysqli_error($link));
It will show you the error also.
Hope this works:
$query = "INSERT INTO users (email, password, userId) VALUES ('$email', '$password', $userId)";
Give a space after table name and all the variables in single quote. :)
UPDATE
Space is not mandatory to give, but would be good for better coding :)
Try to put the values inside quotes.
$query = "INSERT INTO users(email, password, userId) VALUES ('$email', '$password', '$userId' )";
To understand why quotes are mandatory i give an example :).
Mysql supports SELECT from another table for inserted values like in the code below:
INSERT INTO users (email, password, userId)
VALUES
((SELECT email FROM user_info WHERE id = '$userId'),'$password','$userId'))
I am new to using MySQLi. I try to use MySQLi in order to insert data in my database. But does not work. Where may be the error?
echo 'connected';
$con = mysqli_connect("localhost",$username,$password,$database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// mysqli_select_db($con,"kraus");
$firstname = $_POST['uname'];
$lastname = $_POST['address'];
$age = $_POST['pass'];
$sql = "INSERT INTO registration('uname', 'address', 'password') VALUES ('$firstname', '$lastname', '$age')";
mysqli_query($con,$sql);
echo "1 record added";
mysqli_close($con);
Why is line this commented out? You are selecting the database in mysqli_connect("localhost","root","root","kraus") but it makes no sense why that is there:
// mysqli_select_db($con,"kraus");
Should you not have that commented like this?
mysqli_select_db($con,"kraus");
Also there is no space here between registration and the fields in (…) as well as the quotes around your fields:
$sql = "INSERT INTO registration('uname', 'address', 'password') VALUES ('$firstname', '$lastname', '$age')";
That should be like the following with a space added between the table name & the fields. And since there should just be no quotes around your field names so the final query should be this:
$sql = "INSERT INTO registration (uname, address, password) VALUES ('$firstname', '$lastname', '$age')";
Or perhaps have back ticks like this:
$sql = "INSERT INTO registration (`uname`, `address`, `password`) VALUES ('$firstname', '$lastname', '$age')";
Also, you should really refactor & cleanup your whole codebase like this:
// Set the connection or die returning an error.
$con = mysqli_connect("localhost","root","root","kraus") or die(mysqli_connect_errno());
echo 'connected';
// Select the database.
// mysqli_select_db($con, "kraus");
$post_array = array('uname','address','pass');
foreach ($post_array as $post_key => $post_value) {
$$post_key = isset($_POST[$post_value]) && !empty($_POST[$post_value]) ? $_POST[$post_value] : null;
}
// Set the query.
$sql = "INSERT INTO registration (uname, address, password) VALUES (?, ?, ?)";
// Bind the params.
mysqli_stmt_bind_param($sql, 'sss', $uname, $address, $pass);
// Run the query.
$result = mysqli_query($con, $sql) or die(mysqli_connect_errno());
// Free the result set.
mysqli_free_result($result);
// Close the connection.
mysqli_close($con);
echo "1 record added";
Note how I am using mysqli_stmt_bind_param and also setting an array of $_POST values & rolling throughout them. Doing those two basic things at least enforce some basic validation on your input data before it gets to the database.
You have quotes around the column names in your query. Maybe you meant to use backticks instead:
(`uname1`, `address`,...)
You are also vulnerable to sql injection. Look into mysqli prepared statements.
My MYSQLi query is not inserting properly into the database and I am not sure where the syntax error is. Please help!
$name = mysqli_real_escape_string($_POST['name']);
$mail = mysqli_real_escape_string($_POST['mail']);
$comment = mysqli_real_escape_string($_POST['comment']);
$postid = mysqli_real_escape_string($_POST['postid']);
mysqli_query($con, "INSERT INTO `comment` (name, mail, comment, post_id) VALUES ({$name}, {$mail}, {$comment}, {$postid})");
You need to surruound with quotes your strings in your query, only integer field can be inserted without quotes
mysqli_query($con, "INSERT INTO `comment` (name, mail, comment, post_id) VALUES ('$name', '$mail', '$comment', '$postid')");
Since you are already using mysqli I would rather use prepared statements instead of sanitize your variables and then insert in the database.
Try with:
mysqli_query($con, "INSERT INTO `comment` (name, mail, comment, post_id) VALUES ('".$name."', '".$mail."', '".$comment."', '".$postid."')");
It should work now..
Okay, so I'm updating my site from MySQL to MySQLi, which means I have to re-code some of the database stuff.
I looked on php.net on how to use MySQLi queries to insert data into a table and did exactly what they said to, but no luck.
Here's my connection variable:
$con = mysqli_connect("localhost", "username", "password", "database");
And here is the code to insert the data:
mysqli_query($con, "INSERT INTO users ('user', 'pass', 'email') VALUES ('$user', '$pass', '$email')");
It doesn't reply with any errors, and it just takes me to the intended landing page. It doesn't actually add the data to the table though.
Any ideas?
As answered above, removing the quotes from the column names will solve your problem:
mysqli_query($con, "INSERT INTO users (user, pass, email) VALUES ('$user', '$pass', '$email')");
But I also noted that your script is vulnerable against SQL injection attacks.
In MySQLi you can prepare your statements before execution, so you will be sure that no one will inject SQL commands in your database.
If you don't want to prepare each sql statements before execution, at least use the mysqli_real_escape_string function, that will protect your system against SQL injection too. Use like that:
mysqli_query($con, "INSERT INTO users (user, pass, email) VALUES ('" . mysqli_real_escape_string($user) . "', '" . mysqli_real_escape_string($pass) . "', '" . mysqli_real_escape_string($email) . "')");
remove single quotes from column names
mysqli_query($con, "INSERT INTO users (user, pass, email) VALUES ('$user', '$pass', '$email')");
OR
mysqli_query($con, "INSERT INTO users (`user`, `pass`, `email`) VALUES ('$user', '$pass', '$email')");
I'm having a little trouble with my insert statement this morning. Yes, I am using the deprecated mysql_query function. My insert statement looks as follows:
$query3 = "INSERT INTO ".$db_prefix ." offer_det
(fname, lname, 10k, 14k, 18k, 21k, 22k, 24k, 925, coins, bars)
VALUES '".$fname."', '".$lname."', '".$_10k."', '".$_14k."',
'".$_18k."', '".$_21k."', '".$_22k."', '".$_24k."',
'".$_925."', '".$coins."', '".$bars."')";
$result3 = mysql_query($query3);
My PHP form values are all the variables listed in the first part of the insert statement, 'fname', etc.
My variables are set to pull from the post and are listed as the values going into the insert.
I had to change the variables to underscore before they started, I guess PHP didn't like that.
My questions:
Are those 10k, 14k, etc, okay mysql table row names?
Is there an issue I'm missing here?
The datatype for fname and lname are varchar and for the 10k through bars are decimal (7,3).
The column name 925 must be quoted using backticks.
(`fname`, `lname`, `10k`, `14k`, `18k`, `21k`, `22k`, `24k`, `925`, `coins`, `bars`)
You may also want to consider changing the column names to something else to avoid further similar problems in the future.
You should quote the 925 column name, as per MySQL Schema Object names
So correctly:
$query3 = "insert into ".$db_prefix."offer_det (fname, lname, 10k, 14k, 18k, 21k, 22k, 24k, `925`, coins, bars)
values
('".$fname."', '".$lname."', '".$_10k."', '".$_14k."', '".$_18k."', '".$_21k."',
'".$_22k."','".$_24k."', '".$_925."', '".$coins."', '".$bars."')";
Another recommendation: you should escape the incoming strings, because SQL injection is a nasty thing to experience...
Use the QUERY as like follow..
$query3 = "insert into ".$db_prefix."offer_det (fname, lname, 10k, 14k, 18k, 21k, 22k, 24k, 925, coins, bars)
values ('$fname', '$lname', '$_10k', '$_14k', '$_18k', '$_21k', '$_22k',
'$_24k', '$_925', '$coins', '$bars')";
$query_exec=mysql_query($query3) or die(mysql_error());
And for inserting a variable you need to use single codes only..
Can I be bold and suggest a change in your implementation?
/// put your vars in an easier to use format
$insert = array(
'fname' => $fname,
'lname' => $lname,
'10k' => $_10k,
/* and so on ...*/
);
/// considering you are using mysql_query, use it's escape function
foreach ( $insert as $field => $value ) {
$insert[$field] = mysql_real_escape_string($value);
}
/// pull out the keys as fields and the values as values
$keys = array_keys($insert);
$vals = array_values($insert);
/// the following should auto backtick everything... however it should be
/// noted all the values will be treated like strings as you were doing anyway
$query = "INSERT INTO `" . $db_prefix . "offer_det` " .
"(`" . implode('`,`', $keys) . "`) " .
"VALUES ('" . implode("','", $vals ) . "')";