I made my first function for connecting to mysql database. I have index.php and functions.php and i included functions.php to index.php!
This is my Connect to database function...
function connect_to_database()
{
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'root';
/*** mysql password ***/
$password = '';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=zadatak1", $username, $password);
/*** echo a message saying we have connected ***/
/**echo 'Connected to database';**/
}
catch(PDOException $e)
{
echo $e->getMessage();
}
return $dhb;
}
I don't know is it correct and if i am calling it right.
I type in index.php
<?php
require_once 'functions.php';
connect_to_database();
active_links();
include 'includes/head.php';
include 'includes/nav.php';
..................
See comments:
function connect_to_database()
{
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'root';
/*** mysql password ***/
$password = '';
$dbh = false; // initialized for error
try {
$dbh = new PDO("mysql:host=$hostname;dbname=zadatak1",
$username, $password);
/*** echo a message saying we have connected ***/
/**echo 'Connected to database';**/
}
catch(PDOException $e)
{
echo $e->getMessage();
// consider to exit / throw own exception / stop continuing script anyhow ....
}
// returns false on error
return $dbh; // typo here, was $dhb !!
}
Usage:
$DB = connect_to_database();
if ( $DB !== false )
$DB->function();
So it works fine now, here is the answer! Thank you for help
I created file named config.php
// PDO connect *********
function connect()
{
$host = 'localhost';
$db_name = 'database_name';
$db_user = 'root';
$db_password = '';
return new PDO('mysql:host='.$host.';dbname='.$db_name, $db_user, $db_password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
}
and just calling connect function like this, $pdo = connect(); or any name for var but that is the way!
<?php
include 'config.php';
$pdo = connect();
........
Related
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.
I've set up a database using MAMP.
When I try the following test, I only receive a blank page. Fairly new to this, and I've tried different suggestions found on the web with no luck.
Tried using both port and socket.
<?php
$user = 'root';
$password = 'root';
$db = 'test';
$host = 'localhost';
$port = 3306;
$socket = "/Applications/MAMP/tmp/mysql/mysql.sock";
$link = mysql_connect(
"$host:$socket",
$user,
$password
);
$db_selected = mysql_select_db(
$db,
$link
);
if (!$link){
echo "ERROR";
}
else {
echo "Success";
}
mysql_close($link);
?>
<?php
$servername = "localhost";
$username = "root";
$password = "root";
try {
$conn = new PDO("mysql:host=$servername;test", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
Would you like to try PDO ?!
<?php
$dsn = "mysql:host=localhost;dbname=databasenamehere";
$user = 'root';
$pass = '';
$option = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
try {
$connect = new PDO($dsn, $user, $pass,$option);
$connect->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $r) {
echo 'Failed' . $r->getMessage();
}
I've been trying for a while now to get my loginscript working and i can't seem to find the issue, either im just blind or there's something else going on here.
It doesn't matter if i input the correct credentials or not into the form, i still end up getting a lovely error 500.
Any ideas?
The DB connect funtion:
function db_connect() {
if i move this column-->
$server = 'localhost';
$uname = 'root';
$passw = 'password';
$datab = 'database';
/* check connection */
try{
$conn = new PDO("mysql:host=$server;dbname=$datab;", $uname, $passw);
} catch(PDOException $e) {
die( "Connection failed: " . $e->getMessage());
}
<---
return $conn; /added this as suggested, still returns NULL.
}
The login file:
include('../lib/functions.php'); //This is correct!
db_connect();
<-- HERE, it works -->
Earlier had an issue where my password hash during register was faulty, so password_verify($_POST['password'], $results['passw'])had no effect, always returning false even with correct input.
if(!empty($_POST['username']) && !empty($_POST['password'])):
$records = $conn->prepare('SELECT uname,passw FROM users WHERE uname = :user AND passw = :pass');
$records->bindparam(':user', $_POST['username']);
$records->bindparam(':pass', $_POST['password']);
$records->execute();
$results = $records->fetch(PDO::FETCH_ASSOC);
if(count($results) > 0 && password_verify($_POST['password'], $results['passw']) && $_POST['username'] == $results['uname']) //Also tried removing the &&-->username area incase two and statements were wrong without any luck {
die('It works!');
} else {
die('OR NOT!');
}
endif;
Your db_connect() function defines $conn in it's own scope. So, variable $conn is local. And after db_connect() ends executing $conn just disappears.
Outside this function $conn is simply NULL.
Return $conn to outer scope from your function:
function db_connect() {
$server = 'localhost';
$uname = 'root';
$passw = 'password';
$datab = 'database';
/* check connection */
try{
$conn = new PDO("mysql:host=$server;dbname=$datab;", $uname, $passw);
} catch(PDOException $e) {
die( "Connection failed: " . $e->getMessage());
}
return $conn; // here
}
And in your script:
include('../lib/functions.php'); //This is correct!
$conn = db_connect();
// other codes
ERROR CODE:
Notice: Undefined variable: blog_array in
/home/willconnor/public_html/index.php on line 69
* create the blog array */$blog_array = array();
<?php
if(sizeof($blog_array) > 0)
{
/*** loop over the blog array and display blogs ***/
foreach($blog_array as $blog)
{
echo '<div class="blog_entry">';
echo '<p><span class="category">'.$blog['blog_category_name'].': </span>
<span class="blog_date">Added by '.$blog['blog_user_name'].' on '.$blog['blog_content_date'].'</p>';
echo '<h2>'.$blog['blog_content_headline'].'</h2>';
echo '<p>'.$blog['blog_content_text'].'</p>';
echo '</div>';
}
}
else
{
echo 'No Blogs Here';
}
/*** include the footer file ***/
include 'includes/footer.php';
?>
ERROR CODE:
Warning: mysqli_select_db() expects parameter 1 to be mysqli, string given in /home/willconnor/public_html/includes/conn.php on line 16
<?php
/*** mysqli hostname ***/
$hostname = 'localhost';
/*** mysqli username ***/
$username = 'username';
/*** mysqli password ***/
$password = 'password';
/*** connect to the database ***/
$link = mysqli_connect($hostname, $username, $password);
/*** select the database ***/
$db = mysqli_select_db('blog', $link);
?>
try as follows
/*** mysqli hostname ***/
$hostname = 'localhost';
/*** mysqli username ***/
$username = 'username';
/*** mysqli password ***/
$password = 'password';
$con=mysqli_connect($hostname,$username,$password,"blog");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
and if you want to change the selected database "blog" then only you need to write following line
mysqli_select_db($con,"replace_selected_db");
Actually you could pass the name of the database as the fourth parameter in mysqli_connect() function, like this:
<?php
$hostname = 'localhost';
$username = 'username';
$password = 'password';
$dbname = 'blog';
$link = mysqli_connect($hostname, $username, $password, $dbname);
if (!$link) {
die("Connection failed: " . mysqli_connect_error();
}
?>
You connection should code like:
<?php
/*** mysqli hostname ***/
$hostname = 'localhost';
/*** mysqli username ***/
$username = 'username';
/*** mysqli password ***/
$password = 'password';
/*** database ***/
$my_db = 'blog';
/*** connect to the mysql and select database ***/
$link = mysqli_connect($hostname, $username, $password, $my_db);
/*** Check connection ***/
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
After this you can check for your $blog_array.
Hope this help!
You need to use connection parameter($link) as first parameter for mysqli_select_db() function. Just replace your code with below.
<?php
/*** mysqli hostname ***/
$hostname = 'localhost';
/*** mysqli username ***/
$username = 'username';
/*** mysqli password ***/
$password = 'password';
/*** connect to the database ***/
$link = mysqli_connect($hostname, $username, $password);
/*** select the database ***/
$db = mysqli_select_db($link, 'blog');
?>
The parts in bold are what I am questioning. Inside the search_for_new_user function, if I change $conn->prepare to $this->db_connection()->prepare. I receive a lost connection error. However in the function right above it db_conn_test I can use this syntax. In both cases I am returning the $connection so I don't understand why there must be a difference in syntax.
class Database {
function db_connection() {
$server = "localhost";
$user = "user";
$password = "password";
$database = "database";
return $connection = new mysqli($server, $user, $password, $database);
}
function db_conn_test() {
if (**$this->db_connection()->connect_errno**) {
die($this->db_connection()->connect_errno . ": " . $this->db_connection()->connect_error);
} else {
echo "connected to mysql database";
}
}
function search_for_new_user($email) {
**$conn = $this->db_connection();**
if ($stmt = **$conn->prepare**("SELECT email FROM users where email = ?")) {
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->bind_result($result);
$stmt->fetch();
echo $result;
$stmt->close();
$conn->close();
}
}
}
In db_conn_test you call db_connection twice only if you got connection error during first db_connection call, so in this case connection to DB is not created.
But in search_for_new_user you create connection twice.
I.e.:
in db_conn_test:
// if connection not created, because you got error
if ($this->db_connection()->connect_errno) {
// therefore each time you call db_connection(),
// you again try create connection, and got same error
// and return it in die text
die($this->db_connection()->connect_errno . ": " . $this->db_connection()->connect_error);
} else {
echo "connected to mysql database";
}
but in search_for_new_user: you call db_connection() and create connection(if all is ok). And then if you call db_connection in second try, first connection is gone away and you got error.
Your class should looks like this:
class Database {
protected $connection;
function db_connection() {
if ($this->connection !== null) {
return $this->connection;
}
$server = "localhost";
$user = "user";
$password = "password";
$database = "database";
return $this->connection = new mysqli($server, $user, $password, $database);
}
}