1

Ok so here is the question. I am trying to insert a variable into my query that is pre-defined. However it is not working. The query works if I just give it a value, but when I insert a variable into it, it fails. help?

$connection = new mysqli('localhost', 'user', 'pass', 'db'); 

$username = "test";

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if ($result = $connection->query("INSERT INTO users (username, password, email, firstName, lastName, createDate) VALUES ('".$username."', 'test', 'test', 'test', 'test', 'test')")){

  echo "success";
  $result->close();

}
else {
  echo "error";
}

$connection->close();
?>

If I replace $username with any value, it works.. Am I missing something here?

Chris
  • 461
  • 3
  • 9
  • 16
  • 2
    `$username = test;` is an obvious syntax error, I assume this is a typo? Also use backticks (\`) to escape your database and column names. There are a bunch of MySQL reserved keywords. Most notorious of those is `desc` which is often used as an abbreviation of "description" but is also a mysql keyword (Short for descending, used in `ORDER BY`). – Martin Tournoij Mar 25 '11 at 00:03
  • Unfortunately it's just an `E_NOTICE` in PHP as long it would be a valid name for a constant. PHP automatically treats undefined constants as constants containing their name as a string.. so `test == 'test'` will cause an `E_NOTICE` but the comparison is true.. – ThiefMaster Mar 25 '11 at 00:05
  • Still not sure why the query fails on me when I try to use a variable.. – Chris Mar 25 '11 at 00:07
  • 4
    Instead of using `echo "error";`, maybe try using `mysqli->error()` and that may shed some light ... – Martin Tournoij Mar 25 '11 at 00:08
  • No result unfortunately when I echo the error – Chris Mar 25 '11 at 00:11
  • Why are you using myqsli, but aren't using [prepared statements with placeholders & bound parameters](http://us2.php.net/manual/en/mysqli-stmt.bind-param.php)? – Charles Mar 25 '11 at 00:12
  • Because I have no way of including the $_POST values in a prepared statements. I have to define an actual value.. – Chris Mar 25 '11 at 00:14
  • @chris: that doesnt make any sense... a variable will behave the same whether you define it manually or use something coming from post or get. you could even just pass `'test'` to `Mysqli_Stmt::bind_param` without setting it as a variable... – prodigitalson Mar 25 '11 at 00:20
  • Doesn't that defeat the purpose of a prepared statement? – Chris Mar 25 '11 at 00:21
  • @chris: Ummm no... a statment is a generic object representing a query. you can reuse that query over and over aagain by binding the parameters to different values. When you supply those values you can use variables, or raw values. When you call bind_param you specify what type of value it is to make sure it is quoted appropriately. – prodigitalson Mar 25 '11 at 00:23
  • Huh. Tried this many times. never seemed to work trying to bind a pre-existing variable. – Chris Mar 25 '11 at 00:24
  • I suppose i could be wrong, its been a *long* time since ive used mysqli, but i use prepared statements in PDO constantly... and this is a normal thing to do... – prodigitalson Mar 25 '11 at 00:26
  • For instance, this does not work for me either: `$query = "insert into users values ('NULL', ?, ?, ?, ?, ?, ?, 'NULL')"; $stmt = mysqli_stmt_prepare($query, $connection); mysqli_stmt_bind_param("sssss", $username, $username, $username, $username, $username); mysqli_stmt_execute(); mysqli_stmt_close(); $result = mysqli_query($connection, $query); if ($result) { echo "Success"; } else { echo "Fail"; }` – Chris Mar 25 '11 at 00:30
  • Just curious- you have tried values other than `'test'`, right? Is username a primary key field causing a duplicate key error? – Michael Berkowski Mar 25 '11 at 00:42
  • Yes. Anything I use and it fails on meh. Im trying a PDO solution now – Chris Mar 25 '11 at 00:44
  • PDO is better anyway :-) BTW your statement code doesnt work because youre doing it worng. You assing values to variables youre binding **after** you bind them... which is retarded i know, but thats your issue... – prodigitalson Mar 25 '11 at 00:51

5 Answers5

3

Hello this is for anyone who might still need accomplish what was asked in original question.

A reason why someone possibly might want to not use prepared statements--from: http://www.php.net/manual/en/mysqli.quickstart.statements.php

"Using a prepared statement is not always the most efficient way of executing a statement. A prepared statement executed only once causes more client-server round-trips than a non-prepared statement."

//you will want to clean variables properly before inserting into db
$username = "MyName";
$password = "hashedPasswordc5Uj$3s";

$q = "INSERT INTO `users`(`username`, `password`) VALUES ('".$username."', '".$password."')";

if (!$dbc->query($q)) {
    echo "INSERT failed: (" . $dbc->errno . ") " . $dbc->error;
}    
echo "Newest user id = ",$dbc->insert_id;

Cheers!

Joseph
  • 63
  • 1
  • 3
  • 1
    -1 because you didnt properly escape the variables. I know they were hardcoded and thus could be insured of not needing escaping but that situation is not the norm in an actual application. – prodigitalson Mar 08 '13 at 22:40
  • 2
    This code has a huge security hole. If `$username` or `$password` are maliciously formed, an attacker can do serious damage to the database and/or extract information from it. – doug65536 Aug 14 '13 at 08:29
  • 6
    The question isn't about data cleansing or sql injections - it's a very simple bit of code to help understand what's going on. The dev can add code to prevent sql injection himself... very helpful bit of code. Thanks. – Blind Trevor Jul 21 '14 at 16:23
3

Since ther was some discussion above i thought id provide the following examples in pdo and mysqli for comparison:

MySQLi:

$connection = new mysqli('localhost', 'user', 'pass', 'db'); 

$username = "test";

if ($connection->errno) {
    printf("Connect failed: %s\n", $connection->error);
    exit();
}

$username = 'test';

$stmt = $connection->prepare("INSERT INTO users (username, password, email, firstName, lastName, createDate) VALUES (?,'test', 'test', 'test', 'test', 'test')");

$stmt->bind_param('s', $username_value);
$username_value = $username; // not we could simply define $username_value = 'test' here

if ($result = $stmt->execute()){

  echo "success";
  $stmt->free_result();

}
else {
  echo "error";
}

$connection->close();

PDO:

try {

$db = new PDO($dsn, $user, $pass);
$username = 'test';

$stmt = $db->prepare("INSERT INTO users (username, password, email, firstName, lastName, createDate) VALUES (?,'test', 'test', 'test', 'test', 'test')");

$stmt->execute(array($username));

echo 'Success';
}
catch(PDOException $e)
{
  echo $e->getMessage();
}
prodigitalson
  • 60,050
  • 10
  • 100
  • 114
0

In this case, looking at the context of your question it is better to assign the username variable with some data like $username=$_POST['username'];

This might help...otherwise avoid the double quotes and simply put down $username

Simply Me
  • 1,579
  • 11
  • 23
-2

Its been a long time and probably you've already found out the answer but just in case, it turns out that its actually a simple problem where you put Double quotes and dots in the mysqli query statement at VALUES('".$username"'), but if you just leave it in single quotes and just write the variable name inside the quotes like, VALUES('$username'), it will work. I think it applies for new versions of php though not sure i.e. Change

"INSERT INTO users (username, password, email, firstName, lastName, createDate) VALUES ('".$username."', 'test', 'test', 'test', 'test', 'test')"

to

"INSERT INTO users (username, password, email, firstName, lastName, createDate) VALUES ('$username', 'test', 'test', 'test', 'test', 'test')"

Notice in the VALUE field my variable is not enclosed in double quotes or concatenated in periods i.e. VALUES ('$username'), since it will save the periods as a value.

this works for me but I've noticed a problem in running the query with the same values again, it brings an error but it can be avoided by adding a column in your database table for an auto increment id to make sure that a value is being changed every time you run the query

Hope this helps

Gash
  • 81
  • 4
-4

The best answer to it is we must assign the variable we want into another variable. For example:

$username = $_POST['username'];

$a = $username;

mysqli_query("INSERT INTO tablename (username,test, test, test) VALUES ('$a', 'test', 'test');
Jojo
  • 1,875
  • 3
  • 29
  • 29
  • Please don't use this code. It is a textbook case of sql injection. Using this code will effectively give anyone complete access (read and write) to your entire database. – Magmatic Apr 04 '16 at 15:57