Get query back from MYSQLi prepared statement - php

My prepared statement looks like this:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
// prepare and bind
$stmt = $conn->prepare("INSERT INTO `devices` (`deviceName`, `type`, `deviceToken`) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $deviceName, $deviceToken, $type);
$stmt->execute();
echo "executed";
$result = $stmt->get_result();
$conn->close();
And I want to echo the query.
I know the PDO method:
$binded_query = $stmt->queryString
But I need to use MYSQLi. So how can I do that?

$sql = "INSERT INTO `devices` (`deviceName`, `type`, `deviceToken`) VALUES (?, ?, ?)"
$stmt = $conn->prepare($sql);
echo $sql; // here you go

Related

My error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version

I got the problem in my blog. When I use single quote in textik this error appear.
INSERT INTO clanky (nadpis, textik, datum, autor, kategorie) VALUES (?, ?, ?, ?, ?);
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?, ?, ?, ?, ?)' at line 2
I already know that you cant use single quotes in string due to SQL injection. So im trying to fix it. I tried so many tutorials but nothing helped me.
<?php
if (isset($_POST["btn"])) {
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error){
die("ERROR: Could not connect. " . $conn->connect_error);
}
$nadpis = mysqli_real_escape_string($conn, $_POST['nadpis']);
$textik = mysqli_real_escape_string($conn, $_POST['textik']);
$datum = mysqli_real_escape_string($conn, $_POST['datum']);
$autor = mysqli_real_escape_string($conn, $_POST['autor']);
$kategorie = mysqli_real_escape_string($conn, $_POST['kategorie']);
$sql = "INSERT INTO `clanky` (`nadpis`, `textik`, `datum`, `autor`, `kategorie`)
VALUES (?, ?, ?, ?, ?);";
// '". $_POST['nadpis']."','". $_POST['textik']."','". $_POST['datum']."','". $_POST['autor']."','". $_POST['kategorie']."'
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)){
echo "SQL error";
} else {
mysqli_stmt_bind_param($stmt, "ssiss", $nadpis, $textik, $datum, $autor, $kategorie);
mysqli_stmt_execute($stmt);
}
if (mysqli_query($conn, $sql)) {
echo "New Record added";
header("Location: https://www.globalgraphicdesign.eu/welcome.php");
}else {
echo "Error" . $sql . "" . mysqli_error($conn);
}
$conn->close();
}
?>
I should redirect you to welcome page.
You're trying to prepare it, and using query(), thereby attempting to execute it twice. It will fail when using query(), because placeholders ? are not allowed there. You should also not escape input when using a prepared statement. You should also not output anything before a header() call. You can also enable MySQLi to throw exceptions, which makes error-handling much easier.
Your entire snippet can be reduced to the following.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
$conn = new mysqli($servername, $username, $password, $dbname);
if (isset($_POST["btn"])) {
$sql = "INSERT INTO `clanky` (`nadpis`, `textik`, `datum`, `autor`, `kategorie`)
VALUES (?, ?, ?, ?, ?);";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sssss", $_POST['nadpis'], $_POST['textik'], $_POST['datum'], $_POST['autor'], $_POST['kategorie']);
$stmt->execute();
header("Location: https://www.globalgraphicdesign.eu/welcome.php");
$stmt->close();
exit;
}
} catch (Exception $e) {
echo "Something went wrong. Please try again later";
error_log($e->getMessage());
}

PHP Insert Prepared Statement

I looking through different post regarding prepared statements. I am getting the following error
ERROR: Could not prepare query: INSERT INTO contact (, ,) VALUES (?,
?). You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near ' , , , ) VALUES (?, ?)' at line 1
I can't seem to figure out why I am getting this error. Everything I find online hasn't been helpful. I am hoping someone can point me in the right direction.
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Prepare an insert statement
$sql = "INSERT INTO tablename (name, email) VALUES (?, ?)";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "ss", $name, $email);
// Set parameters
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not execute query: $sql. " . mysqli_error($link);
}
} else{
echo "ERROR: Could not prepare query: $sql. " . mysqli_error($link);
}
// Close statement
mysqli_stmt_close($stmt);
// Close connection
mysqli_close($link);
?>
Thank you,
Found the answer for this issue.
<?php
$servername = "mysql";
$username = "root";
$password = "passwrd";
$dbname = "dbname";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,
$password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO tablename (name, email, commtype,
comment, confirm)
VALUES (:name, :email, :commtype, :comment, :confirm)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':commtype', $commtype);
$stmt->bindParam(':comment', $comment);
$stmt->bindParam(':confirm', $confirm);
// insert a row
$name = $_POST['name'];
$email = $_POST['email'];
$commtype = $_POST['commtype'];
$comment = $_POST['comment'];
$confirm = $_POST['confirm'];
$stmt->execute();
echo "New records created successfully";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
?>

