Using global for database conection not working - php

Ok. Hello guys
I have some problems with my database connection and using it in php.
My normal file structure:
db.php
$mysql_server = "server";
$mysql_user = "user";
$mysql_password = "password";
$mysql_db = "name";
$db = new mysqli($mysql_server, $mysql_user, $mysql_password, $mysql_db);
if ($db->connect_errno) {
exit();
}
$db->set_charset("utf8");
functions.php file
require_once("db.php");
function func_name() {
global $db;
//doing my work here with $db;
}
I'm 100% sure the credentials i user are ok so this is not the problem.
Can you give me some advice regarding this? I used this structure for every project and now i'm losing my mind trying to figure it out. I bet is something that i missed!
please, help! Thank you!

try using below code !!!
<?php
$mysql_server = "localhost";
$mysql_user = "root";
$mysql_password = "";
$mysql_db = "dbName";
$db = new mysqli($mysql_server, $mysql_user, $mysql_password, $mysql_db);
if ($db->connect_errno)
{
exit();
}
$db->set_charset("utf8");
function func_name() {
global $db;
$sql = "SELECT text FROM tableName";
$result = $db->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo $row["columnName"];
}
} else {
echo "0 results";
}
}
func_name();
mysqli_close($db);
?>

Related

Issue connecting to MySQL with PHP

I am trying to connect to MySQL with PHP but i keep getting the following error: "mysqli::__construct(): (HY000/2002): No such file or directory in /Users/markjonathas/Documents/bar/database_connection.php on line 9" I have MAMP downloaded and I am using PHP 7.3.1 and MySQL version 8.0.16.
I have tried to to download Sequel Pro but when I try to connect to the database I get the following error: "MySQL said: Authentication plugin 'caching_sha2_password' cannot be loaded: dlopen(/usr/local/lib/plugin/caching_sha2_password.so, 2): image not found"
//code for database_connection.php:
<?php
$servername = "127.0.0.1:3306";
$username = "root";
$password = "-------";
$database = "barDB";
function db_connect() {
$connection = new mysqli($servername, $username, $password,
$database);
return $connection;
}
function db_disconenct() {
if(isset($connection)) {
$connection->close();
}
}
?>
//code for connecting to database_connection.php:
<?php
require_once("database_connection.php");
$db = db_connect();
?>
Create a file and name it as init.php or whatever you want.
<?php
$db_name = "barDB";
$mysql_user = "root";
$mysql_pass = "-------";
$server_name = "127.0.0.1:3306";
$con = mysqli_connect($server_name, $mysql_user, $mysql_pass, $db_name);
if(!$con){
echo "Server Error";
}else{
}
?>
To access global variables, you have to declare them as global:
function db_connect() {
global $connection, $servername, $username, $password, $database; // <<<<<<<<
$connection = new mysqli($servername, $username, $password, $database);
return $connection;
}
function db_disconenct() {
global $connection; // <<<<<
if(isset($connection)) {
$connection->close();
}
}
Read PHP documentation for details.

Why does my script not return a record from mySQL?

I am building a login portal with mySQL and PHP
I have this file (dbc.php):
<?php
class db_connect {
protected $DB_SERVER = "localhost";
protected $DB_USERNAME = "root";
protected $DB_PASSWORD = "";
protected $DB_DATABASE = "mydb";
public function connect() {
$conn = new mysqli($this->DB_SERVER, $this->DB_USERNAME, $this->DB_PASSWORD, $this->DB_DATABASE);
if(mysqli_connect_errno()) {
die("Connection failed: ". mysqli_connect_errno());
}
return $conn;
}
}
?>
Then my actual PHP script (login.php) takes a POST from the login page:
<?php
//include database connection
include("dbc.php");
session_start();
//put post values into variables
$username = $_POST['username'];
$password = $_POST['password'];
//create db connector object
$db = new db_connect();
$conn = $db->connect();
//select correct db
mysqli_select_db($conn,”mydb”);
$username = mysqli_real_escape_string($conn,$username);
$query = "SELECT password FROM mydb.users WHERE username = '$username'";
$result = mysqli_query($conn,$query);
if(mysqli_num_rows($result) == 0)
{
header('Location: sorry.html');
}
$pwhash = $result;
if (password_verify($password, $pwhash)) {
header('Location: welcome.php');
} else {
header('Location: sorry.html');
}
?>
This never returns a value which is odd.
Any help appreciated!
$result holds a MySQLi response resource, not a string or array.
You need to change this line:
$pwhash = $result;
To this:
$pwhash = mysqli_fetch_assoc($result)['password'];

