Resolve MySQLi empty query error [duplicate] - php

This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 6 years ago.
Warning received:
Warning: mysqli::query(): Empty query in C:\wamp\www\otp-task\welcome.php on line 62
My database connection is here:
function insertDB($email, $OTP , $phonenumber )
{
$servername = "localhost";
$username = "root";
$password = "";
$db = "dbotp";
$conn = new mysqli($servername, $username, $password, $db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// insert to db and close the connection, default time attribute is 60 mins
// the table name is onetime and will hold the otp and phonenum and email
$res = mysqli_query($conn, "INSERT INTO onetime (otpnum,email,phoneNum,action) VALUES ('$OTP' , '$email' , '$phonenumber','success')");
// $res = "INSERT INTO onetime (otpnum,email,phoneNum,action) VALUES ('$OTP' , '$email' , '$phonenumber', 'success')";
if ($conn->query($res) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $res . "<br>" . $conn->error;
}
$conn->close();
}

The following two is just a different format for the same thing:
$conn->query(...)
and
mysqli_query($conn, ...)
Once you executed one of them, use the return value of it instead of re-executing the query:
$res = $conn->query(...)
if ($res) {
// ...
}
Please also read about prepared statements: http://php.net/manual/en/mysqli-stmt.prepare.php

Related

Checking if username exists in DB with PHP and MySQL [duplicate]

This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
How to check if a row exists in MySQL? (i.e. check if username or email exists in MySQL)
(4 answers)
How to prevent duplicate usernames when people register?
(4 answers)
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 1 year ago.
Been struggling with this for a few days, and read a ton of similar problems but still haven't been able to figure it out. I am trying to take user information via an html form and update my database with it, but only if the username doesn't already exist...
Issue 1: No matter what, it can keep creating entries with the same username
Issue 2: I keep getting the error Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, bool given
I am sure they are connected but for the life of me I can't figure out what the fix is.
<?php
//declare variables
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "mypassword";
$db = "user_info";
if (!empty($_POST)) {
//connect to mysqli
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $db);
//check connection
if ($mysqli->connect_error) {
die('Connect Error: ' . $mysqli->connect_errno . ': ' . $mysqli->connect_error );
}
//declare user variables
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$user_name = $_POST['user_name'];
$pass = $_POST['pass'];
$address = $_POST['address'];
$phone = $_POST['phone'];
//get data from form
$sql = "INSERT INTO users (first_name, last_name, user_name, pass, address, phone) VALUES
('{$mysqli->real_escape_string($first_name)}',
'{$mysqli->real_escape_string($last_name)}',
'{$mysqli->real_escape_string($user_name)}',
'{$mysqli->real_escape_string($pass)}',
'{$mysqli->real_escape_string($address)}',
'{$mysqli->real_escape_string($phone)}')";
// ** HERE IS WHERE I AM HAVING ISSUES **
//query to see if entered username already exists
$result = $mysqli->query("SELECT * FROM users WHERE user_name =$user_name");
//alert if user name taken
if (mysqli_num_rows($result) > 0) {
echo "<b>Username already taken! Please select another.</b>";
} else {
//continue to insert into database if username is unique
$insert = $mysqli->query($sql);
//print response from mysql
if ($insert) {
echo "Success! Row ID: {$mysqli->insert_id}";
} else {
die("error: {$mysqli->errno}");
}
}
//close our app
$mysqli->close();
}
?>
Try like this
<?php
if (!empty($_POST)) {
//connect to mysqli
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $db);
//check connection
if ($mysqli->connect_error) {
die('Connect Error: ' . $mysqli->connect_errno . ': ' . $mysqli->connect_error );
}
//declare user variables
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$user_name = $_POST['user_name'];
$pass = $_POST['pass'];
$address = $_POST['address'];
$phone = $_POST['phone'];
$query = $mysqli->prepare("SELECT count(*) FROM users WHERE user_name = ?");
$query->bind_param('s', $user_name);
$query->bind_result($cnt);
$query->execute();
$query->store_result();
$query->fetch();
$query->close();
if ($cnt > 0) {
echo "<b>Username already taken! Please select another.</b>";
} else {
$query = $mysqli->prepare("INSERT INTO users (first_name, last_name, user_name, pass, address, phone) VALUES (?,?,?,?,?,?)");
$query->bind_param('ssssss', $first_name, $last_name, $user_name, $pass, $address, $phone);
$query->execute();
if ($query->execute()) {
echo "Success! Row ID: {$query->insert_id}";
} else {
die("error: {$query->errno}");
}
$query->close();
}
}

