PHP/Mysqli insert : Cannot pass parameter 2 by reference - php

Thanks for helping me out.
I'm trying to do something simple : just 2 inserts in the database.
The first one works well:
$stmt = $db->prepare("INSERT INTO sessions(date, lieu, trainer) VALUES (?,?,?)");
$stmt->bind_param("sss", $date, $location, $trainer);
$stmt->execute();
$session = $stmt->insert_id;
$stmt->close();
Then, I try to do another insert: I have a table 'users' which has 4 columns : an Id, auto-incremented, a username (column called 'fullName'), a sessionId (an int) and a contactInfo (a varchar).
Here's my code for the second insert:
//var_dump($session); returns an int
$stmt = $db->prepare("INSERT INTO users(fullName, sessionId, contactInfo) VALUES (?,?,?)");
$stmt->bind_param("sis", "$username", "$session", "$contactinfo");
$stmt->execute();
$newId = $stmt->insert_id;
$stmt->close();
From what I could read from other posts, it seems that this issue comes when you try to pass a parameter that's not a parameter (e.g.:an int) but in my case it's a variable, I reuse "$session" from the first block ($session = $stmt->insert_id;)
Am I allowed to do that? What did I miss?
Thanks!
EDIT: removed the single quotes and put double quotes, but that doesn't seem to cut it. Tried to put them for both strings but not for session but it doesn't change the result.
EDIT2:following the good advice from serjoscha, I printed the query to have an idea of what it looks like:
echo "INSERT INTO users (fullName, sessionId, contactInfo) VALUES ($username,$session,$contactinfo)";
which gives me something like
INSERT INTO users (fullName, sessionId, contactInfo) VALUES (Paul Honour,56,Location Liège Belgium Email ph#ph.be +329999999)
The query only works if I put it like this:
INSERT INTO users (fullName, sessionId, contactInfo) VALUES ('Paul Honour',56,'Location Liège Belgium Email ph#ph.be +329999999')
Any idea what's wrong?

Your issue are the single quoted variables. Just remove the single quotes or use double quotes for the content of double quotes is partitial evaluated / parsed:
$a=3;
echo '$a'; // prints: $a
echo "$a"; // prints: 3
echo $a; // prints: 3 and this is just what you need
You do not need the quotes for variables, so just remove them:
$stmt->bind_param("sis", $username, $session, $contactinfo);

Found out the issue:
it was failing on "Liège", some problem with the accent. I made sure I had the same encoding on both sides, and I can finally insert!
My code now looks like:
$contactinfo = $db->real_escape_string($contactinfo);
$stmt = $db->prepare("INSERT INTO users (fullName, sessionId, contactInfo) VALUES (?,?,?)");
$stmt->bind_param("sis", $username, $session, $contactinfo);
$stmt->execute();
$userId = $stmt->insert_id;
$stmt->close();

Related

conditional insert column values

i am having a problem with inserting records to my tables as i want to insert values into specific columns if only the value is not null, my query goes like this
i have tried:
INSERT INTO users(id,name,phone,address) VALUES($userId,$userName,$userPhone,$userAddress);
but it gives me error if on client side one of the parameters is not sent not all the time the client side send all the parameters (id,name,phone,address) i want to have some kind of condition instead of the handle all combinations to the query to go over this problem
You should be using prepared queries, but your immediate problem is that you aren't quoting anything:
$query = "INSERT INTO users(id,name,phone,address) VALUES('$userId', '$userName', '$userPhone', '$userAddress')";
Now, assuming you're doing this properly using a PDO connection, this is how you should be doing it to protect your database:
$db = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$query = "INSERT INTO users (id, name, phone, address) VALUES (?, ?, ?, ?)";
$stmt = $db->prepare($query);
$result = $stmt->execute(array($userId,$userName,$userPhone,$userAddress));
if ($result) {
//success
} else {
//failure
}
Put ' inside VALUES () like '$userId'.
INSERT INTO users(id,name,phone,address) VALUES('$userId','$userName','$userPhone','$userAddress');
If parameter are not coming, then let it Insert Null in DB Table column. (Allow Null). And, if you don't want to insert NULL in DB Table column, then assign any default value before inserting.

prepared statement not executing but msqli_stmt_execute returning true

I have an insert query below and am checking if the insert was successful using: mysqli_stmt_execute. The query is not executing as the values are not being entered into my db. However, I am getting into the if condition. I cannot understand this. I have wrapped the stmt_prepare in an if condition previously and that also was returning true tht it was preparing successfully. I did the same with the bind statement and now I have it on the final execute statement. All return true but the query is not executing. The structure of the table is correct. I even preformed an insert in phpmyadmin and pasted the generated query into my AddToken variable.
$con = 'my login credentials'
$stmt = mysqli_stmt_init($con);
$AddToken = "INSERT INTO `auth` VALUES ('',?, ?)";
mysqli_stmt_prepare($stmt, $AddToken);
mysqli_stmt_bind_param($stmt, "si", $Token, $ID);
if (mysqli_stmt_execute($stmt)){
$message2 = "here";
// worked
}
else{
//didn't work
$message2 = "here 2";
}
echo $message2;
EDIT I have no idea what the problem was but I deleted my auth table and recreated it and it worked?
You need not have empty strings in your VALUES()in the insert query, since you are inserting only two values
May be better to specify the column names if you know
$AddToken = "INSERT INTO `auth` (column1, column2) VALUES (?, ?)";

inserting data from a form into your mysql database using php

i used this code
<?php
$conn = new PDO("mysql:host=localhost;dbname=CU4726629",'CU4726629','CU4726629');
$sql="INSERT INTO review (username, movie_name, ratings) VALUES ("$_POST['username']","$_POST['moviename']","$_POST['ratings']")";
header('Location: reviews.php');
?>
but it keeps giving me this error
Parse error: syntax error, unexpected T_VARIABLE in
/home/4726629/public_html/check_login.php on line 5
Take this for an example:
<?php
// insert some data using a prepared statement
$stmt = $dbh->prepare("insert into test (name, value) values (:name, :value)");
// bind php variables to the named placeholders in the query
// they are both strings that will not be more than 64 chars long
$stmt->bindParam(':name', $name, PDO_PARAM_STR, 64);
$stmt->bindParam(':value', $value, PDO_PARAM_STR, 64);
// insert a record
$name = 'Foo';
$value = 'Bar';
$stmt->execute();
// and another
$name = 'Fu';
$value = 'Ba';
$stmt->execute();
// more if you like, but we're done
$stmt = null;
?>
You just wrote a string in your above code:
$sql="INSERT INTO review (username, movie_name, ratings) VALUES ("$_POST['username']","$_POST['moviename']","$_POST['ratings']")";
Above answers are correct, you will need to concat the strings to form a valid sql query. you can echo your $sql variable to check what is to be executed and if is valid sql query or not. you might want to look in to escaping variables you will be using in your sql queries else your app will be vulnerable to sql injections attacks.
look in to
http://php.net/manual/en/pdo.quote.php
http://www.php.net/manual/en/pdo.prepare.php
Also you will need to query you prepared sql statement.
look in to http://www.php.net/manual/en/pdo.query.php
A couple of errors:
1) you have to concat the strings!
like this:
$sql="INSERT INTO review (username, movie_name, ratings)
VALUES (".$_POST['username'].",".$_POST['moviename'].",".$_POST['ratings'].")";
2) you are not using the PDO at all:
after you create the "insert" string you must query the db itself, something like using
$conn->query($sql);
nb: it is pseudocode
3) the main problem is that this approach is wrong.
constructing the queries in this way lead to many security problems.
Eg: what if I put "moviename" as "; drop table review;" ??? It will destroy your db.
So my advice is to use prepared statement:
$sql="INSERT INTO review (username, movie_name, ratings)
VALUES (?,?,?)";
$q = $conn->prepare($sql);
$fill_array = array($_POST['username'], $_POST['moviename'], $_POST['ratings']);
$q->execute($fill_array);
You forgot dots:
$sql="INSERT INTO review (username, movie_name, ratings)
VALUES (".$_POST['username'].",".$_POST['moviename'].",".$_POST['ratings'].")";
and fot the future for now your variables are not escaped so code is not secure
String in a SQL-Statment need ', only integer or float don't need this.
$sql="INSERT INTO review (username, movie_name, ratings) VALUES ('".$_POST['username']."','".$_POST['moviename']."','".$_POST['ratings']."')";

