Can anyone see what is wrong with the code below? For some reason i can get it to return the id of the affected row..in fact it doesnt return anything but the query runs fine and the record is created in the db...
$stmt = $this->db->stmt_init();
if($stmt->prepare('INSERT INTO Assets(id,assetName,type, username, password, mail) VALUES (?,?,?,?,?,?)'))
{
$stmt->bind_param("isssss", $id, $assetName, $type, $username, $password, $mail);
$stmt->execute();
$stmt->close();
return $stmt->insert_id;
}
else
{
$stmt->close();
return "";
}
You are closing the statements before trying to get the insert id:
$stmt->close();
return $stmt->insert_id;
Related
I tried the questions with similar titles, but they are all regular queries that are not in functions.
I am trying to create an update function in a Database class so I don't have to write out the entire process over and over. However, I am getting the error:
Invalid parameter number: number of bound variables does not match number of tokens
Here is my function.
public function updateRow($query, $params) {
try {
$stmt = $this->master_db_data->prepare($query);
foreach($params as $key => $val) {
$stmt->bindValue($key+1, $val);
$stmt->execute();
return true;
}
} catch(PDOException $e) {
die("Error: " . $e->getMessage());
}
}
And its usage:
$query = "UPDATE records SET content=?, ttl=?, prio=?, change_date=? WHERE id=?";
$params = array($SOA_content, $fields['SOA_TTL'], '1', $DATE_TIME, $id);
if($db->updateRow($query, $params)) {
echo "Success";
}
else {
echo "Fail";
}
Doing it without a function works:
$pdo = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
$query = "UPDATE records SET content=:content, ttl=:ttl, prio=:prio, change_date=:change_date WHERE id=:id";
$stmt = $pdo->prepare($query);
$stmt->bindValue(":content", $SOA_content);
$stmt->bindValue(":ttl", $fields['SOA_TTL']);
$stmt->bindValue(":prio", 1);
$stmt->bindValue(":change_date", $DATE_TIME);
$stmt->bindValue(":id", $id);
$stmt->execute();
Am I wrong with my bindValue in the function? If so, how?
Always make sure your execute calls happen after all binding has been performed. In this situation, move the execute out of the binding loop.
I need a second pair of eyes on this. I can NOT figure out why this function works just fine:
function get_password($db, $id) {
try {
$sql = $db->prepare('SELECT password FROM employee
WHERE employee.emp_id = ?');
$sql->bindParam(1, $id);
$sql->execute();
$password = $sql->fetchColumn();
} catch(Exception $e) {
echo $e->getMessage();
die();
}
return $password;
}
and this function fails on fetchColumn():
function get_name($db, $email) {
try {
$sql = $db->prepare('SELECT login
FROM employee
WHERE email = ?');
$sql->bindParam(1, $email);
$sql->execute();
$user_name = $sql->fetchColumn(0);
} catch(Exception $e) {
echo $e->getMessage();
die();
}
return $user_name;
}
I have verified the following:
I am trimming the email, so no extra white space is in there
the query works from the command line
the prepare() statement is successful and errorInfo() returns nothing
the bindParam() statement returns true and errorInfo() returns nothing
the execute() statement returns 1 row and errorInfo() returns nothing
the fetchColumn(0) statement returns False (ARGH!!!!) but errorInfo() still returns nothing.
I have also tried using just fetchColumn(), fetchAll, and other fetch attempts.
I have also tried re-writing in the SELECT to this:
'SELECT employee.login FROM employee WHERE employee.email = ?'
but results are the same.
Is there some concept here I'm missing? Any other ideas of how I might debug this?
I have a function to delete a row from my table and I like to return true if the row existed before. I use the following function achieve that:
$mysqli = $this->mysqli;
$stmt = $mysqli->prepare("DELETE FROM active_clients WHERE token LIKE ?");
$stmt->bind_param('s', $token);
$stmt->execute();
if($stmt->affected_rows < 1){
$stmt->close();
return false;
}
$stmt->close();
return true;
It also worked propperly on my local host but when I moved to live server it doesn't return the correct result. affected_rows returns always 0 but the row is deleted as it should be. How can it be? Could there be a problem with php-version? I run locally 5.4 and on live server 5.3... Or ist it also possible that it has something to do with database or server configuration?
Try this:
$mysqli = $this->mysqli;
$stmt = $this->mysqli->prepare("DELETE FROM active_clients WHERE token LIKE ?");
if(!$stmt){
die('prepare() failed: ' . $mysqli->error);
}else{
$stmt->bind_param('s', $token);
if($stmt->execute()){
$stmt->store_result();
if($stmt->affected_rows < 0){
$stmt->close();
return false;
}else{
$stmt->close();
return true;
}
}else{
die('execute() failed: ' . $mysqli->error);
}
}
If the last query was a DELETE query with no WHERE clause, all of the records will have been deleted from the table but this function will return zero with MySQL versions prior to 4.1.2.
Check your Mysql version.
Resource: http://php.net//manual/en/function.mysql-affected-rows.php
I'm creating an authentification file with php and mysql, but I have this mistake in this line:
$stmt2->bind_param('ss',$twitter_id, $name);
The error message is
Call to a member function bind_param() on a non-object in ...
Where's my mistake?
$name in my database is a VARCHAR
$twitter_id in my database is a VARCHAR
$bd is my database connection
If a user is already registered, it should show me a message saying "User already registered", and if the user isn't registered, it should insert a new id and name in my database.
session_start();
if (!isset($_SESSION['userdata'])) {
header("location: index.php");
} else {
$userdata = $_SESSION['userdata'];
$name = $userdata->name;
$twitter_id = $userdata->id;
$stmt = $bd->prepare("SELECT ID_TWITTER FROM USERS");
$stmt->execute();
$stmt->bind_result($checkUser);
if ($stmt->fetch()) {
if($checkUser!==$twitter_id){
$cSQL = "INSERT INTO USERS (ID_TWITTER, FULL_NAME) VALUES(?,?)";
$stmt2 = $bd->prepare($cSQL);
$stmt2->bind_param('ss',$twitter_id, $name);
$stmt2->execute();
$stmt2->close();
} else {
echo "User already exits";
}
}
$stmt->close();
}
Could it be a typo? does $bd exist or should it be $db ?
Shameless plug: I do this exact thing in a project I have on github. Feel free to use the classes for whatever you like; they are mostly copy-pastable.
Your real issue is that $bd->prepare() returned false.
Check that you actually called it correctly and set it to new mysqli(*params)
The error Call to a member function ... on a non-object in ... means that $db is not an object, which means that it was not instantiated to an object. Thus, $this->method() isn't possible. bind_param(string $format, mixed &*vars); uses pass-by-reference and if this fails, it throws an error.
Try it yourself by sticking this in there:
$stmt->bind_param("ss", "string", "string");
To get around this issue where it can fail, check if $db->prepare() returns true:
if ($query = $bd->prepare($sql)) {
//stuff
}
In addition, in the first query you do it is probably not a good idea to be adding the overhead of a prepare for a single query that only checks row count without user input.
Solved : it works now
$stmt = $bd->prepare("SELECT ID_PROVIDER FROM USERS WHERE ID_PROVIDER = ?");
$stmt->bind_param('s', $twitter_id);
$stmt->execute();
$stmt->bind_result($checkUser);
while ($stmt->fetch()) {
$result = $checkUser;
}
if (empty($result)) {
$cSQL = "INSERT INTO USERS (ID_TWITTER, FULL_NAME)
VALUES(?,?)";
$stmt2 = $bd->prepare($cSQL);
$stmt2->bind_param('ss', $twitter_id, $name);
$stmt2->execute();
$stmt2->close();
}else {
echo "User already exits";
}
I am brand new to php and I ran into a problem that has already taken a few hours of poking around and researching and I could not find anything like it anywhere around the net.
Database:MyPHPAdmin winserver
Goal: Create a new row in table 'photo'. Take the last insert p_id for the current user and update the table accessible_to by creating a new row with that p_id.
I know I can create a trigger, and no it does not work either don't know why. Run out of ideas how.
What I found out by simply printing before-in-after the if statement
if ($stmt = $mysqli->prepare("insert into accessible_to values(?, ?, ?)"))
is that it just bypasses it.
Please post your suggestions.
P.S. The if statement above to which I am referring has been twisted in several ways and yet it does not work.
The connection is already imported.
Thank you a lot.
if(!isset($_SESSION["id"])) {
echo "You are not logged in. ";
echo "You will be returned to the homepage in 3 seconds or click here.\n";
header("refresh: 3; index.php");
}
else {
//if the user have uploaded a photo, insert it into database
if(isset($_POST["ext"])) {
//insert into database, note that p_id is auto_increment
if ($stmt = $mysqli->prepare("insert into photo (ext, owner_id) values (?,?)")) {
$stmt->bind_param("ss", $_POST["ext"], $_SESSION["id"]);
$stmt->execute();
$stmt->close();
$id = htmlspecialchars($_SESSION["id"]);
}
//The following function is fetching the last added p_id in PHOTO by the user with the current SESSION
//Do not simply get the last p_id in PHOTO because someone else might have just added another picture meanwhile
if ($stmt = $mysqli->prepare("select MAX(p_id) from photo where owner_id = ?")){
$stmt->bind_param("s", $id);
$stmt->execute();
$stmt->bind_result($p_id);
if ($stmt->fetch()){
$p_id = htmlspecialchars($p_id);
}
}
echo "BEFORE accessible_to insertion";
echo '<br />';
if ($stmt = $mysqli->prepare("insert into accessible_to values(?, ?, ?)")){
echo "Finally inside accessible_to insertion";
echo '<br />';
$stmt->bind_param("iss", $p_id, $id, 'T');
$stmt->execute();
$stmt->close();
}
echo "AFTER accessible_to insertion";
echo '<br />';
}
//if not then display the form for posting message
else {
echo "Something";
You can't boolean test an assignment and expect it to return a different result. What you want to test for is if $stmt->execute successfully executed or not.
$stmt = $mysql->prepare("insert into foo values (?,?)");
$stmt->bind_param(1,$f1);
$stmt->bind_param(2,$f2);
if ($stmt->execute()) {
... worked
} else {
... fubar
}
You have to start by calling mysqli::connect($server, $user, $pw, $db). The best way to do that is by constructing an object like:
$connection = new mysqli($server, $user, $password, $db);
if ($connection->errno)
{
echo "Connection failed";
echo $this->connection->error;
}
else
{
$stmt = $connection->prepare("insert into photo (ext, owner_id) values (?,?)")) {
$stmt->bind_param("ss", $_POST["ext"], $_SESSION["id"]);
$stmt->execute();
$stmt->close();
}