Mysqli bind parameters not working - php

I'm trying to use prepared statements to enter data in a database. The unprepared statement works but this prepared statement does not. I can't find out why.
Prepared version:
$stmt = $mysqli->prepare("INSERT INTO videos (file_name, upload_by, date, path)
VALUES (?, ?, ?, ?)");
$stmt->bind_param('ssss', $newstring, $id, $date->format('Y-m-d'), $location);
$stmt->execute();
Unprepared version:
$sql = "INSERT INTO videos (file_name, upload_by, date, path) VALUES ('$newstring', '$id', '
$date', 'Nominator/$location$newstring')";
mysqli_query($mysqli, $sql);

Replace $stmt-execute(); with $stmt->execute();
Also, don't use date and path in query. Rename them with some other name like date1 and path1.
Update your Query like below that will surely work (Tested Offline):
<?php
$mysqli = new mysqli('localhost', 'root', '', 'test2');
if ($mysqli->errno) {
printf("Connect failed: %s\n", $mysqli->error);
exit();
}
$stmt = $mysqli->prepare("INSERT INTO videos (file_name, upload_by, date1, path1) VALUES (?, ?, ?, ?)");
$stmt->bind_param('ssss', $file_name, $upload_by, $date1, $path1);
$date1 = date("Y-m-d");
$file_name = "test.jpg";
$upload_by = "amit";
$path1 = "test";
if ($result = $stmt->execute()){
echo "success";
$stmt->free_result();
} else {
echo "error";
}
$stmt->close();
?>

You are binding your parameter twice, if you are using only ?, don't bind parameter again just execute directly.
//Prepare your query first
$stmt = $mysqli->prepare("INSERT INTO videos (file_name, upload_by, date, path)
VALUES (?, ?, ?, ?)");
//Just pass your argument and execute directly without binding the parameter (The parameter is binded already)
$stmt->execute('ssss', $newstring, $id, $date->format('Y-m-d'), $location);

Related

PHP SQL insert prepared statements doesn't insert properly

When executing the following code, no Errors occur but the data isn't put into the database!
$zero = 0;
$connection = new mysqli("localhost", "andrewle_me", "*****", "andrewle_velocity");
$stmt = $connection->prepare("INSERT INTO accounts Values(?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("issssssi", $zero, $_POST["username"], password_hash($_POST["password"], PASSWORD_DEFAULT), $_POST["Email"], $_POST["firstname"], $_POST["lastname"], $_POST["nationality"], $zero);
$stmt->execute();
$stmt->close();
$connection->close();
echo "Success";
Define your posts and password hash outside of the param binding. Set the fields in the table that your values are going to be entered into.

PHP connected to db can't use insert function

I've been sitting on the same small problem now for over 10 hours, so it's time to ask stackoverflow! I'm connected to the database but when calling mysqli_stmt_bind_param I get "invalid object or resource".
I've tried the insert statement in the console and it works fine..
<?php
$con=mysqli_connect("127.0.0.1:3306", "myUsername", "password");
mysqli_select_db($con, "webshop");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query= mysqli_stmt_init($con);
mysqli_stmt_prepare($query, "INSERT INTO user (name, email, hash, address, tel) VALUES (?, ?, ?, ?, ?)");
mysqli_stmt_bind_param($query, "ssssi", $name, $email, $hash, $address, $tel);
if(mysqli_stmt_execute($query))
{
mysqli_close($con);
}
?>
Thankful for any help at all!
You have to use the statement object returned by mysqli_stmt_prepare()
$stmt = mysqli_stmt_prepare($con, "INSERT INTO user (name, email, hash, address, tel) VALUES (?, ?, ?, ?, ?)");
mysqli_stmt_bind_param($stmt, "ssssi", $name, $email, $hash, $address, $tel);
if(mysqli_stmt_execute($stmt))
Also, the mysqli_stmt_init($con) call is not needed (I think).
mysqli_stmt_init is needed as you are accessing mysqli using the procedural style.
This returns an object of type mysqli_stmt, which then acts as a container for the query you are building. As such, you should pass this as the first parameter to mysqli_stmt_prepare, mysqli_stmt_bind_param and mysqli_stmt_execute.
So your code would look like:
<?php
$con=mysqli_connect("127.0.0.1:3306", "myUsername", "password");
mysqli_select_db($con, "webshop");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$stmt = mysqli_stmt_init($con);
$query = "INSERT INTO user (name, email, hash, address, tel) VALUES (?, ?, ?, ?, ?)";
mysqli_stmt_prepare($stmt, $query);
mysqli_stmt_bind_param($stmt, "ssssi", $name, $email, $hash, $address, $tel);
if(mysqli_stmt_execute($stmt))
{
mysqli_close($stmt);
}
?>
One, unrelated point - you appear to be requiring that your tel field (which I presume to be a telephone number) is an integer. This might be a bad idea if you have to handle telephone numbers starting with 0 (common in the UK for example) at any point.

INSERT INTO sqlsrv_query statement not working

When working with the sqlsrv_query command I can request data from the MSSQL server.
This works
But!
When I want to add data it returns the error [error:array].
The code I use for this is:
$tsql= "INSERT INTO dbo.VERLOF_events (id,
username,
soort,
afdeling,
description,
evdate,
trdate)
VALUES
(?, ?, ?, ?, ?, ?, ?)";
$var = array('', $username, $soort, $afdeling, $description, $evdate, $trdate);
if (!sqlsrv_query($conn, $tsql, $var))
{
die('Error: ' . sqlsrv_errors());
}
echo "1 record added";
The array values are set in the POST statement.
$afdeling = $row['Afdeling'];
$submit = #$_POST['submit'];
$description = #$_POST["description"];
$evdate = #$_POST["evdate"];
$trdate = #$_POST["trdate"];
$username = #$_SESSION['username'];
$soort = #$_POST['Dagen'];
Why does it return the array error?
I looked it up but could not find the problem returning the error.
Any help is appreciated!
The problem is probably you're trying to add an empty value in the id field. If you set identity on it with auto-numbering, you don't need to include it in your query :
$tsql= "INSERT INTO dbo.VERLOF_events (
username,
soort,
afdeling,
description,
evdate,
trdate)
VALUES
(?, ?, ?, ?, ?, ?)";
$var = array($username, $soort, $afdeling, $description, $evdate, $trdate);
if (!sqlsrv_query($conn, $tsql, $var))
{
die('Error: ' . sqlsrv_errors());
}
echo "1 record added";

sqlite php getting unrecognized token: ":" error while inserting and parameterized query

I am working with sqlite for the first time.
Preparing a query string like
$articleInsertQuery = "INSERT INTO Articles VALUES (?, ?, ?, ?, ?)", ($i, $title, $content, $date, 93,);
It returns "Parse error". I also tried without passing parametrized query like
$articleInsertQuery = "INSERT INTO Articles VALUES ($i, $title, $content, $date, 93)";
ANd getting "Unable to prepare statement: 1, unrecognized token: ":" "
Any idea where I am doing wrong?
#arnoldIf you are using PDO for that.
The way to prepare and execute your query would be as follows.
$dbObject = new PDO('sqlite:sqlitedb');// NEW LINE
$articleInsertQuery = "INSERT INTO Articles VALUES (?, ?, ?, ?, ?)";
$query = $dbObject->prepare($articleInsertQuery);
$query->execute(array($i, $title, $content, $date, 93));
EDIT:
See sqlite3 prepare.
$articleInsertQuery = "INSERT INTO Articles VALUES (:i, :title, :content, :date, :int)";
$query = $dbObject->prepare($articleInsertQuery);
$query->bindValue(':i', $i, SQLITE3_INTEGER);
$query->bindValue(':title', $title, SQLITE3_TEXT);
$query->bindValue(':content', $content, SQLITE3_TEXT);
$query->bindValue(':date', $date, SQLITE3_TEXT);
$query->bindValue(':int', 93, SQLITE3_INTEGER);
$result = $query->execute();
Hope this helps.

Can you use mysqli prepared statements and transactions together?

All I want to know is if you can use mysqli's prepare, execute, and rollback together?
$m = new mysqli($dbhost,$dbuser,$dbpassword,$dbname);
$m->autocommit(FALSE);
$stmt = $m->prepare("INSERT `table` (`name`,`gender`,`age`) VALUES (?,?,?)");
$stmt->bind_param("ssi", $name, $gender, $age);
$query_ok = $stmt->execute();
$stmt = $m->prepare("INSERT `table` (`name`,`gender`,`age`) VALUES (?,?,?)");
$stmt->bind_param("ssi", $name, $gender, $age);
if ($query_ok) {$query_ok = $stmt->execute();}
if (!$query_ok) {$m->rollback();} else {$m->commit();}
Can you do this? Let's assume that the above code has a loop and or the variables get new data in them.
Best way to handle this is with exceptions (as always, darn PHP error/warning stuff). Simply because our commit() call may fail too. Note that finally is only available in newer PHP versions.
<?php
// Transform all errors to exceptions!
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
$connection = new \mysqli($dbhost, $dbuser, $dbpassword, $dbname);
$connection->autocommit(false);
$stmt = $connection->prepare("INSERT `table` (`name`, `gender`, `age`) VALUES (?, ?, ?)");
$stmt->bind_param("ssi", $name, $gender, $age);
$stmt->execute();
// We can simply reuse the prepared statement if it's the same query.
//$stmt = $connection->prepare("INSERT `table` (`name`, `gender`, `age`) VALUES (?, ?, ?)");
// We can even reuse the bound parameters.
//$stmt->bind_param("ssi", $name, $gender, $age);
// Yet it would be better to write it like this:
/*
$stmt = $connection->prepare("INSERT `table` (`name`, `gender`, `age`) VALUES (?, ?, ?), (?, ?, ?)");
$stmt->bind_param("ssissi", $name, $gender, $age, $name, $gender, $age);
*/
$stmt->execute();
$connection->commit();
}
catch (\mysqli_sql_exception $exception) {
$connection->rollback();
throw $exception;
}
finally {
isset($stmt) && $stmt->close();
$connection->autocommit(true);
}

Categories