Database Connectivity in PHP - unexpected error - php

Following is my piece of code in which I am trying to create database connectivity. Please see the comments below in the code in which I mentioned where exactly the problem is occurring. Moreover, I also mentioned one connectivity code that is working fine.
Please let me know how I can call my dbconfig.php so it'll behave like that piece of code that results to successful connection.
Thanks
<?php
//Including Header file for the connectivity to the database
require_once('Connections/dbconfig.php');
mysql_select_db($database_dbconfig, $dbconfig);
// If I use the following line of code for connectivity then it works perfectly fine:
//$dbh = new PDO('mysql:host=localhost;dbname=rare','root','');
$dbh= $dbconfig;
$q = 'select resident_id,u_first,u_last from z_events group by resident_id';
/*
The following error will occur when I try to make a connection from the header file:
Fatal error: Call to a member function prepare() on a non-object in C:\Users\QAD\Downloads\CAR\index12 - Copy.php on line 200
*/
$user = $dbh->prepare($q);
$user->execute();
?>
dbconfig.php
<?php
# FileName="Connection_php_mysql.htm"
# Type="MYSQL"
# HTTP="true"
$hostname_dbconfig = "localhost";
$database_dbconfig = "rare";
$username_dbconfig = "root";
$password_dbconfig = "";
$dbconfig = mysql_pconnect($hostname_dbconfig, $username_dbconfig, $password_dbconfig) or trigger_error(mysql_error(),E_USER_ERROR);
?>

You are mixing mysql_* functions with PDO functions - first connecting to your database using mysql_connect and then using prepare() to query your database.
You should move to PDO completely, replace this line:
$dbconfig = mysql_pconnect($hostname_dbconfig, $username_dbconfig, $password_dbconfig) or trigger_error(mysql_error(),E_USER_ERROR);
With this one:
$dbconfig = new PDO('mysql:dbname=' . $database_dbconfig . ';host=127.0.0.1', $username_dbconfig, $password_dbconfig);
And put this in your other file:
<?php
//Including Header file for the conectivity to the database
require_once('Connections/dbconfig.php');
$dbh = $dbconfig;
$q = 'select resident_id,u_first,u_last from z_events group by resident_id';
$user = $dbh->prepare($q);
$user->execute();
?>

Try This
$connection = mysql_connect("localhost","root","") or die(mysql_error());
$db = mysql_select_db("database_name") or die(mysql_error());

change your database selection into this
mysql_select_db($database_dbconfig);

Related

I can't update my MySQLi Database with PHP (no Errors)

I can't Update my Database with PHP. I don't get any errors but it doesn't change anything!
Here is my file:
<?php
include_once 'dbh.inc.php';
?>
<?php
$id = $_GET['verId'];
$name = $_GET['verName'];
echo $id;
echo $name;
$sql = "UPDATE allusers SET ver = '1' WHERE idUsers = '$id';";
?>
The variables are defined and work.
Here's the dbh.inc.php file:
<?php
$servername = "localhost";
$dBUsername = "root";
$dBPassword = "";
$dBName = "loginsystem";
$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBName);
if (!$conn) {
die("Connection failed: ".msqli_connect_error());
}
?>
Other files that use dbh.inc.php work fine.
Thanks for your help.
You need to execute your SQL, but the way you are using MySQLi is very wrong. Let me show you how to get started with a simple query.
First in your dbh.inc.php (you should name it properly too) you should have the following code:
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new \mysqli("localhost", "root", "", "loginsystem");
$conn->set_charset('utf8mb4');
Do not use root for connection. Create a valid MySQL user with a proper password.
Then in your main PHP file, you can use it as follows:
<?php
include_once 'dbh.inc.php';
$id = $_GET['verId'];
$name = $_GET['verName'];
echo $id;
echo $name;
// prepare -> bind data -> execute
$stmt = $conn->prepare("UPDATE allusers SET ver='1' WHERE idUsers=?");
$stmt->bind_param('s', $id);
$stmt->execute();
I used here what is called a prepared statement. You can learn more about MySQLi here: https://phpdelusions.net/mysqli_examples/update

