PHP OOP MySQL connection [closed] - php

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
In previous projects, I use the following code to connect to MySQL database:
File: connect.php
define('DB_SERVER','my_server');
define('DB_DATABASE','my_database');
define('DB_SERVER_USERNAME','my_user');
define('DB_SERVER_PASSWORD','my_password');
$db_server = DB_SERVER;
$db_username = DB_SERVER_USERNAME;
$db_password = DB_SERVER_PASSWORD;
$db_database = DB_DATABASE;
$connection = mysqli_connect($db_server, $db_username, $db_password,$db_database);
if ($connection) {
//Connected OK
} else {
die ("Cannot connect to database $db_database in $db_server!");
}
And all my other scripts looks like the next:
include "connect.php"
//From here, I can use the $connection variable to select/insert/delete/update data in my_database.
Now, I'm trying to use a more OOP approach in my programming, then I create the next code to connect to MySQL:
Class Connection extends mysqli{
public function __construct(){
if ($config = parse_ini_file('config/config.ini',true)){
$server = $config['database']['server'];
$username = $config['database']['username'];
$password = $config['database']['password'];
$database = $config['database']['dbname'];
parent::__construct($server,$username,$password,$database);
if (mysqli_connect_error()){
$message = "Conection error (" . mysqli_connect_errno() . ") " .
mysqli_connect_error();
throw new Exception($message);
}
} else {
$message = "Config file not found.";
throw new Exception($message);
}
}
}
And my scripts now looks like:
set_include_path(__DIR__.'/Classes');
spl_autoload_extensions(".php");
spl_autoload_register();
try {
$connection = new Connection();
} catch (Exception $ex){
die($ex->getMessage());
}
//Again, from here I can use the variable $connection to use my database
Both solutions works, but...
The questions are:
Is this necessary or am I overcomplicating these scripts?
Are there best practices in this concerns?
Thanks in advance for any comments to improve all of this.

config.php:
<?php
//Enter your database connection details here.
$host = 'localhost'; //HOST NAME.
$db_name = 'databasename'; //Database Name
$db_username = 'root'; //Database Username
$db_password = ''; //Database Password
try
{
$pdo = new PDO('mysql:host='. $host .';dbname='.$db_name, $db_username, $db_password);
}
catch (PDOException $e)
{
exit('Error Connecting To DataBase');
}
?>
database.class.php:
<?php
class database
{
function __construct($pdo)
{
$this->pdo = $pdo;
}
function getData()
{
$query = $this->pdo->prepare('SELECT * FROM database');
$query->execute();
return $query->fetchAll();
}
}
?>
index.php:
<?php
require_once 'config.php';
require_once 'database.class.php';
$db = new database($pdo);
$rows = $db->getData();
?>

Related