What is the query binding marker for CURRENT_DATE when using mysqli prepared statements?

So I've finished building a question and answer site and am now trying to defend it against SQL injection but having problems with CURRENT_DATE. I want to insert current date with the question into db but what binding marker would that be? "s" for string is not working?
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "questions87";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
session_start();
$question = $_POST["question"];
$uname = $_SESSION['username'];
$qa_email =$_SESSION['email'];
// prepare and bind
$stmt = $conn->prepare("INSERT INTO login (username, username, q_date, qa_email) VALUES (?, ?, ?, ?)");
$stmt->bind_param("ssss", $question, $uname, CURRENT_DATE, $qa_email);
$stmt->execute();
if ($stmt) {echo "Thank you ". $uname . " Your question has been submitted " . "<br>";}
else {echo "Error: " . $sql . "<br>" . mysqli_error($conn);}
$stmt->close();
$conn->close();
?>
Use simple mysql function NOW() and remove placeholder for q_date:
$stmt = $conn->prepare("INSERT INTO login (username, username, q_date, qa_email) VALUES (?, ?, NOW(), ?)");
$stmt->bind_param("sss", $question, $uname, $qa_email);
Btw, I noticed, you have field username twice in this query. I suppose one of the occurences should be replaced with some other field.

Binding parameters in mysql

I'm trying to learn about binding parameters in MySQL. I tried this test but I'm getting the error "Call to a member function bind_param() on a non-object".
Am I doing something wrong?
Here is the updated code:
$sql = "INSERT INTO users (field1, field2, field3) VALUES (?, ?, ?)";
connect();
$stmt = $conn->prepare($sql);
$stmt->bind_param("sss", $value1, $value2, $value3);
$value1 = "test1";
$value2 = "test2";
$value3 = "test3";
$stmt->execute();
Here is the connect() function:
function connect(){
global $conn;
$conn = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
}
To bind params in a prepared query in PDO, pass an array containing your params to the execute function :
$result = $conn->prepare($sql);
$result->execute(array($value1, $value2, $value3));
UPDATE
For the mysqli version :
connect();
$result = $conn->prepare($sql);
$result->bind_param('sss', $value1, $value2, $value3);
$result->execute();
See http://php.net/manual/en/mysqli-stmt.bind-param.php

PHP Mysqli no errors, no querys

I'm trying to use mysqli instead of mysql queries, and it's not working.
Mysqli:
$mysqli->connect($db1['host'], $db1['user'], $db1['password'], $db1['database']);
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
no errors. If I try this query:
if(isset($_POST['username']))
{
$password = $_POST['p'];
$random_salt = hash('sha512', uniqid(mt_rand(1, mt_getrandmax()), true));
$password = hash('sha512', $password.$random_salt);
if ($insert_stmt = $mysqli->prepare("INSERT INTO members (username, email, password, salt) VALUES (?, ?, ?, ?)")) {
$insert_stmt->bind_param('ssss', $username, $email, $password, $random_salt);
$insert_stmt->execute();
}
echo "Success";
}
nothing is inserted, no errors with mysqli error.
Table structure is correct, and it says success. I'm new to mysqli, I'm used to mysql. Is there something I've missed with error reporting?
you have to do it like this way
$password = hash('sha512', $password.$random_salt);
$insert_stmt = $mysqli->prepare("INSERT INTO members (username, email, password, salt) VALUES (?, ?, ?, ?)");
$insert_stmt->bind_param('ssss', $username, $email, $password, $random_salt);
if($insert_stmt->execute())
{
echo "Success";
}
Actually you are first checking the query and after that binding the params, because of that it was just displaying Success.
Better try this, its from php manual
<?php
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno)
{
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli- >connect_error;
}
You could do the $stmt->execute(); in an if loop like this:
if ($stmt->execute()){
$result = $stmt->affected_rows;
if ($result) { echo "yay" } else { echo "boo"; }
}
else {
printf("Execute error: %s", $stmt->error);
}

Categories