Trying to access using a function my $connection variable to a database located in a different directory

As the title says, I have a database connection file in a different directory and im trying to access that inside a function, it works if its not inside a function as I have been using through out my web development, but now that I need to access inside a function it does not work.
function getSubCat($mainCat){
include"../sql/sqln.php";
$sql = "SELECT SUB_CAT FROM CATEGORIES WHERE CAT = '$mainCat' GROUP BY SUB_CAT";
$getQuery = $connection->query($sql);
}
PHP storms points out this error. unidentified variable 'connection'
Database connection
<?php
session_start();
$username = "xxx";
$password = "xxxx";
$database = "xxx";
$localhost = "xxxx";
$connection = mysqli_connect($localhost, $username, $password, $database);
?>
UPDATE:
I tested it and the function is actually working, but PHP storms still give me an warning/error (unidentified variable 'connection'). not sure if I should just ignore it since its actually working.
Send the $connection variable as a parameter:
function getSubCat($mainCat,$connection){
include"../sql/sqln.php";
$sql = "SELECT SUB_CAT FROM CATEGORIES WHERE CAT = '$mainCat' GROUP BY SUB_CAT";
$getQuery = $connection->query($sql);
}
and when you call the function do it this way:
getSubCat($mainCat,$connection)

MySQL error message, mysql_connect(), any way to fix it?

So this is the error message:
PHP Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead
This is the affected piece of code:
class wdClient {
var $dbLink; // The database link
var $prefix; // Table prefix
var $script; // The script running
/**
* Construct a new directory object.
*/
function wdClient() {
error_reporting(E_ALL ^ E_NOTICE);
$this->prefix = WDDBPREFIX;
// Connect to the database
$this->dbLink = mysql_connect(WDDBHOST, WDDBUSER, WDDBPASSWD);
// Select the database
mysql_select_db(WDDBNAME, $this->dbLink) or die('Sorry, The site is currently unavailable!');
}
where WDDBPREFIX, WDDBHOST, WDDBUSER, WDDBPASSWD, WDDBNAME are already defined in a config file.
I have tried simply using mysqli_connect instead of mysql_connect but it's not working.
Note: Never use MySQL, use this method!
//MySQLi information
$db_host = "localhost";
$db_username = "username";
$db_password = "password";
//connect to mysqli database (Host/Username/Password)
$connection = mysqli_connect($db_host, $db_username, $db_password) or die("Error " . mysqli_error());
//select MySQLi dabatase table
$db = mysqli_select_db($connection, "table") or die("Error " . mysqli_error());
Good luck!
well, as pointed in here http://php.net/manual/en/function.mysqli-connect.php , you should make something like this:
$link = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");
Apparently, in your case it will look like this:
$link = mysqli_connect(WDDBHOST, WDDBUSER, WDDBPASSWD, WDDBNAME);
And then you can continue with your code...
if (!link){
die('Sorry, The site is currently unavailable!');
} else{
// write your SQL here and fetch it
}

Fatal Error Call To a member Function query()

I've seen some of the previous posts on here but they really don't explain what it is I'm looking for. maybe someone can point me in the right direction.
All I'm doing is a simple select statement that works on some other pages but not this one.
at the top of my page, I have the connection to my db: include 'myDBconnection.php'; just like any other page that uses it.
I'm using these to tell me what errors I have:
ini_set('display_errors', 'On');
error_reporting(E_ALL);
and they are returning this:
"Fatal error: Call to a member function query() on a non-object in /var/www/vhosts/mydomainname.com/httpdocs/somedirectory/index.php on line 16"
So, this is my simple select statement that I'm trying to just display on the page:
<?php
//just a simple select statement
if($row = $con->query("SELECT * FROM ErrorCodeTable WHERE ErrorCodeID = 100"))//this is line 16 in my code
{
$eCodeId = $row['ErrorCodeID'];
$eCode = $row['ErrorCode'];
echo $eCodeId." = ".$eCode;
}
?>
So, I'm stumped. Why is it telling me that?
Just for clarity's sake, this is my DB connection and I'm reading from an INI file.
function getConnected()
{
$file = "../myConnection.ini";
if (!$settings = parse_ini_file($file, TRUE)) throw new exception('Unable to open ' . $file . '.');
$host = $settings['connection']['default_host'];
$user = $settings['connection']['default_user'];
$paass = $settings['connection']['default_pw'];
$dbName = $settings['connection']['default_db'];
$con = 'mysqli_connect("'.$host.'", "'.$user.'", "'.$paass.'", "'.$dbName.'")';
return $con;
}
//MYSQLI CONNECTION
$con = getConnected();
//CONNECTION CHECK
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
So, why do I get the "Fatal Error" message? Did I overlook or forget something in my query?
Be gentle. :-)
Remove the single quotes around the below statement
$con = 'mysqli_connect("'.$host.'", "'.$user.'", "'.$paass.'", "'.$dbName.'")';
^ ^
By enclosing it in single quotes , your $con behaves like a string instead of a connection resource. The mysqli_connect function will never be executed.
Simply rewrite it like..
$con = mysqli_connect($host,$user,$paass,$dbName);

