Something is wrong with sql query [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Please check this code and let me know if there is any mistakes in it.
// Create connection
$conn = mysqli_connect($servername, $username, $password, $shop_item);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$item_sql = "SELECT * FROM shop-items";
mysqli_query($conn, 'SET CHARACTER SET utf8;');
$result_item = mysqli_query($conn, $item_sql);
echo var_dump($result_item); //returns: bool(false)
if (mysqli_num_rows($result_item) > 0) { // doesn't execute. the error is "mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean";

As I mentioned shop-items is treated by mysql as shop minus items.
If your table name is really shop-items - you should use backticks to escape it:
$item_sql = "SELECT * FROM `shop-items`";
And for checking errors you can use mysqli_error() function:
$err = mysqli_error($conn);
echo $err;

It could be better to use structure similar to this:
$conn = new mysqli('localhost', 'root', 'password', 'your_database');
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql="SELECT * FROM shop-items";
if ($result = $conn->query($sql)) {
// actions in case of success
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

It may be an issue with the dash. Have you tried
SELECT * FROM `shop-items`

I would try and use the following code for all my queries from PHP to you database because as someone mentioned before with what you're using errors can occur from not syntax:
$mysqli = new mysqli("localhost", "user", "password", "DB");
/* Check conection */
if (mysqli_connect_errno()) {
printf("Conection error: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * FROM shop-items";
if ($stmt= $mysqli->prepare($query)) {
/* execute the query */
$stmt->execute();
/* Bind the results to variables */
$stmt->bind_result($col1, $col2); //as many variables as columns the query will return
/* obtener los valores */
while ($stmt->fetch()) {
//do something with the results
}
/* close the query */
$stmt->close();
}
/* close the DB connection */
$mysqli->close();
?>
Hope this helps!!

Related

How can I change my SQL statements to be prepared (and secure) statements? [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 3 years ago.
Basically I want to protect myself from SQL injections. I have tried searching online and watching videos but cannot understand exactly what I have to change because as far as I can tell, everyone does it a little bit differently. Any help is appreciated!
?php
// Create connection
$con = mysqli_connect("IPAddress","User","Password","DBName");
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
$sql = "INSERT INTO Email_Subs (email)
VALUES ('$_POST[email]')";
if ($con->query($sql) === TRUE) {
echo "You have successfully subscribed!";
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
$con->close();
?>
You must first use new mysqli() instead of mysqli_connect() to avoid any error in the next php versions
<?php
/* CONNECTION */
$database_connection = new StdClass();
/** MySQL hostname */
$database_connection->server = 'localhost';
/** MySQL database username */
$database_connection->username = 'root';
/** MySQL database password */
$database_connection->password = '';
/** The name of the database */
$database_connection->name = 'yourdatabasename';
/* ESTABLISHING THE CONNECTION */
$database = new mysqli($database_connection->server, $database_connection->username, $database_connection->password, $database_connection->name);
if($database->connect_error) {
echo 'connection failed';
}
?>
Then do smething like this :
$stmt = $database->prepare("INSERT INTO Email_Subs (email) VALUES (?)");
$stmt->bind_param("s", $_POST[email]);
$stmt->execute();
$stmt->close();
$database->close();

SQLi Error when trying to echo a certain ID in PHP

I am making a status update page for practicing PHP and MySQL.
I am currently trying to echo the saved status on the page.
The statuses are saved in a row called "Status" and they are all given a certain ID in a row called "statusID."
The problem I am having is which fetch I want to use because converting it into a string using (string)$var doesn't work. ($var is an example).
Also, the $idNum variable is something for later use, shouldn't have anything to do with this.
Here is the code: (Obviously the first variables are censored so none tries to connect to the database, the connection working in the actual code.)
The problem lies in the $fetchRes I believe.
<?php
$idNum = 1;
$servername = "censored";
$username = "censored";
$password = "censored";
$db_name = "censored";
$conn = mysqli_connect($servername, $username, $password, $db_name);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Status FROM SavedStatuses WHERE statusID=1;";
$statusQuery = mysqli_query($conn, $sql);
$fetchRes = mysqli_fetch_assoc($statusQuery);
if($conn->query($sql) == TRUE)
{
echo $fetchRes;
} else {
echo "Failed to retrieve status, error: " . $conn->error;
}
?>
As I mentioned in comments, you are querying twice and not looping over (successful) results.
A "loop" is to use either a while or a foreach. I used a while loop for this example.
From the "official" manual:
http://php.net/manual/en/mysqli-result.fetch-assoc.php
Example:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
/* free result set */
$result->free();
}
/* close connection */
$mysqli->close();
?>
So in your case, your code would read as:
Sidenote: Status and status are two different animals, so make sure the letter case matches (in the loop).
<?php
$mysqli = new mysqli("censored", "censored", "censored", "censored");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT Status FROM SavedStatuses WHERE statusID=1";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
echo $row["Status"];
}
/* free result set */
$result->free();
}else{
echo "The query failed: " . mysqli_error($mysqli);
}
/* close connection */
$mysqli->close();
?>

php mysqli SELECT doesnt return row [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have this code:
$check_user = "SELECT * FROM privateChats WHERE name = '$category'";
$result = mysqli_query($conn,$check_user);
$row = mysqli_fetch_assoc($result);
if($row["user1"] == $login_session or $row["user2"] == $login_session){
$sql = "SELECT * FROM privateChat WHERE name = '$category' ORDER BY position DESC";
}
// it goes on
It gets stuck at $result = mysqli_query($conn,$check_user); it doesn't give an error either.
There is a table called privateChats and there is a record in it.
My connection code:
$servername = "localhost";
$username = "thewhateverclub";
$password = "password";
$dbname = "my_thewhateverclub";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (mysqli_connect_error($conn)) {
die("Connection failed: " . mysqli_connect_error($conn));
}
Try this -
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM privateChats WHERE name = '$category'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Data1 " . $row["column1"]. " - Data2: " . $row["column2"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
Also add this line at the start of your php script.
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
However, this doesn't make PHP to show parse errors - the only way to show those errors is to modify your php.ini with this line:
display_errors = on
You need to check mysqli Errors by below way:-
$conn = mysqli_connect("localhost", "my_user", "my_password", "my_db");
//check connection error
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
// check variable is set or not
$category = isset($category) ? $category : 'notSet';
$check_user = "SELECT * FROM privateChats WHERE name = '$category'";
$result = mysqli_query($conn,$check_user);
// Check for query errors
if(!$result){
printf("Error: %s\n", mysqli_error($conn));
}
$row = mysqli_fetch_assoc($result);
Hope it will help you :)

mysqli SELECT query not working, for unknown reason [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Here is my php for connecting to a database and querying the table "userActivityTime", in which there is one row. I am not having trouble connecting to the database (i.e. no errors), but my query is not working, and despite looking all over the internet, I cannot figure out why. Hoping you all can help. Thanks so much in advance!
<?php
// ESTABLISH TABLE AND COLUMN NAMES
$mysqli = new mysqli("*****", "****", "*****", "****");
// MAKE SURE CONNECTION SUCCEEDED
if ($mysqli_connection->connect_error) {
echo "Not connected, error: " . $mysqli_connection->connect_error;
exit();
} else {
echo "connected";
}
$query = "SELECT 'userDailyTime' FROM 'userActivityTime'";
if ($mysqli->query($query)) {
echo $mysqli->error;
}
exit();
?>
use back-ticks if necessary not single quotes:
SELECT `userDailyTime` FROM `userActivityTime`
or just
SELECT userDailyTime FROM userActivityTime
Edit:
An example from the internet, worm your stuff into the concept.
<?php
$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 id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
You don't need to put the table and column names in quotes. You are telling it to echo $mysqli->error when the query is successful (prepend it with an exclamation mark) . Also, you create $mysqli then refer to it as $mysqli_connection, so I am not sure how your code works.
Try this:
<?php
// ESTABLISH TABLE AND COLUMN NAMES
$mysqli = new mysqli("*****", "****", "*****", "****");
// MAKE SURE CONNECTION SUCCEEDED
if ($mysqli->connect_errno) {
echo "Not connected, error: " . $mysqli->connect_error;
return false;
} else {
echo "connected";
}
$query = "SELECT userDailyTime FROM userActivityTime";
if (!$mysqli->query($query)) {
echo $mysqli->error;
}
return true;
?>

PHP: Trouble using mysqli

I used this php code in order to make a select on my database:
$check = 'true';
$request = trim(strtolower($_REQUEST['username']));
$query_username=sprintf("SELECT * FROM users WHERE username = '$request'");
$database= mysql_pconnect($hostname, $username, $password) or die(mysql_error());
mysql_select_db($mydatabase, $database);
$resultUsers = mysql_query($query_username, $mydb) or die(mysql_error());
$usernameFound= mysql_num_rows($resultUsers);
if ($usernameFound> 0) {
$check = 'false';
}
The above code works good.
But now I'm trying to convert it using mysqli. So I rewrited the code in this way:
$connectiondb = new mysqli($hostname, $username, $password, $database);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$request = trim(strtolower($_REQUEST['username']));
$query=sprintf("SELECT * FROM utente WHERE username = '$request'");
if(!$result = $connectiondb->query($query)){
die('Error in query execution [' . $connectiondb->error . ']');
}
$rows = $result->num_rows();
$result->free();
$connectiondb->close();
if($rows>0){
$check = 'false';
}
But this does not work! No error is generated, but I can't obtain the right result.
What can be the problem?
It should be $rows = $result->num_rows;
I also recommend you switch to using prepared statements when using mysqli, your current code is vulnerable to injections.

Categories