PDO SUM MYSQL table

I am learning as i go and been picking up snippets of code as i go and been working on this for the past few days and now i have thrown the towel in to seek help.
I am trying to calculate the sum of 2 columns in my database using PDO.
here is my code
<?php
$host = "localhost";
$db_name = "dbname";
$username = "root";
$password = "root";
try {
$con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
}
// show error
catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}
$query = "SELECT SUM (fill_up) AS TotalFill,
SUM (mileage_covered) AS Totalmiles
FROM fuel_cost";
$row = $query->fetch(PDO::FETCH_ASSOC);
$total_fill = $row['TotalFill'];
$total_miles = $row['Totalmiles'];
$myanswer = $total_fill/$total_miles;
//display the answer
echo $myanswer
?>
I have also checked my database table and both columns are varchar(32)
the error I am getting is Call to a member function fetch() on a non-object
I have searched into this but not sure what's the issue with the above code
Thank You in advance
Try this code :-
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT SUM (fill_up) AS TotalFill,
SUM (mileage_covered) AS Totalmiles
FROM fuel_cost";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
$total_fill = $row['TotalFill'];
$total_miles = $row['Totalmiles'];
$myanswer = $total_fill / $total_miles;
//display the answer
echo $myanswer;
die;
}
} else {
echo "0 results";
}
$conn->close();
?>

new mysqli_connect cat find database

<?php
$host = "localhost";
$username = "root";
$password = "";
$db = "mineforums";
$connect = mysqli_connect($host, $username, $password, $db) or die(mysqli_error($connect));
?>
That is my php code to connect to my database. Whenever I try to just connect though it doesnt do anything. The way I have my login-form setup is the action will be to this code and then doesnt do anything and when I return to my index it says database not selected because if you're logged in it says 'Welcome, {username}'
you could split the process
<?PHP
$host = "localhost";
$username = "root";
$password = "";
$db = "mineforums";
$connect = mysql_connect($host, $username, $password)OR DIE("Could Not Connect To Server". MySQL_Error());
if($connect) {
mysql_select_db($db)OR DIE("Could Not Select Databse". MySQL_Error();
}
?>

ADODB mySQLi Connection

I am using mysql with adodb and what changes i have to do if i want to shift to mysqli.
this is my connection file and i need to make changes in this file only or i have to update all my query files.
include_once("adodblib/adodb.inc.php");
class ADb {
function ADb()
{
global $dbserver;
global $dbuser;
global $dbpass;
global $database;
$dbuser = "root";
$dbpass = "asdasdasd";
$dbserver = "localhost";
$database = "DB_NAME";
$this->conn1 = &ADONewConnection('mysql');
$this->conn1->PConnect($dbserver, $dbuser, $dbpass, $database);
}
function query($sql){
$Result = $this->conn1->Execute($sql);
return $Result;
}
function ExecuteQuery($sql){
$Result = $this->conn1->Execute($sql);
return $Result;
}
function ExecuteQuery1($sql){
return $this->query($sql);
}
function Execute($sql){
return $this->query($sql);
}
}
You just need to change the parameter of ADONewConnection to mysqli.
Change the line
$this->conn1 = &ADONewConnection('mysql');
to
$this->conn1 = &ADONewConnection('mysqli');

Categories