PHP SQL request returning null value - php

I'm just starting PHP and keep returning null for my SQL query. I am successfully connected to the database and have copied and pasted the query even straight from the database.
<?php
$servername = "localhost";
$username = "username";
$password = "";
$dbname = "customerbasics";
$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM `orders`";
$result = $conn->query($sql);
if ($result == NULL){
echo 'No results';
};
if ($result->num_rows > 0) {
echo 'Rows returned';
}
} else {
echo "0 results";
}
$conn->close();
?>
This is what the browswer prints:
Update: Error checking added:
Fatal error: Uncaught mysqli_sql_exception: No database selected

Add the fourth parameter to your connection function
$conn = new mysqli($servername, $username, $password, $dbname);
You have forgotten the database name in your connection. For more information, you can go here. Plus I recommend you to learn PDO or prepared statements

First, you have to select database before executing a query:
mysqli_select_db($conn, $dbname);
Then execute your query:
$sql = "SELECT * FROM `orders`";
Other way, you can also specify database name directly every executing a query:
$sql = "SELECT * FROM $dbname.`orders`";

Related

Selecting data from sql database doesn't work. how do I fix it?

I am trying to select data from a database. I do have a successful connection, but it seems like the query doesn't work even though I know for sure that the query is right. What am I doing wrong?
If I execute the code below, the result I get is: "Connected successfullyBad query". The 'Bad query' should mean that the query is wrong, but I checked it and it isn't wrong...
<?php
$servername = "localhost";
$username = "root";
$password = "usbw";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql ="SELECT * FROM `producten`";
$result = mysqli_query($conn, $sql) or die("Bad query");
$conn->close();
?>
I expect to only see "connected successfully"
You are missing your database name. You can do it two ways, or in the connect statement:
$conn = new mysqli($servername, $username, $password,$database);
Or you can do it in your select statement:
$sql ="SELECT * FROM `yourdatabase`.`producten`";
If you donĀ“t set your database your query is wrong
Your query is right just write your database name in mysqli constructor.
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
Visit: https://www.php.net/manual/en/mysqli.construct.php
Please give database name also, check below code.
<?php
$servername = "localhost";
$username = "root";
$password = "usbw";
$dbname = ""; //Enter database name
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql ="SELECT * FROM `producten`";
$result = mysqli_query($conn, $sql) or die("Bad query");
$conn->close();
?>

Trying to read the status of a user in my mysql databse from php

Trying to read the status of a user in my mysql database from php
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Find status for row with Username of the Url?username=
$sql = "SELECT Status FROM Users WHERE Username = '".$_GET["username"]."'";
$result = mysql_query($sql) or die('Error connecting to database');
$username = mysql_result($result, 0, "Status");
echo 'Username Status is ' . $Status;
mysqli_close($conn);
?>
In result I'm getting is this:
Fatal error: Uncaught Error: Call to undefined function mysql_query() in /storage/ssd4/269/2113269/public_html/teststat.php:11 Stack trace: #0 {main} thrown in /storage/ssd4/269/2113269/public_html/teststat.php on line 11
Your syntax for mysqli is not correct, because mysqli is different from mysql syntax.
MySQLi stands for MySQL improved. It's an object-oriented interface to
the MySQL bindings which makes things easier to use.
I suggest you to use the mysqli version and don't mixup mysql syntax with mysqli syntax.
$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 Status FROM Users WHERE Username = '".$_GET["username"]."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row or remove while loop if you wish
while($row = $result->fetch_assoc()) {
echo 'Username Status is ' . $row['Status'] ;
}
} else {
echo "0 results";
}
$conn->close();
You mixed up mysql and mysqli
$result = mysql_query($sql) or die('Error connecting to database');
$username = mysql_result($result, 0, "Status");

SQL database connection in PHP successful, but I can't query it [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 6 years ago.
<?php
$servername = "localhost";
$username = "user";
$password = "pass";
$dbname = "test";
$tablename = "mapcoords";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error)
{
echo "Failure";
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql = "SELECT (lat, lng) FROM mapcoords";
$result = $conn->query($sql);
while($row = $result->fetch_assoc())
{
echo "ok";
}
$conn->close();
?>
Here is the code. So like I said, it can connect successfully, but the code won't successfully query. What's weird is that if I copy and paste the same code, which seems to be EXACTLY the same, it works. It makes no sense. I can't find a single difference between their code and my code besides the way they space things and the way I space things. Here is their code:
<?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 (lat, lng) FROM mapcoords";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["lat"]. " " . $row["lng"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
The problem is that this query:
SELECT (lat, lng) FROM mapcoords
returns the folloowing error:
[21000][1241] Operand should contain 1 column(s)
You have to change the query to
SELECT lat, lng FROM mapcoords

converting from MySQL to MySQLi Object-oriented

Ok, so I've been informed that it would be best practice to convert over to the new mysqli
So I've been working on this on a new site, so far so good, but I ran into a problem where I can't figure out how to convert it for my search query
I have a search feature added to my site, but now I can't get it to work.
This was my old code:
$query = "SELECT * FROM snippet_tools WHERE `db_title` LIKE ".sql_val('%'.$_GET['search'].'%')." OR `db_body`=".sql_val('%'.$_GET['search'].'%');
$result = mysql_query($query) or die("<b>A fatal MySQL error occured</b>.<br />Query: ".$query."<br />Error: (".mysql_errno().") ".mysql_error());
$anymatches = mysql_num_rows($result);
if ($anymatches == 0 ) {
I've upgraded my code to user oo
this is what I have:
$servername = "localhost"; $username = "xxxxxxxxx"; $password = "xxxxxxxxx"; $dbname = "xxxxxxxxxxxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql_search = "SELECT * FROM `questions` WHERE `q_title` LIKE ".sql_val('%'.$_GET['search'].'%')." OR `q_answered` LIKE ".sql_val('%'.$_GET['search'].'%');
$result = $conn->query($sql_search);
$anymatches = $result->num_rows;
if ($anymatches == 0 ) {
but every time I run it to perform a search I keep getting this error message:
Notice: Trying to get property of non-object in H:\root\site5\questions.php on line 611
You can refer W3 School site and get basic idea about the variations of MySQL and MySQLi and their functions. It is really helpful to go ahead with your project.
Ex Database connection example in both ways
So you can solve your problem based on that concept. Try to extract concepts.
Try this approach!
<?php
error_reporting(E_ALL);
$servername = "localhost"; $username = "root"; $password = "root"; $dbname = "cities";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$get = array('search' => "Lon");
$sql_search = "SELECT * FROM cities WHERE (city_name LIKE '%$get[search]%')";
$result = $conn->query($sql_search);
$anymatches = $result->num_rows;
if ($anymatches == 0 ){
echo "No matches!";
}
else
{
echo $anymatches . " match found!";
}
?>

Returning results from database

I am trying to do a simple SELECT to return rows of data from my database. I have a valid connection from my database so I know the issue is not there. I have ensured the names of each column are correct but it just returns 0 results.
My table inside the db is called 'user' and here is the members.php file:
<?php include 'header.php'; ?> <- this is where the db conect file is pulled in.
<?php
$sql = "SELECT id, username, email_address FROM user";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo
$row["id"];
}
} else {
echo "0 Members";
}
$conn->close();
?>
Just for ref here is my DB connection (Not the most secure i am just testing):
<?php
$servername = "localhost";
$username = "***********";
$password = "**********";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully<br><br>";
?>
you didnt select your database
$conn=new mysqli($servername, $username, $password);
this require another parameter which is your d.b name
$conn=new mysqli($servername, $username, $password,$db_name);

Categories