Php connecting but failing to select a database - php

I am having trouble getting php to connect to my mysql database on a shared hosting. This worked when it was on my MAMP local server.
I get the following error:
Error: No database selected Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in /hermes/bosnaweb03b/b2270/ipg.theburguersaredownco/cheval/main.php on line 34
My db_connect php file:
<?php
$connect = mysqli_connect('theburguersaredownco.ipagemysql.com', 'user', 'password');
if (!$connect) {
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully';
mysqli_select_db('db_cheval');
?>
I get the message: "Connected successfully", so I am assuming the connection to the database is established and therefore there are no issues with the mysql_connect function or any of its arguments (i.e. the user and password are correct etc...).
my main.php file:
<?php
include 'db_connect.php';
include 'header.php';
error_reporting( E_ALL );
ini_set( "display_errors", 1 );
?>
<a id="roundLogo" href="index.php" class="not-active"></a><div>
</div></a>
<div id="subheader" class="notVisible">
<nav id="menu2">
<ul>
<?php
$query = mysqli_query($connect,"SELECT * FROM categories");
if (!$query) {
printf("Error: %s\n", mysqli_error($connect));
// exit();
}
while ($q = mysqli_fetch_array($query)) {
if($q['id']<4){ ?>
etc...
Line 34 is this one:
while ($q = mysqli_fetch_array($query)) {
It is the first time I do this and I am new to php and mysql so I don't have much experience. Can someone help me find the problem here. How can I debug this?
Thank you

You should use localhost for host parameter even if you running on hosting or local webserver but your problem is missing parameter in mysqli_select_db that why "No database selected" return
$connect=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_select_db($connect,"db_cheval");

Related

Global Scope fails for included file

Can someone please help me with a scoping issue. I've been looking at this for so long and I just don't see why this isn't working:
connection.php
<?php
$hostname = "xxx.xxx.xxx.xxx";
$username = "xxxxxxxx";
$password = "xxxxxxxx";
$db_name = "xxxxxxxx";
function isSecure() {
return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
|| $_SERVER['SERVER_PORT'] == 443;
}
global $link;
$link = mysqli_connect($hostname, $username, $password, $db_name);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
?>
builder.php
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
$connection = $path . '/scripts/connection.php';
include_once ($connection);
session_start();
$club_id = $_SESSION['club_id'];
if (mysqli_connect_errno()) {
trigger_error("Failed to connect to MySQL: " . mysqli_connect_error());
exit();
}
$sql = "SELECT * FROM Workout_types
WHERE club_id=$club_id
ORDER BY type";
$result = mysqli_query($link, $sql) or trigger_error("Error description:" . mysqli_error($link) . "done");
?>
and I get the dreaded
mysqli_query() expects parameter 1 to be mysqli, null given in...
error.
Implementing the troubleshooting tips below, I changed a couple of lines.
builder.php:
require_once ("../scripts/connection.php");
connection.php:
if (!$link) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
It still doesn't work, but the errors are a bit different:
PHP Warning: mysqli_query(): Couldn't fetch mysqli in G:\PleskVhosts\example.com\httpdocs\workouts\builder.php on line 114
PHP Warning: mysqli_error(): Couldn't fetch mysqli in G:\PleskVhosts\example.com\httpdocs\workouts\builder.php on line 114
PHP Notice: Error description:done in G:\PleskVhosts\example.com\httpdocs\workouts\builder.php on line 114
where line 114 is the mysqli_query line.
I checked the GoDaddy docs, and that path is correct.
Just to prove that my include path was correct, I added this to connection.php:
global $test;
$test = "hello world";
Then in builder.php, I added a line echo $test;, and it printed hello world with no trouble whatsoever.
I should mention two other things could be helpful:
The code that I posted for builder.php is embedded in html code for a web page. It's the only php code in that file.
I originally wrote this code about 5 years ago, and it's been functioning flawlessly until I upgraded the php version on my server from 5.6.40 to 7.3.27. That's when it began to fail.

Making a PHP dropdown box pull data from an SQL database

so I've been trying to get this working for a few days now and I am completely lost. I've tried following a few of the answers on here but I can't seem to figure out what I need to change to adapt it to my database.
There have been complex and simple solutions I have seen, but what I am attempting at the minute is this:
...
<?php
echo "";
define('DB_USER', 'username');
define('DB_PASSWORD', 'password');
define('DB_HOST', 'localhost');
define('DB_NAME', 'username_test');
$dbc = #mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die('Could not connect to MySQL: ' . mysqli_connect_error() );
mysqli_set_charset($dbc, 'utf8');
?>
<?php
public function get_data()
{
$mysqli= new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME) or die("Couldn't connect".mysqli_connect_error());
$sql="SELECT Staff_Surname, Staff_Forename FROM users";
$result=$mysqli->query($sql) or die($mysqli->error);
while ($row=$result->fetch_array(MYSQLI_ASSOC))
{
echo "<option value=\"".$row["Staff_Surname"]."\" selected>".$row["Staff_Forename"]."</option>";
}
}
?>
<html>
<body>
<select name="abc" id="xyz">
<?php get_data(); ?>
</select>
</body>
</html>
...
which just results in a bunch of errors when I try to run it in a browser. I am using Microsoft Expression Web 4 and XAMPP.
This is a screenshot of the SQL database I just need to pull the forename and surname into a dropdown box:
SQL database
Any help you guys can offer would be really appreciated. Thank you.
Sorry, in the preview it looked like it showed what the error was. When I try to run the code in a browser I get this: enter image description here
Notice: Use of undefined constant DB_PASS - assumed 'DB_PASS' in index.php on line 17
Warning: mysqli::__construct(): (HY000/1045): Access denied for user 'username'#'localhost' (using password: YES) in index.php on line 17
Warning: mysqli::query(): Couldn't fetch mysqli in index.php on line 19
Warning: get_data(): Couldn't fetch mysqli in index.php on line 19
Change
$mysqli= new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME) or die("Couldn't connect".mysqli_connect_error());
to
$mysqli= new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME) or die("Couldn't connect".mysqli_connect_error());
Parse error: syntax error, unexpected 'public' (T_PUBLIC), expecting end of file in index.php on line 15
Change
public function get_data()
to
function get_data()
These changes should take care of all the errors you are receiving.
Code with #stealthyninja edits:
<?php
echo "";
define('DB_USER', 'username');
define('DB_PASSWORD', 'password');
define('DB_HOST', 'localhost');
define('DB_NAME', 'username_test');
$dbc = #mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die('Could not connect to MySQL: ' . mysqli_connect_error() );
mysqli_set_charset($dbc, 'utf8');
?>
<?php
function get_data()
{
$mysqli= new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die("Couldn't connect".mysqli_connect_error());
$sql= "SELECT Staff_Surname, Staff_Forename FROM users";
$result= $mysqli->query($sql) or die($mysqli->error);
while ($row=$result->fetch_array(MYSQLI_ASSOC))
{
echo "<option value=\"".$row["Staff_Surname"]."\"selected>".$row["Staff_Forename"]."</option>";
}
}
?>
<html>
<body>
<select name="abc" id="xyz">
<?php get_data(); ?>
</select>
</body>
</html>
EDIT:
Issues connecting to MySQL. First the usernames and passwords are
here: login info
The XAMPP control panel: XAMPP
The testcode that worked previously: Registration
And the error it now presents: Registration Error
I don't think I have changed anything from when it worked before. I built the Registration page following a tutorial in the book "PHP and MySQL for Dynamic Web Sites fifth edition" by Larry Ullman.

How do I start a PGSQL connection in PHP?

I am trying to start a pgsql connection in php but i get pg_last_error(): No PostgreSQL link opened yet Please forgive my amateur question as i am a bit new to php.
Here is my php code:
<?php
$connect = pg_connect("host=xxx.xx.xxx.21 dbname=d106 user=b16 password=bran") or die("Could not connect: " . pg_last_error());
$result = pg_query($connect,"SELECT distinct thestartgeom FROM bikes");
if (!$result)
{
echo "no results ";
}
while($row = pg_fetch_array($result))
{
$coor = $row['thestartgeom'];
echo $coor;
}
pg_close($connect);
?>
In your pgsql connection you have missed the port number.
Try this way.
<?php
$host = "host=xxx.xx.xxx.21";
$port = "port=5432";
$dbname = "dbname=d106";
$credentials = "user=b16 password=bran";
$connect= pg_connect( "$host $port $dbname $credentials" ) or die("Could not connect: " . pg_last_error());
$result = pg_query($connect,"SELECT distinct thestartgeom FROM bikes");
if (!$result)
{
echo "no results ";
}
while($row = pg_fetch_array($result))
{
$coor = $row['thestartgeom'];
echo $coor;
}
pg_close($connect);
?>
You can store PgSQL connection code in one PHP file to reuse
pgsql_db_connection.php file
<?php
$host = "host=xxx.xx.xxx.21";
$port = "port=5432";
$dbname = "dbname=d106";
$credentials = "user=b16 password=bran";
$connect= pg_connect( "$host $port $dbname $credentials" );
if(!$connect){
echo "Error : Unable to open database\n";
}
?>
Call pgsql_db_connection.php file in other php files to use your database connection.
<?php
require_once('pgsql_db_connection.php');
$result = pg_query($connect,"SELECT distinct thestartgeom FROM bikes");
if (!$result)
{
echo pg_last_error($connect);
exit;
}
while($row = pg_fetch_array($result))
{
$coor = $row[0];
echo $coor;
}
?>
When pg_connect fails, it returns FALSE and produces a PHP warning with the detailed information on why it couldn't initiate the connection. If you can see the other message:pg_last_error(): No PostgreSQL link opened yet that you're reporting, I'd expect you should be able to see the previous one too, which is the one normally telling the reason of the failure.
If the display_errors configuration setting is set to 0, the first message would not show up on the browser/screen but the second would not either.
Anyway, assuming you can't have access to pg_connect warnings for whatever reason such as custom error handler, what's wrong with your code is that pg_last_error() must have an already opened connection to work.
To access the detailed error message from a failed pg_connect, the built-in PHP function error_get_last() (returning an array) could be used.
<?
$connect= pg_connect("your-connect-string");
if (!$connect) {
print_r(error_get_last());
// for only the message:
// echo error_get_last()['message']
}
die("DB connection failed");
?>
See also how to catch pg_connect() function error? if you prefer exceptions.

mysql not connect with php scripts?

<?php
$cons=mysql_connect("localhost","root","");
mysql_select_db("infogallery") or die('Not Connected to the data base:'.mysql_error());
?>
I write above code for connection with mysql but when i run this scripts..nothing display on the brouser...what can i do for the connection with mysql....
If nothing is displayed, then it means it succeeded. Add more code which queries the database and displays some results.
Don't connect as the root account. Create an account specifically for playing around with.
Once you've done that, modify your code as follows:
$cons = mysql_connect('localhost', 'username', 'password');
if ($cons === FALSE) {
die("Failed to connect to MySQL: " . mysql_error());
}
mysql_select_db(etc.....);
You don't check if the connection failed, then try to do a database operation on that potentially failed connection. The or die(...) you have will only show the error caused by the select attempt, and the error message from the failed connection will be lost.
I like to just do
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("infogallery") or die(mysql_error());
echo "So far, so good.";
How about something like the following:
<?php
try {
$cons = mysql_connect("localhost","username","password");
} catch ($e) {
die('Failed to connect to the database: ' . mysql_error());
}
try {
mysql_select_db("infogallery", $cons);
} catch ($e) {
die('Failed to select the database: ' . mysql_error());
}
?>

Using PHP to connect to MySQL: ERROR?

I tried running the following code: (http://localhost/read.php)
<html>
<body>
<?php
$link = mysql_connect('localhost', 'root', 'password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
if (mysql_query("CREATE DATABASE testphp",$link))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
?>
</body>
</html>
and got the following error:
Fatal error: Call to undefined function mysql_connect() in
C:\Program Files (x86)\ApacheSoftware Foundation\Apache2.2\htdocs\read.php
on line 5
Look at you phpinfo(). Most likely mysql extensions is not there.
And while you are at it, you could just drop the ancient mysql_* way ow doing thing and learn how to use PDO and prepared statements. It's an abstraction API for database connection and interaction.
your mysql-extension for php is not loaded! check that in your php.ini.

Categories