$firstName = mysqli_real_escape_string($dbcon, $_POST['newFirstName']);
$lastName = mysqli_real_escape_string($dbcon, $_POST['newLastName']);
$emailAddress = mysqli_real_escape_string($dbcon, $_POST['newEmailAddress']);
$sqlQuery = "INSERT INTO admins (firstname, lastname, email) VALUES ('$firstName','$lastName','$emailAddress')
ON DUPLICATE KEY UPDATE firstname ='".$firstName."' lastname='".$lastName."' email='".$emailAddress."'";
My issue is on the last line. AFAIK you have to use double quotes for PHP to actually insert your variable into the string, but no matter what quotes I use I get errors. What's the proper syntax for inserting the variables?
You are missing commas from your SQL query in between the parameters you are updating.
Additionally for your update statement, you need to specify the table and SET:
"Update admins
Set firstname = '". $firstname . "' , lastname = '" . $lastname . "' " etc.
You should separate the columns you're updating with a comma. e.g:
ON DUPLICATE KEY UPDATE firstname ='".$firstName."', lastname='".$lastName."',
email='".$emailAddress."'";
Related
I'm having trouble specifying my tablename inside the following query.
$sql = "INSERT INTO db269193_crud.posts (post_title,description)
VALUES ('" . $title . "','" . $description . "')";
The tablename is: db269193_crud.posts. I can't specify the table name as 'posts' because of my hostingprovider. They only allow me to specify it in conjunction with my databasename (which is db269193).
So the table name becomes: db269193(dot)posts. This dot however keeps lighting up in my editor as an incorrect syntax.
I need someone's help to tell me if I specified the table name correctly or if I have to use a variable to hide the dot notation like:
$tablename = 'db269193.crud';
$sql = "INSERT INTO $tablename (post_title,description)
VALUES ('" . $title . "','" . $description . "')";
You can put the entire name in backticks to escape it:
INSERT INTO `db269193_crud.posts` (post_title, description)
VALUES ('" . $title . "', '" . $description . "')
As for the rest of your statement, I would encourage you to use parameters instead of munging the query string. By putting random strings in the query, you are just inviting syntax errors and SQL injection attacks.
I can't specify the table name as 'posts' because of my hostingprovider. They only allow me to specify it in conjunction with my databasename (which is db269193).
I pretty much doubt that as it would require DB changes which simply make no sense. I assume that it's your fault as you did not select DB to use in the first place. Check how you connect and ensure you provide DB name as well or at least you mysqli_select_db() or equivalent.
$tablename = 'db269193.crud';
You can use backticks when name of table or column conflicts or is reserved word:
$tablename = '`db269193.crud`';
or
$tablename = '`db269193`.`crud`';
$sql = "INSERT INTO $tablename (post_title,description)
VALUES ('" . $title . "','" . $description . "')";
You are complicating simple strings with unnecessary concatentation. This will work and is less error prone:
$sql = "INSERT INTO $tablename (post_title,description)
VALUES ('{$title}','{$description}')";
however you are still seem to be vulnerable to sql injection here. I'd recommend switching to PDO.
I want to update an already existing table it only has email and I want to add first name and last name does this code work to do so?
UPDATE table
SET fname='$fname', lname='$lname'
WHERE email= '$_SESSION['email'].';
Or can I also use this
$sql="INSERT INTO $tbl_name(fname, lname)VALUES( '$fname, $lname')" WHERE email= '$_SESSION['email'].';
Your UPDATE has a syntax error (problem with apostrophes.)
INSERT will not update but multiply rows. That is not what you want to have.
Here is my suggested query:
$sql="UPDATE table SET fname='$fname', lname='$lname' WHERE email='".$_SESSION["email"]."'" ;
Fix your quotes, like so:
$sql="INSERT INTO $tbl_name(email) VALUES ( '" . $email . "') WHERE email = '" . $_SESSION['email'] . "'";
Try like this: In case of simple Update Query
$user_email = $_SESSION['email'];
$fname = 'Thierry';
$lname = 'Henry';
UPDATE table
SET fname='$fname', lname='$lname'
WHERE email= '$user_email';
Insertion is not a good idea here. It might duplicate your records.
If you want to be more specific than Go like this: Just providing your general syntax. No real time Syntax:
$user_email = $_SESSION['email'];
$fname = 'Thierry';
$lname = 'Henry';
$check_user = 'SELECT * FROM table WHERE email = "user_email"';
if($check_user)
{
YOUR UPDATE QUERY
}
else
{
YOUR INSERT QUERY
}
In case you are using mysql_ functions you should also escape the input:
$email = mysql_real_escape_string($_SESSION['email']);
Disclaimer for idiots: This does not imply I suggest to use mysql_* functions. Use mysqli or PDO instead.
You should also check against NULL and empty values in your query.
$sql = "REPLACE INTO " . $table . "
SET email='" . $email . "'
WHERE email='" . $email . "'
AND email IS NOT NULL
AND email != ''";
From http://dev.mysql.com/doc/refman/5.0/en/replace.html:
REPLACE works exactly like INSERT, except that if an old row in the
table has the same value as a new row for a PRIMARY KEY or a UNIQUE
index, the old row is deleted before the new row is inserted.
Please don't downvote if this doesn't exactly fit, just use INSERT or UPDATE with the same syntax then.
<?php
$db = new mysqli("localhost","root","password","eme");
if($db->connect_errno){ echo "Not connected."; exit();}
echo $db->query("SELECT * FROM users") . "<br>";
echo $_POST[FirstName] . " " . $_POST[LastName];
$db->query("INSERT INTO users (FirstName, LastName) VALUES ('$_POST[FirstName]','$_POST[LastName]')");
echo $db->query("SELECT * FROM users") . "<br>";
?>
I cannot figure out why this code doesn't work. The only line that outputs anything is "echo $_POST[FirstName] . " " . $_POST[LastName];"
My database has a "users" table and the database is called eme. The database connects properly.
There is currently no data in the database. I figured I could add some with "INSERT," but it's failing.
You have several problems:
The query() method of mysqli returns a mysqli_result object. you need to use one of it's methods to get the actual data back from the query. For instance fetch_assoc()
In your insert, you need to either assign $_POST['FirstName'] to a variable, or explicitly add it to the string.
ie.
"INSERT INTO users (FirstName, LastName) VALUES ('" . $_POST['FirstName'] . "','" . $_POST['LastName'] . "')"
or
$first = $_POST['FirstName'];
$last = $_POST['LastName'];
"INSERT INTO users (FirstName, LastName) VALUES ('" . $first . "', '" . $last . "')"
You should also sanitize the data before inserting it to prevent major security threats.
Lastly, it's not a bug per se, but you should always use a string or integer value for an array index.
ie. You have $_POST[FirstName], it should be either $_POST['FirstName'] or $_POST["FirstName"]
It will still work, but the interpreter thinks it's a constant, which isn't defined, so assumes the literal value, throwing a warning (maybe notice, can't remember offhand). It's unnecessary overhead.
Try this...
$db->query("INSERT INTO users (FirstName, LastName) VALUES('".$_POST['FirstName']."','".$_POST['LastName']."')");
For more info on Quotes, look over this link - What is the difference between single-quoted and double-quoted strings in PHP?
It must be the simplest error, but I dont see nor find it.
I fill a variable $aa_minerid with value 7.
I use this variable in a insert.
The insert always inserts a 0 (zero) in the database never a 7
The field i put it in is a smallint(6)
I tried
VALUES ('$aa_productid')
VALUES ($aa_productid)
VALUES ("$aa_productid")
VALUES ('{$aa_productid}')
VALUES ("{$aa_productid}")
and all with use of ` aswell
into script placed hereafter.
If I put there : VALUES ( 7 )
It does work perfect.
So what do I do wrong in this script?
BTW the echo at the end DOES show the right value of the variable $aa_productid
<?php
/* This php script should transfer data from the aa to the sql database */
// Info coming from aa
$aa_productid = 7 ;
include ("dogs.inc");
$cxn=mysqli_connect($host,$user,$passwd,$dbname);
$query = 'SELECT * FROM `Price` WHERE '
. ' `Time_Stamp`=(select max(`Time_Stamp`) from `Price` where `Product_ID` = \'1\')';
$result=mysqli_query($cxn,$query) or
die("Couldn't execute select query");
$row = mysqli_fetch_row($result);
$aa_price=$row[3] ;
$aa_value = $aa_price * $aa_amount;
// Info ready to go to database
$sqlinsert = 'INSERT INTO Mining (Product_ID)'
. ' VALUES ( $aa_productid )' ;
echo $aa_productid;
Single quotes don't do variable expansion in PHP. But I would recommend you use prepared statements, such as:
$stmt = $cxn->prepare('INSERT INTO Mining (Product_ID) VALUES ( ? )');
$stmt->bind_param('i', $aa_productid);
$stmt->execute();
See the documentation at prepare and bind_param.
This will protect you from SQL injection.
Try
'.$aa_productid.'
or
".$aa_productid."
Depending on the type of apostrophe used to beging the string, use the same one.
Also, if You are using ", then You should be able to Just do
$insert="INSERT INTO $tablename;";
It's been a while since I have done any PHP but..
I think you need to have smartquotes turned on
Try this instead:
$sqlinsert = 'INSERT INTO Mining (Product_ID)'
. ' VALUES ('. $aa_productid .' )' ;
concatenate the variable into the query.
When you are using variables within quotes, you must use the double-quote if you want PHP to parse variables within it. So, this would work:
$sqlinsert = 'INSERT INTO Mining (Product_ID) VALUES ('.$aa_productid.')';
Or this would:
$sqlinsert = "INSERT INTO Mining (Product_ID) VALUES ($aa_productid)";
Try:
$query = "SELECT * FROM Price WHERE Time_Stamp=(select max(Time_Stamp) from Price where Product_ID = "1")";
$sqlinsert = "INSERT INTO Mining (Product_ID) VALUES ( '$aa_productid' )" ;
Also, its always a good idea to escape the strings before entering them in the db.
Try this syntax instead:
$sqlinsert = "INSERT INTO Mining (Product_ID) VALUES ("' . $aa_productid . '")";
no need to concatenate the two parts of the insert. Also double quoting the variable seems to avoid problems.
Hy all,
Not sure what's going on here, but if I run this:
$query = 'INSERT INTO users
(`id`, `first_name`, `second_name`, `register_date`, `lastlogin_date`)
VALUES
("'. $user_id . '", "' . $first_name .'", "'. $second_name . '", "' . $date . '", "' . $date . ");';
$result = mysql_query($query);
I get no return, but if I change it to this it's fine:
$query = 'INSERT INTO users (`id`, `first_name`, `second_name`, `register_date`, `lastlogin_date`)
VALUES ("21021212", "Joe", "Bloggs", "20090202", "20090202");';
$result = mysql_query($query);
User id = bigint(20)
first name = varchar(30)
second name = varchar(30)
date = int(8)
At first I thought it was a issue with the vars but they are exactly the same and still don't work.
Any help appreciated.
Get into the habit of escaping all database inputs with mysql_real_escape_string- really, you should use some kind of wrapper like PDO or ADODb to help you do this, but here's how you might do it without:
$query = sprintf("INSERT INTO users ".
"(id, first_name, second_name, register_date, lastlogin_date)".
"VALUES('%s','%s','%s','%s','%s')",
mysql_real_escape_string($user_id),
mysql_real_escape_string($first_name),
mysql_real_escape_string($second_name),
mysql_real_escape_string($date),
mysql_real_escape_string($date));
$result = mysql_query($query);
and also check for errors with mysql_error
if (!$result)
{
echo "Error in $query: ".mysql_error();
}
What's the result from "mysql_error()"? Always check this, especially if something doesn't seem to be working.
Also, echo out $query to see what it really looks like. That could be telling.
Maybe the value of $date was "1111'); DELETE FROM users;"?
Seriously though? The problem is that isn't how you interact with your database. You shouldn't be passing in your data with your query. You need to specify the query, the parameters for the query, and pass in the actual parameter values when you execute the query. Anything else is inefficient, insecure and prone to bugs like the one you have.
By using PDO or something that supports parametrized queries, you'll find these kinds of issues go away because you are calling the database property. It is also much more secure and can speed up the database.
$sth = $dbh->prepare("INSERT INTO users (`id`, `first_name`, `second_name`, `register_date`, `lastlogin_date`) VALUES (?,?,?,?,?)")
$sth->execute(array($user_id ,$first_name , $second_name , $date, $date ));
In addition to echoing the query and checking mysql_error() as #GoatRider suggests:
Are you escaping your data properly? See mysql_real_escape_string()
You shouldn't end your queries with a semicolon when using mysql_query()
in $query = 'INSERT INTO users (id, first_name, second_name, register_date, lastlogin_date) VALUES ("' . $user_id . '", "' . $first_name . '", "' . $second_name . '", "' . $date . '", "' . $date . '");
are u giving the correct date format?? it might be the issue. otherwise the syntax is all fine.