No database selected [duplicate] - php

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 6 years ago.
I have created a 'db.php' file where I make a connection to my db:
$db_user = 'usprojus';
$db_pass = 'xxxxxx';
$db_host = 'localhost';
// Verbinden
$dblink = mysqli_connect($db_host, $db_user, $db_pass);
// Datenbank "myproject" auswaehlen
// Entspricht "USE myproject;"
$selected = mysqli_select_db($dblink, 'myproject');
if (!$selected) {
die ('Cannot use DB : '.mysqli_error($dblink));
}
mysqli_set_charset($dblink, 'utf8');
In order to test that is working I am trying to get data from my 'users' table:
require_once('db.php');
// Get all the data from the "users" table
$result = mysql_query("SELECT * FROM users")
or die(mysql_error());
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo 'user_id: '.$row['user_id'].'<br />';
echo 'date_registered: '.$row['date_registered'].'<br />';
echo 'last_login: '.$row['last_login'].'<br />';
echo 'username: '.$row['username'].'<br />';
echo 'email: '.$row['email'].'<br />';
echo 'password: '.$row['password'].'<br />';
echo 'photo: '.$row['photo'].'<br />';
echo 'description: '.$row['description'].'<br />';
echo 'notify: '.$row['notify'].'<br />';
}
But I get this error in the browser:
No database selected
For the life of me I cannot figure out where the problem lies.
Sorry, I know this is a newbie question, and it seems it has been posted here several times. But I could not figure it out.
Thank you for your time and patience.

You're mixing up mysqli_ and mysql_ functions.
I.e. mysqli_connect, mysqli_select_db, mysqli_set_charset but then mysql_query and mysql_fetch_array in your second file.
Choose one.

Perhaps you should use mysqli_query() (see php docs)

It looks like you are connecting to the database using the mysqli functions, but your query is using a mysql function.
Try switching your query to the mysqli function:
$result = mysqli_query("SELECT * FROM users")