Not inserting data to database from link

So when someone press this link, it should insert all the data from that text id to a new table but with the username who clicked it and the id of the text the user pressed.
The problem is, when a user clicks the link, it doesn't insert the data, what could be wrong?
The session works, so it must be something with the GET?
<?php
if(isset($_GET['collect'])) {
$perman = $_GET['collect'];
$username = $_SESSION['username'];
$query = $dbh->query("INSERT INTO collections (id, ad, user) VALUES ('', $perman, $username)");
echo 'Saving';
echo $perman;
header ('Refresh: 1; URL=http://localhost/de/collect.php');
}
?>
First, inserting '' for ID isn't very good (don't know if it works), don't use it (uses default), or insert NULL (uses default too, if NOT NULL).
Second, to insert values it's good practice to enquote it and use escape_string on it. I think that's your problem.
$query = $dbh->query("INSERT INTO collections (ad, user) VALUES ('" . $dbh->escape_string($perman) . "', '" . $dbh->escape_string($username) . "')");
You should be doing it like this...if you're using PDO
Much safer, with prepared statements
$sql = "INSERT INTO books (id,ad,user) VALUES (:id,:ad,:user)";
$q = $conn->prepare($sql);
$q->execute(array(':id'=>null,':ad'=>$perman,':user'=>$username));
You tagged your Question with "PDO". Are you using PDO? If yes, why are you not using bindParam() or bindValue()?
If $perman and $username are strings, you've to escape them:
$query = $dbh->query("INSERT INTO `collections` (`id`, `ad`, `user`) VALUES ('', '{$perman}', '{$username}')");
That query should work, but there are still security issues. You've to escape the values. With PDO it's very simple.
General: use http://php.net/manual/en/function.mysql-error.php
Your column "id" should be Integer and have an auto_increment. Of course some IDs are Strings, but if you're able to avoid it, avoid it!
You could print out the $_GET params by using
print_r($_GET);
Edit
Example with PDOStatement::bindValue():
$stmt = $dbh->prepare("INSERT INTO `collections` (`id`, `ad`, `user`) VALUES (:id, :ad, :user)");
$stmt->bindValue(":id", 123);
$stmt->bindValue(":ad", "ad");
$stmt->bindValue(":user", "username");
$stmt->execute();

