PHP Mysqli no errors, no querys - php

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);
}

Related

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;
?>

Why does the following not appear to open an SQL connection?

I find that the folowing script hangs for some reason. It will load and PHP doesn't see any errors, but it will not process the data (noting that we are in a context where I have a seperate login database open.)
In process.php we have the following:
<? PHP
//Process the POST data in prepration to write to SQL database.
$_POST['chat_input'] = $input;
$time = date("Y-m-d H:i:s");
$ip = $_SERVER['REMOTE_ADDR'];
$name = $_SESSION['username'];
$servername = "localhost";
$username = "id3263427_chat_user";
$password = "Itudmenif1!Itudmenif1!";
$dbname = "id3263427_chat_user";
$id = "NULL";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = 'INSERT INTO `chat` (`id`, `username`, `ip`, `timestamp`,
`message`) VALUES ('$id','$name', '$ip', '$time', '$input')';
if(mysqli_query($link, $sql)){
mysqli_close($conn);
header('Location: ../protected_page.php');
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
?>
the html form passed to the script above is as follows:
<form action="/process.php" method="post" id="chat">
<b> Send A Message (500 Character Max):</b><br>
<textarea name="chat_input" form="chat" size="500"></textarea>
<input type="submit" value=submit>
</form>
Not sure what's going on with this.
You got the syntax error because you're closing the $sql string before $id with your '.
What is this about your $id variable? With your current code you will insert the String "NULL". If you want to set the sql value null you should use $id = null; or just don't insert any value.
If you want your database to set an id, also leave it blank.
$input = $_POST['chat_input'];
$id = null;
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error){
die("ERROR: Could not connect. " . $conn->connect_error);
}
First solution
If this isn't a production code, you could insert the variables directly into the statement, but you should use " instead of ' for your sql string, so you can insert variables and ' without closing the string.
$sql = "INSERT INTO chat (id, username, ip, timestamp, message) VALUES ('$id', '$name', '$ip', '$time', '$input')";
if($conn->query($sql) === true) {
$conn->close();
header('Location: ../protected_page.php');
} else {
echo "ERROR: Could not able to execute $sql. " .$conn->error;
$conn->close();
}
Second solution
A better approach would be a prepared statement.
$stmt = $conn->prepare('INSERT INTO chat (username, ip, timestamp, message) VALUES (?, ?, ?, ?)');
$stmt->bind_param("ssss", $username, $ip, $time, $input);
if($stmt->execute()) {
$stmt->close();
$conn->close();
header('Location: ../protected_page.php');
} else {
echo "ERROR: Could not able to execute $stmt. " . $conn->error;
$stmt->close();
$conn->close();
}
The "s" in bind_param() defines a string at the given position, if you want to insert an integer, use "i" instead.
e.g. bindParam("sis", $string, $integer, $string);

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.

Get query back from MYSQLi prepared statement

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

how can fix the error Call to a member function bind_param() on a non-object in Can"t Insert in to database

I cant get insert into database and bind_param to work.
$query="INSERT INTO user (UserName,email,Password) VALUES ('?','?','?')";
$inst=$this->db->prepare($query);
$inst->bind_param("sss",$username,$email,$password);
if(!$inst) {
echo "Query Prep Failed: %s\n", $conn->error;
exit;
}
$username="";
$email="";
$password="";
$inst->execute();
Be sure that you use a instance of mysqli:
$mysqli = new mysqli("host", "user", "password", "database");
$stmt = $mysqli->prepare("INSERT INTO user (UserName, email, Password) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $username, $email, $password);
$stmt->execute();

Categories