The problem is here:
while($row = mysql_fetch_array( $result )) {
In your db.php you are connecting with the improved MySQL extension (mysqli).
But in your while loop you use the old MySQL extension.

Related

Converting from mysql _query to mysqli_query [duplicate]

This question already has answers here:
How to change mysql to mysqli?
(12 answers)
Closed 3 years ago.
I have many simple PHP files with MySQL queries that I need to modify since my webhost migrated from PHP5 -> PHP7. I am pretty much a PHP/MySQL beginner trying to wrap my head around the changes from MySQL to MySQLi.
I've begun reading the PHP docs re: MySQLi but am getting stuck on mysqli_query at the moment.
Here is the MySQLi code I've tried so far:
<?php
$con = mysqli_connect("localhost”, “my_user","my_password,"my_db”);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$result = mysqli_query("SELECT image, caption
FROM tbllinkcat, tblimages
WHERE tbllinkcat.catid = tblimages.catid
AND tbllinkcat.catid=1;");
while($row = mysql_fetch_array($result))
{
echo $row['image'];
echo "<br />";
echo $row['caption'];
echo "<br />";
}
mysql_close($con);
?>
I'm pretty sure the mysqli_connect code is working but I get errors on the mysqli_query code (error: Warning: mysqli_query() expects at least 2 parameters.
And I am pretty sure I will get errors on the mysql_fetch_array too once I correct mysqli_query. So for now I was wondering if someone could just show me an example of a mysqli_query that would work for the specific SQL statements in my code above? I will continue reading the PHP docs for MySQli and mysqli_query. Thank you.
mysqli_query needs two parameters:
Your database connection
A query
That will result in this:
$result = mysqli_query($con, "SELECT image, caption FROM tbllinkcat, tblimages WHERE tbllinkcat.catid = tblimages.catid AND tbllinkcat.catid=1;");
You also have some weird looking quotation marks in your connect function, correct them:
$con = mysqli_connect("localhost", "my_user", "my_password", "my_db");
To fetch the array, you would use:
while($row = mysqli_fetch_assoc($result))
{
echo $row['image'];
echo "<br />";
echo $row['caption'];
echo "<br />";
}
And finally, to close the connection:
mysqli_close($con);
Note: Just so you know, when using queries with user input, please use prepared statements and bind_param. This will prevent SQL injection attacks. I will show and example below.
$stmt = $db->prepare("SELECT * FROM users WHERE username = ?");
$username = $_POST['username'];
$stmt->bind_param('s', $username);
$result = $stmt->execute();
<?php
$con = mysqli_connect("localhost”,“my_user","my_password”,"my_db”);
//establish database connection
if (!$con)
{
die('Could not connect:'.mysqli_error());
}
$result = mysqli_query($con,"SELECT image,caption FROM tbllinkcat, tblimages WHERE tbllinkcat.catid = tblimages.catid AND tbllinkcat.catid=1");
//perform sql select query with database connection
while($row = mysqli_fetch_array($result))
{
echo $row['image'];
echo "<br />";
echo $row['caption'];
echo "<br />";
}
mysqli_close($con);
?>
For More Info read :-https://www.php.net/manual/en/mysqli.query.php

How do I obtain data through a MySQL Database using GET in PHP?

I've tried the solutions in this question, however mysql has been depricated for mysqli. Even with these changes it still doesn't return the information, instead returns an error, with nothing else (Nothing is heard from mysqli)
What i'm trying to do is kind of similar to the question linked, however it would look like this in the url: example.com?view-work=A01 It would search for A01 in the database, then return the Name, description, an image URL and date it was made live.
This is the code that i've been able to make using the answers from the question:
<?php
//Establishing a connection to the Artwork Database
mysqli_connect('localhost', 'dbuser', 'dbpassword');
mysqli_select_db('db');
$artworkidentifier = $_GET["view_work"];
//Returning the result, if there is one
$artworkidentifier = mysqli_real_escape_string($artworkidentifier);
$sql = "SELECT * FROM ArtDB WHERE art_refcode = '$artworkidentifier'";
$result = mysqli_query($sql);
if (!$result) {
echo "Something's gone wrong! ".mysqli_error();
}
$data = mysqli_fetch_assoc($result);
echo $data["Artwork_Name"];
echo $data["Artwork_Description"];
echo $data["Artwork_URL"];
echo $data["DateUploaded"];
?>
Seems like the cause of these errors was my own incompetence, also probably the fact I'm kind of new to PHP and MySQL in general. I learnt that I needed to reference my connection in some of the commands for them to successfuly process after adding the debug exception mentioned in the OP's comments.
As someone also pointed out, Yes this code is still vulnerable to other types of SQL injection, I'll be addressing these before the final version of the code goes live.
Fixed Code:
<?php
//Establishing a connection to the Artwork Database
$link = mysqli_connect('localhost', 'dbusr', 'dbpasswd', 'db');
//Exeptional Debugging
ini_set('display_errors', 1);
ini_set('log_errors', 1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
if (!$link) {
echo "Error: Unable to connect to MySQL!";
echo "Error No.".mysqli_connect_errno();
echo "Error in question: ".mysqli_connect_error();
exit;
}
$artworkidentifier = $_GET["view_work"];
//Returning the result, if there is one
$artworkidentifier = mysqli_escape_string($link, $artworkidentifier);
$sql = "SELECT * FROM ArtDB WHERE art_refcode = '$artworkidentifier'";
$result = mysqli_query($link, $sql);
if (!$result) {
echo "Something's gone wrong!"; //This line will be changed later to sound more professional
}
$data = mysqli_fetch_assoc($result);
echo $data["Artwork_Name"];
echo $data["Artwork_Description"];
echo $data["Artwork_URL"];
echo $data["DateUploaded"];
?>

Sql echo row with php [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 7 years ago.
I can connect to DB but i cant echo , all time that said 0 results but my DB have TABLE (text) with 2 COLUMN id and text and i have inserted text in my table.
$con = mysqli_connect("localhost","1078362","nenaddurmisi022");
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT vesti FROM comment";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0)
{
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo $row["vesti"]."<br>";
}
}
else {
echo "0 results";
}
mysqli_close($con);
You're using all mysqli functions except for your database connection. Try changing the first line to...
$con = mysqli_connect("localhost", "1078362", "nenaddurmisi022");
...and change the last line to...
mysqli_close($con);
I'm guessing there are a lot of errors generated by this script, but you're not seeing them. You should add these lines to the top of the script...
error_reporting(E_ALL);
ini_set('display_errors', 1);
try
$sql = "SELECT * FROM text";
instead of
$sql = "SELECT text FROM text";
also be sure you'r table name is text.
one last thing you could try is to replace
echo $row["text"]."<br>";
by
print_r($row);
to see if there's a result set from you'r Database

Outputting contents of database mysqli

Hi I know this is a little general but its something I cant seem to work out by reading online.
Im trying to connnect to a database using php / mysqli using a wamp server and a database which is local host on php admin.
No matter what I try i keep getting the error Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given when i try to output the contents of the database.
the code im using is:
if (isset($_POST["submit"]))
{
$con = mysqli_connect("localhost");
if ($con == true)
{
echo "Database connection established";
}
else
{
die("Unable to connect to database");
}
$result = mysqli_query($con,"SELECT *");
while($row = mysqli_fetch_array($result))
{
echo $row['login'];
}
}
I will be good if you have a look at the standard mysqli_connect here
I will dont seem to see where you have selected any data base before attempting to dump it contents.
<?php
//set up basic connection :
$con = mysqli_connect("host","user","passw","db") or die("Error " . mysqli_error($con));
?>
Following this basic standard will also help you know where prob is.
you have to select from table . or mysqli dont know what table are you selecting from.
change this
$result = mysqli_query($con,"SELECT *");
to
$result = mysqli_query($con,"SELECT * FROM table_name ");
table_name is the name of your table
and your connection is tottally wrong.
use this
$con = mysqli_connect("hostname","username","password","database_name");
you have to learn here how to connect and use mysqli

How does one implement a MySQL database into a webpage?

I am a complete database newbie. So far, I know that I can connect to MySQL using PHP's mysql_connect() command, but apart from that, I really don't see how to take that data and put it onto a web page.
a) are there ways other than mysql_connect()
b) lets say I had a table of data in mysql and all I wanted was for that table (for example: list of names and telephone numbers) to now appear on my web page. I can't for the life of me find a tutorial for this.
<?
$database_name = "dbname";
$mysql_host = "localhost"; //almost always 'localhost'
$database_user = "dbuser";
$database_pwd = "dbpass";
$dbc = mysql_connect($mysql_host, $database_user, $database_pwd);
if(!$dbc)
{
die("We are currently experiencing very heavy traffic to our site, please be patient and try again shortly.");
}
$db = mysql_select_db($database_name);
if(!$db)
{
die("Failed to connect to database - check your database name.");
}
$sql = "SELECT * FROM `table` WHERE `field`= 'value'";
$res = mysql_query($sql);
while($row = mysql_fetch_assoc($res)) {
// code here
// access variables like the following:
echo $row['field'].'<br />';
echo $row['field2'];
}
?>
Check out mysql_fetch_assoc mysql_fetch_array and mysql_fetch_object
This is the very basics, you will want to search for tutorials. There are many about.

Categories