PHP not getting parameters

I acces my page passing some parameters through the URL:
www.mypage.com/page.php?aID=4091cdcd-773d-4ca5-bab2-41e1188870a9&sID=1_MX4yMjI1MTgxMn4xMjcuMC4wLjF-V2VkIERlYyAyNiAwOTo1MDoyNiBQU1QgMjAxMn4wLjg1MjA4MTF-&nam=Gab&tel=7777777777
then in my PHP code I have:
if(isset($_GET['sID'])) {
$sID = $_GET['sID'];
}
if(isset($_GET['aID'])) {
$aID = $_GET['aID'];
}
if(isset($_GET['nam'])) {
$nam = $_GET['nam'];
}
if(isset($_GET['tel'])) {
$tel = $_GET['tel'];
}
I have no problem retrieving $nam and $tel, but $aID and $sID always get an empty string. I have tried using double quotes (isset($_GET["aID"])) , but it has not made any difference.
Are there illegal characters on the string or a limit in size of a variable you can pass through the URL? How can I GET variables $aID and $sID?
$query = "INSERT INTO myTable (ArchiveID, SessionID, Name, Tel) VALUES ('$aiD', '$siD', '$nam', '$tel' )";
echo $query;
Echo $query's output is:
INSERT INTO myTable (ArchiveID, SessionID, Name, Tel) VALUES ('', '', 'Gab', '7777777777' )
Testing your URL, I get the following result:
Array
(
[aID] => 4091cdcd-773d-4ca5-bab2-41e1188870a9
[sID] => 1_MX4yMjI1MTgxMn4xMjcuMC4wLjF-V2VkIERlYyAyNiAwOTo1MDoyNiBQU1QgMjAxMn4wLjg1MjA4MTF-
[nam] => Gab
[tel] => 7777777777
)
Therefore, I'm not sure what you mean by you're getting an empty string. You did have a typo in your code, where $tel references $_GET['aID']. I would advise you verify your code.
I would recommend that you also use $_SERVER['REQUEST_METHOD'] to verify that your script is using GET.
Update
Per your updated query, it seems as though your case is incorrect. The variable name is case-sensitive.
$query = "INSERT INTO ... VALUES ('$aiD', '$siD', '$nam', '$tel' )";
^ ^
Should be:
$query = "INSERT INTO ... VALUES ('$aID', '$sID', '$nam', '$tel' )";
You have to enable error reporting and logging to the highest level when you develop PHP.
You have to check return values of methods you call to see if they did what you thought they did. You have to look for more error information if something failed.
You have to look into prepared statements to prevent SQL injection.
And yes, mysql_* functions are deprecated. Do not use it for new code.
You notice in your sql statement you are not calling the variables you defined:
$query = "INSERT INTO myTable (ArchiveID, SessionID, Name, Tel) VALUES ('$aiD', '$siD', '$nam', '$tel' )";
should be:
$query = "INSERT INTO myTable (ArchiveID, SessionID, Name, Tel) VALUES ('$aID', '$sID', '$nam', '$tel' )";
and looks like njk updated his answer to reflect this so he should be credited for the answer.

Categories