2

Apologies if this seems very simple. I'm just starting with PHP and MySQL and i've been stuck with this for the last 2 days.

Essentially, I am writing a user reg/login system and i'm having problems (apparently) selecting the database that user credentials will be stored in.

My code stripped down to the essentials.

<?php
$servername = "localhost";
$username = "qtesting";
$password = "test";
$database = "qtesting";

$mysqli = mysqli_connect($servername, $username, $password) or die('Error connecting to MySQL server.');;
if($mysqli->connect_errno > 0){
    die('Unable to connect to database [' . $mysqli->connect_error . ']');
}
$result=mysqli_query("USE qtesting");
echo $result;

If I allowed my full code to run, it returns with "No database selected" when I attempted to run any further queries. So I pared the code back line-by-line to what you see above and turned on query logging to see what is going on.

According to my query log, a connection is successfully opened to the server but the USE query does not appear to be running. To clarify, I created the $result variable and asked PHP to echo $result for debugging purposes.

Also, you may notice I have defined a $database variable. I also attempted to select the database while establishing a connection by mysqli_connect($servername, $username, $password, $database)

Does anyone have any ideas?

LStarky
  • 2,740
  • 1
  • 17
  • 47
Michael E
  • 53
  • 1
  • 4

3 Answers3

1

You should select you database before execute your sql.

PHP Site

<?php
$servername = "localhost";
$username = "qtesting";
$password = "test";
$database = "qtesting";

$mysqli = mysqli_connect($servername, $username, $password) or die('Error connecting to MySQL server.');;
if($mysqli->connect_errno > 0){
    die('Unable to connect to database [' . $mysqli->connect_error . ']');
}
$mysqli->select_db($database);

//write you insert, update, delete or select
0

Selecting the database on connection

Adjust your mysqli_connect string to specify the database selection, adding the fourth parameter:

$mysqli = mysqli_connect($servername, $username, $password, $database) or die('Error connecting to MySQL server.');

http://php.net/manual/en/function.mysqli-connect.php

Note on MySQL user credentials

You said "...selecting the database that user credentials will be stored in." I assume you're talking about your own table with users and passwords, right? The MySQL connection username and password (qtesting and test) is for your script to connect, and is stored internally in a system table in MySQL.

LStarky
  • 2,740
  • 1
  • 17
  • 47
0

Actually you have made the connection but didn't select the database. Paste the following line of code just after the if statement

mysqli_select_db($mysqli,$database);