error in passing multiple parameters in MySQL stored procedure from php [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 4 years ago.
i have an stored procedure InsertStudent in MySQL DB which is working fine from database,
now i am calling the above Sp from php by giving all the parameter its giving following error
Error: CALL InsertStudent(Mohd Maaz,455,1,2,0)
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server
version for the right syntax to use near 'Maaz,455,1,2,0)' at line 1
here is my code
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "funed";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$StudentName = "Mohd Maaz";
$StudentClass = 1;
$StudentRollNo = 455;
$StudentSection = 2;
$StudentIsdltd = 0;
$sql = "CALL InsertStudent(".$StudentName.",".$StudentRollNo.",".$StudentClass.",".$StudentSection.",".$StudentIsdltd.")";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
You just forgot to quote the parameters
replace
$sql = "CALL InsertStudent(".$StudentName.",".$StudentRollNo.",".$StudentClass.",".$StudentSection.",".$StudentIsdltd.")";
with
$sql = "CALL InsertStudent('".$StudentName."','".$StudentRollNo."','".$StudentClass."','".$StudentSection."','".$StudentIsdltd."')";
or I prefer to use the variables in the string directly without concatenating
$sql = "CALL InsertStudent('$StudentName','$StudentRollNo','$StudentClass','$StudentSection','$StudentIsdltd')";

Returns Internal Server Error (500) after connecting to MySQL database [duplicate]

This question already has an answer here:
PHP: 500 Error to error page
(1 answer)
Closed 5 years ago.
I want to select data from a MySQL database with PHP. Problem is, that when I try to echo out the $result, I get a 500 Error. When I leave out the echo $result;, I get a 200 OK return.
You guys gut any ideas?
Here's the PHP:
$q = $_GET['q'];
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "test";
//establish connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check Conncetion
if(!$conn) {
die("Connection failes: " . mysqli_connect_error());
}
$sql = "SELECT * FROM phptesting";
$result = mysqli_query($conn, $sql);
echo $result;
/*
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. "- Name: " . $row["first_name"]. " " . $row["last_name"]";
}
*/
mysqli_close($conn);
For your info, $q is just an integer with an id for testing it out.
echo is used to output primitive data type such as String, Integers.
$result holds the metadata of your SQL query result.
In ur code ur trying to echo the metadata. And This caused PHP fatal error.

"SELECT email FROM table WHERE name=$name"; in PHP [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
I am facing trouble printing the details of a username from MYSQL. The quotes in WHERE name = "xxx" is the cause.
This is the code:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT name, email FROM MyTable WHERE name=$name";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["name"]. " - email: " . $row["email"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
How do I replace the WHERE name = $name?
you are missing an ''
should be:
WHERE name = '$name'
notice the quotes
I think you shoudl use this notation (previously be sure of a proper sanitize of $name for preventing potential SQL injection)
"SELECT name, email FROM MyTable WHERE name='$name'";

PHP (mysqli) to find single value [duplicate]

This question already has answers here:
Single result from database using mysqli
(6 answers)
Closed 1 year ago.
I know how to search using mysqli to find if there is at least one match. How do I go about retrieving another value from a found row. It must just require changing 1 or 2 things.
Imagine I have the following DB:
ID | emailaddress | password
1 | dummy#email.com | DUMB1PASS
2 | second#email.com | DUMB2Pass
I can use the following code to verify if the the email address "dummy#email.com" exists. How would I look up the password associated with that row (i.e. the row containing dummy#email.com).
$email = "dummy#email.com";
$servername = "correct"; $username = "correct"; $DBpass = "correct"; $dbname = "correct";
$conn = new mysqli($servername, $username, $DBpass, $dbname);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT emailaddress FROM registration WHERE emailaddress = '$email'";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
echo "we found a match";
}
else
{
echo "we did not find a match";
}
I imagine I can do something like:
$email = "dummy#email.com";
$servername = "correct"; $username = "correct"; $DBpass = "correct"; $dbname = "correct";
$conn = new mysqli($servername, $username, $DBpass, $dbname);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT password FROM registration WHERE emailaddress = '$email'";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
echo "the value is '$result'";
}
else
{
echo "we did not find a match";
}
However, it produces this error:
Catchable fatal error: Object of class mysqli_result could not be converted to string in MYPAGE on line XX.
I think that the cause of this is likely that $result is an array or something. However, I don't know enough about sql/php to know if that is the problem, or how to pull the result from it if it is the case.
I'd really appreciate any help.
You need to fetch the row first, try this:
if ($result->num_rows) {
$row = $result->fetch_row();
echo 'the value is: ', $row[0];
}

Categories