how can i resolve my problem with sql request in php [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I have a problem with my sql request in my php. I try to use the "query" but when I do a "fetch" I get an error. I know this error is because of my sql request but I can't find the problem.
my php code :
$host = 'localhost';
$dbName = 'appliderencontre';
$username = 'root';
$pswd = '';
try
{
$db = new PDO("mysql:host=" .$host .";dbName=" . $dbName, $username, $pswd);
//$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo $e;
}
$requete = "SELECT pseudo FROM user";
$reponse = $db-> query($requete);
while($donnee = $reponse->fetch()){
echo $donnee['pseudo'];
}
$reponse ->closeCursor();
And that is my error :
I need your help, i can't find anything for helping me.
Thanks a lot !
(Sorry for my english, i'm a begginer).
Change this code :
$db = new PDO("mysql:host=" .$host .";dbName=" . $dbName, $username, $pswd);
to
$db = new PDO("mysql:host=" .$host .";dbname=" . $dbName, $username, $pswd);
because dbname must be lower-case.
Try to run this code and use PDO::FETCH_OBJ in the fetch function.
$host = "localhost";
$user = "root";
$password = '';
$dbname = "appliderencontre";
try {
$dns = "mysql:host=".$host.";dbname=".$dbname.";charset=utf8";
$pdo = new PDO($dns, $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "PDOError: " . $e->getMessage()." In ".__FILE__;
}
$query = 'SELECT pseudo FROM user';
$query = $pdo->query($query);
while ($row = $query->fetch(PDO::FETCH_OBJ)) {
echo $row->pseudo;
echo '<br>';
}

i want get data from table sql [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
i have a table register with email and username colums.
> ex - username email
> test test#gmail.com
> new new#gmail.com
SELECT * FROM Register WHERE email='test#gmail.com'
I can get this colom ,but i cant select username.i want assign username to variable
I think you want something like this if you use MySQL :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT username, email FROM MyTable";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "username: " . $row["username"]. " - email: " . $row["email"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
In my opinion you're probably a beginner with web development with databases.
I recommend you w3chools. You can reed various examples in this site:
https://www.w3schools.com/php/php_mysql_select.asp
Your question is not clear, but if you are new with database I recommend you to start with PDO instead of mysqli.
<?php
//Db connection
function pdo_connect_mysql() {
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'root';
$DATABASE_PASS = '';
$DATABASE_NAME = 'phpcrud';
try {
return new PDO('mysql:host=' . $DATABASE_HOST . ';dbname=' . $DATABASE_NAME . ';charset=utf8', $DATABASE_USER, $DATABASE_PASS);
} catch (PDOException $exception) {
// If there is an error with the connection, stop the script and display the error.
exit('Failed to connect to database!');
}
}
// User Input
$username = 'john';
$email = 'john#gmail.com';
$sql = 'SELECT * FROM register WHERE username = ? email = ?';
$stmt = pdo_connect_mysql() ->prepare($sql);
$stmt->execute([$username, $email]);
$register = $stmt->fetchAll();
?>

Safe way to connect database with php using MySQLi [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I just cut down my long code to small so its easy to understand. I am building php based website. I am using MySQLi as i know some MySQL. And for me PDO is hard to learn in small time period.
I created three files
- db.con.php
- index.php
- logout.php
I will post my all three files and i just want to know if its safe or there is any Vulnerability
And i thanks to all who see my question and appreciate answer alot.
db.con.php
<?php
//db.con.php
class DB {
protected $db_name = 'demo';
protected $db_user = 'root';
protected $db_pass = '';
protected $db_host = 'localhost';
public function connect() {
$DBerror = 'Database Error';
$connection = ($GLOBALS["___mysqli_ston"] = mysqli_connect($this->db_host, $this->db_user, $this->db_pass)) or die($DBerror);
((bool)mysqli_query($GLOBALS["___mysqli_ston"], "USE $this->db_name")) or die($DBerror);
return true;
}
}
$db = new DB();
$db->connect();
//start session
session_start();
?>
index.php
<?php
require_once 'db.con.php';
$userID = $_GET['userID'];
$userID = mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $userID);
$CheckQuery = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM users WHERE id='$userID'");
$VerifyID = mysqli_num_rows($CheckQuery);
if ($VerifyID !== 1){
header("Location: logout.php");
}
while ($row = mysqli_fetch_assoc($CheckQuery)) {
$id = $row['id'];
$name = $row['name'];
}
echo "My id is $id and my name is $name";
?>
And last logout.php
<?php
//logout.php
session_start();
session_destroy();
echo "Logout successful";
?>
Make it PDO not mysqli
Leave DB class alone for a while
Learn prepared statements
db.con.php
<?php
$dsn = "mysql:host=localhost;dbname=demo;charset=utf8";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn, 'root', '', $opt);
session_start();
index.php
<?php
require_once 'db.con.php';
$stmt = $pdo->prepare("SELECT 1 FROM users WHERE id=?");
$stmt->execute(array($_GET['userID']));
$row = $stmt->fetch();
if(!$row) {
header("Location: logout.php");
exit;
}
$id = $row['id'];
$name = $row['name'];
echo "My id is $id and my name is $name";
Look it works better without homebrewed wrappers

Can't connect on database on my localhost [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 8 years ago.
Improve this question
I have php script:
<?php
$host = $_GET['host'];
$username = $_GET['username'];
$pass = $_GET['pass'];
$con = mysql_connect($host, $username, $pass);
if (!$con) {
echo 'Connection failed!';
} else {
echo 'Connected successfully!';
}
mysql_close($con);
?>
running on remote server and when I execute it and try to connect to database located on my PC i get an error:
Warning: mysql_connect() [function.mysql-connect]: Can't connect to MySQL server on '109.60.110.255' (4) in /home/a6859995/public_html/zavrsni/connect.php on line 12
How can I fix that?
I recommend to use pdo like this:
class_config.php:
class class_config {
public static $db_host = 'localhost';
public static $db_name = 'yourdbname';
public static $db_user = 'youruser';
public static $db_pass = 'yourpass';
}
class_pdo.php:
require_once "class_config.php";
class class_pdo {
public static function dbFactory() {
$host = class_config::$db_host;
if(strpos($host,":") !==false) {
$parts = explode(":",$host);
$hostname = "unix_socket=".$parts[1];
} else {
$hostname = "host=$host";
}
$user = class_config::$db_user;
$pass = class_config::$db_pass;
$dbase = class_config::$db_name;
$pdo = new PDO("mysql:$hostname;dbname=$dbase", $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
return $pdo;
}
}
use it in your script like this:
require_once("class_pdo.php");
$pdo = class_pdo::dbFactory();
$stmt = $pdo->prepare("SELECT * FROM `tablename` WHERE id = :id ");
$stmt->bindValue(":id", $id, PDO::PARAM_INT);
$stmt->execute();
[...]
Try This instead: mysql_connect() is deprecated so use mysqli_connect...
$host = $_GET['host'];
$username = $_GET['username'];
$pass = $_GET['pass'];
$databae = $_GET['database'];
$con = mysqli_connect($host, $username, $pass, $database);
if (mysqli_connect_errno()) {
echo 'Connection failed!';
} else {
echo 'Connected successfully!';
}
mysql_close($con);
?>
Though mysql_connect() is deprecated try using PDO.. I am just presenting it in mysql_connect for you..
$host = $_GET['host'];
$username = $_GET['username'];
$pass = $_GET['pass'];
$database = $_GET['database'];
$connect=new connect($host,$username,$pass,$database);
class connect{
function __construct($host,$user,$password,$db_name){
mysql_connect($host,$user,$password) or die("Connection error");
mysql_select_db($db_name);
$error=mysql_error();
if (!empty($error))
{
echo $error;
}
}
}
Thanks everyone on help. Main problem were privileges on MySQL database, but PDO usage helped me to understand how it's to be done these days, sorry on n00b code at start :D

MySQL connect on PHP

what is the best way to connect PHP application on MySQL.
So far I had the below connection classes.
class Connection{
private static $server = "127.0.0.1";
private static $catalog = "schemadb";
private static $username = "rootuser";
private static $password = "password";
public static $current = null;
public static function Open(){
self::$current = mysqli_init();
if(!self::$current){
die("Failed to initialize connection");
}
if(!self::$current->real_connect(self::$server,self::$username,self::$password,self::$catalog)){
die("Cannot connect to server");
}
return self::$current;
}
public static function Close(){
self::$current->close();
}
}
and also I have
abstract class abstractDAO
{
protected function getConnection()
{
$mysqli = new mysqli("127.0.0.1","rootuser","password","schemadb");
return $mysqli;
}
}
or if there's any other best approach to connect PHP application on MySQL. Please advise thanks..
You can try using the PDO object:
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
Have a look at PHP PDO documentation page
Try to use php frameworks like codeigniter, Yii, cake php. If you implement in any one of this framework no need to write php mysql query It will automatically generate.
You just need to enter your database configuration like give in below
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'sample';
You can connect through data using PDO, here is an example
<?php
$servername = "localhost";
$username = "root";
$password = "nopass";
try {
$conn = new PDO("mysql:host=$servername;dbname=wireframe", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
$stmt = $conn->prepare("SELECT * FROM todolist");
$stmt->execute();
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>
<table border="1" align="center">
<tr>
<th>name</th>
<th>type</th>
<th>status</th>
</tr>
<?php
foreach($stmt->fetchAll() as $k=>$v){
echo
"<tr>
<td>{$v['name']}</td>
<td>{$v['type']}</td>
<td>{$v['status']}</td>
</tr>\n";
}
?>
</table>
</body>
</html>
try this
<?php
$user = $_POST["username"];//if this doesnt work try the next line
$user = (isset($_POST["username"]) ? $_POST["username"] : "");
$host = "localhost";//mysql password
$username = "";//mysql username
$password = "";//mysql password
$db_name = "database";//database name
$tbl_name ="test";//table name
//make the connection
$con = mysql_connect("$host","username","password")or die("Could not connect.");
$conn = mysql_select_db("$db_name")or die("Could not select database.");
$sql = "SELECT * FROM $tbl_name WHERE username='$username'";
//query mysql
$result = mysql_query($sql);
if($result){
//if it works show this
}else{
//if it doesnt work show this
}
?>
ive tryed a lot of times to make a connection to a database and i finaly found one.

Categories