PHP database selection issue

I'm in a bit of a pickle with freshening up my PHP a bit, it's been about 3 years since I last coded in PHP. Any insights are welcomed! I'll give you as much information as I possibly can to resolve this error so here goes!
Files
config.php
database.php
news.php
BLnews.php
index.php
Includes
config.php -> news.php
database.php -> news.php
news.php -> BLnews.php
BLnews.php -> index.php
Now the problem with my current code is that the database connection is being made but my database refuses to be selected. The query I have should work but due to my database not getting selected it's kind of annoying to get any data exchange going!
config.php
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "test";
?>
database.php
<?php
class Database {
//-------------------------------------------
// Connects to the database
//-------------------------------------------
function connect() {
if (isset($dbhost) && isset($dbuser) && isset($dbpass) && isset($dbname)) {
$con = mysql_connect($dbhost, $dbuser, $dbpass) or die("Could not connect: " . mysql_error());
$selected_db = mysql_select_db($dbname, $con) or die("Could not select test DB");
}
}// end function connect
} // end class Database
?>
News.php
<?php
// include the config file and database class
include 'config.php';
include 'database.php';
...
?>
BLnews.php
<?php
// include the news class
include 'news.php';
// create an instance of the Database class and call it $db
$db = new Database;
$db -> connect();
class BLnews {
function getNews() {
$sql = "SELECT * FROM news";
if (isset($sql)) {
$result = mysql_query($sql) or die("Could not execute query. Reason: " .mysql_error());
}
return $result;
}
?>
index.php
<?php
...
include 'includes/BLnews.php';
$blNews = new BLnews();
$news = $blNews->getNews();
?>
...
<?php
while($row = mysql_fetch_array($news))
{
echo '<div class="post">';
echo '<h2> ' . $row["title"] .'</h2>';
echo '<p class="post-info">Posted by | <span class="date"> Posted on ' . $row["date"] . '</span></p>';
echo $row["content"];
echo '</div>';
}
?>
Well this is pretty much everything that should get the information going however due to the mysql_error in $result = mysql_query($sql) or die("Could not execute query. Reason: " .mysql_error()); I can see the error and it says:
Could not execute query. Reason: No database selected
I honestly have no idea why it would not work and I've been fiddling with it for quite some time now. Help is most welcomed and I thank you in advance!
Greets
Lemon
The values you use in your functions aren't set with a value. You likely need to convert the variables used to $this->dbName etc or otherwise assign values to the variables used.
Edit for users comment about variables defined in config.php:
You really should attempt to get the data appropriate for each class inside that class. Ultimately your variables are available to your entire app, there's no telling at this point if the variable was changed by a file including config.php but before database.php is called.
I would use a debugging tool and verify the values of the variables or just var_dump() them before the call.
Your Database class methods connect and selectDb try to read from variables that are not set ($dbhost, $dbname, $con, etc). You probably want to pass those values to a constructor and set them as class properties. Better yet, look into PDO (or an ORM) and forget creating your own db class.

Categories