I find the error: could not find driver in the next script. I'm breaking my head over it now for some time now maybe you see the my fault.
This is my code:
class ConnectStation {
private $host = "localhost";
private $DatabaseType = "mysql";
private $database = array (
1 => "Database_one",
2 => "Database_two",
3 => "Database_true"
);
private $user1 = "MyUsername1";
private $pass1 = "MyPassword1";
private $user2 = "MyUsername2";
private $pass2 = "MyPassword2";
public function ConnectDB($user, $database){
if ($database==""){$database=1;}
try{
switch ($user){
case "ReadOnly":
$connection = new PDO("'".$this->DatabaseType.":host=".$this->host.";dbname=".$this->database[$database]."', '".$this->user1."', '".$this->pass1."'");
$connection->exec('SET CHARACTER SET utf8');
return $connection;
break;
case "Admin":
$connection = new PDO("'".$this->DatabaseType.":host=".$this->host.";dbname=".$this->database[$database]."', '".$this->user2."', '".$this->pass2."'");
$connection->exec('SET CHARACTER SET utf8');
return $connection;
break;
}
}
catch(PDOException $e){
echo $e->getMessage();
}
}
}
Oke so far the connection than the scrip i use for a query to send to the database. the code is like this:
$userCard = new ConnectStation;
$query = "SELECT username FROM users";
foreach ($this->ConnectDB('ReadOnly', 1)->query($query) as $row){
echo $row['username']."<br>";
}
Any help ore advise is welcome?
Your call to the PDO constructor is totally screwed up with unnecessary quotes and weird argument order. Just do:
$dsn = sprintf('%s:host=%s;dbname=%s', $this->DatabaseType, $this->host, $this->database[$database]);
$connection = new PDO($dsn, $this->user1, $this->pass1);
Related
I wrote a class for PDO and need to disconnect PDO => ( I don't know how to do it )
I don't know code wrote is structurally correct?!
use $this->returnconn(); for db connection
Please guide me...
Sample code:
class conn {
public $inner;
public function returnconn() {
$CONF = $TMPL = array();
// The MySQL credentials
$CONF['host'] = 'localhost';
$CONF['user'] = 'root';
$CONF['pass'] = '';
$CONF['name'] = 'cmss';
$dsn ="mysql:host=".$CONF['host'].";dbname=".$CONF['name']."";
try{
$conn = new PDO($dsn,$CONF['user'],$CONF['pass']);
$conn ->exec("SET CHARACTER SET UTF8");
}catch(PDOException $e){
die($e->getMessage());
}
return $conn;
}
public function select(){
switch ($this->inner->switch){
case "select":
$sql="SELECT ".$this->inner->todo." FROM ".$this->inner->table." WHERE ".$this->inner->sql."";
$result=$this->returnconn()->prepare($sql);
/*
* this->returnconn();
*/
$result->execute();
if($result->rowCount()<=0){
return '{"msg":"empty "}';
}else{
return $result->fetch(PDO::FETCH_ASSOC);
}
break;
}
}
}
/* receive data */
$obj = new conn;
$iner = array();
$iner['table'] = 'category';
$iner['switch'] ='select';
$iner['todo'] = '*';
$iner['sql'] = '`id` IS NOT NULL ORDER BY `id` ASC';
$in = json_decode(json_encode($iner));
$obj ->inner = $in;
echo json_encode($obj ->select());
Do need a function to disconnect?
I started to learn PHP, have made a great way for myself (not for PHP world) but I cannot succeed updating the information part.. I have problem about updating multiptle tables, and keep receiving this nice error: Could not update data: Query was empty.
I've searched a lot, have been fighting with that for a week and tried to do my best but no result. That's why I am posting here. By the way I know that my code is not neither whole PDO nor MYSQLI but I'm trying my best to learn and implement them as well..
I have got 3 tables now: Students - LessonsBought - Payments.
1) students_id is a joined one with students_id in other tables.
2) students_id is a foreign Key with lessonsbought_id and payments_id
(InnoDB)
Here is my code :
<?php
$servername = "localhost";
$username = "MY-DB-USERNAME";
$password = "MY-DB-PASSWORD";
$dbname = "MY-DB-NAME";
$conn = mysql_connect($servername, $username, $password, $dbname);
if(isset($_POST['update']))
{
$students_name = $row['students_name'];
$students_phone = $row['students_phone'];
$students_email = $row['students_email'];
$students_grade = $row['students_grade'];
$students_reg_date = $row['students_reg_date'];
$lessonsbought_type = $row['lessonsbought_type'];
$lessonsbought_hour = $row['lessonsbought_hour'];
$payment_total = $row['payment_total'];
$payment_method = $row['payment_method'];
$payment_done = $row['payment_done'];
$payment_waiting = $row['payment_waiting'];
$students_id = $_GET["id"];
$sql = mysql_query("UPDATE students,lessonsbought,payment SET
students_name = '$students_name', students_phone = '$students_phone',
students_email = '$students_email', students_grade = '$students_grade',
students_reg_date = '$students_reg_date',
lessonsbought_type= '$lessonsbought_type',
lessonsbought_hour='$lessonsbought_hour',payment_total='$payment_total',
payment_method = '$payment_method', payment_done='$payment_done',
payment_waiting = '$payment_waiting', WHERE students_id =
'$students_id'");
$retval = mysql_query( $sql, $conn );
if(!$retval )
{
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n <font color='green'>
<b>Record deleted successfully</b><font><br />
<a class='buttons' href='/result.php'>Turn Back To Result Page</a>";
}
?>
first you have to select database
mysql_select_db("database_name");
secondly use separate update query to update different table
thirdly you are calling mysql_query inside another mysql_query.
your sql variable will be just query. like shown below
$sql="UPDATE students SET students_name = '$students_name', students_phone = '$students_phone' WHERE students_id = '$students_id'";
lastly Please stop using mysql_* functions.
I have taken some of your code and added it into PDO so you can see how you should be doing this. In this instance it'll work also once all fields have been entered;
Firstly, set yourself up a database connection file:
class Database
{
private $host = "localhost";
private $db_name = "dbname";
private $username = "user";
private $password = "pass";
public $conn;
public function dbConnection()
{
$this->conn = null;
try
{
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $exception)
{
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
}
Then, I'd make a DBCommon file also. You need to ensure you require_once the database connect file:
class DBCommon
{
private $conn;
/** #var Common */
public $common;
public function __construct()
{
$database = new Database();
$db = $database->dbConnection();
$this->conn = $db;
}
public function runQuery($sql)
{
$stmt = $this->conn->prepare($sql);
return $stmt;
}
}
Then you need to make your classes, so for this one it'd be for example, class student;
class student extends DBCommon
{
public function __construct()
{
parent::__construct();
}
public function updateStudent($name, $phone, $email, $grade)
{
$userid = $_SESSION['user_session'];
$stmt = $this->runQuery("UPDATE `tablename` SET `students_name` = :sname, `students_phone` = :phone, `students_email` = :email, `students_grade` = :grade WHERE `students_id` = :sid");
$stmt->bindParam(array(':sname' => $name, ':phone' => $phone, ':email' => $email, ':grade' => $grade, ':sid' => $userid));
$stmt->execute();
echo "Your Records have now been updated.";
}
}
You can add a try / catch block around these to pass back an error message.
Then within your form file you'd need to include the classes file and then create the class and then form your trigger for the code to run when you press the submit button like below:
require_once ('class.file.php');
$class = new student();
if (isset($_POST['update']))
{
$class->updateStudent($_POST['name'], $_POST['phone'], $_POST['email'], $_POST['grade']);
}
I know this doesn't precisely tell you what you've done wrong but the major wrong thing you have done is gone via MySQL_. This way is a much cleaner and effective way.
P.S. Always bind your params never use '{$var}' within your queries as you'll be subject to vulnerabilities.
I have 3 files: dbconnect (here's declaration of $pdo), core.php (file with class to manage) and test.php.
I want to receive data from DB, but I have error:
Notice: Undefined variable: pdo in C:\xampp\htdocs\project\core.php on line 24
In dbconnect $pdo is in try catch, but before this I put: $pdo=null(to make variable accessible) but it doesn't work.
dbconnect ---> core.php(error here) ---> test.php;
//dbconnect.php
<?php
$mysql_host = 'localhost';
$username = 'root';
$password = '';
$database = 'db';
$pdo = null;
try {
$pdo = new PDO('mysql:host='.$mysql_host.';dbname='.$database.';charset=utf8', $username, $password );
}
catch(PDOException $e) {
echo 'Połączenie nie mogło zostać utworzone.<br />';
}
?>
//core.php
require_once('cms/dbconnect.php');
class getCore{
public $link_allegro;
public $link_facebook;
function getLinks(){
$query= $pdo->query('SELECT `url` FROM `links` WHERE `title` = "facebook"');
$row = $query->fetch();
$this->link_facebook = $row["url"];
$query= $pdo->query('SELECT url FROM links WHERE title = "allegro"');
$row = $query->fetch();
$this->link_allegro = $row["url"];
$query->closeCursor();
}
}
//test.php
<?php
require_once('core.php');
$tmp = new getCore;
$tmp->getLinks();
echo $tmp->link_allegro;
echo $tmp->link_facebook;
?>
Anyone can solve this? Thanks.
This is a scoping problem. $pdo doesn't exists in your getCore class.
You can make a DatabaseConnect class to manage your db access.
You can use this basic class for your database connection :
<?php
class DatabaseConnect {
private $mysql_host = 'localhost';
private $username = 'root';
private $password = '';
private $database = 'db';
private $pdo = null;
public function getPdo(){
return $this->pdo;
}
public function __construct(){
try {
$this->pdo = new PDO('mysql:host='.$mysql_host.';dbname='.$database.';charset=utf8', $username, $password );
}
catch(PDOException $e) {
echo 'Połączenie nie mogło zostać utworzone.<br />';
}
}
}
?>
You can getting your PDO instance in an other class with calling DatabaseConnect object -> getPdo() :
- Instannciate a new DatabaseConnect.
- Get PDO instance with the methof of the class.
Like that :
$databaseConnect = new DatabaseConnect();
$pdo = $databaseConnect->getPdo();
You next code :
//core.php
require_once('cms/dbconnect.php');
class getCore{
public $link_allegro;
public $link_facebook;
function getLinks(){
$databaseConnect = new DatabaseConnect();
$pdo = $databaseConnect-getPdo();
$query= $pdo->query('SELECT `url` FROM `links` WHERE `title` = "facebook"');
$row = $query->fetch();
$this->link_facebook = $row["url"];
$query= $pdo->query('SELECT url FROM links WHERE title = "allegro"');
$row = $query->fetch();
$this->link_allegro = $row["url"];
$query->closeCursor();
}
}
//test.php
<?php
require_once('core.php');
$tmp = new getCore;
$tmp->getLinks();
echo $tmp->link_allegro;
echo $tmp->link_facebook;
You need to pass $pdo to the getLinks() function as an input to make it available for use. you could try getLinks($pdo)
I was recently introduced to the idea of classes in PHP, and after some research I've come to the conclusion that I need to store database related functions in a class to access later. It has worked for the most part, but some use cases I am still confused with. For example,
Below is an example of how I would normally connect to my database and display information from user id's in a table
dbcon.php:
<?php
$con = mysqli_connect("host","username","password","database") or die("Couldn't connect");
require_once("functions.php");
?>
functions.php
function getUserInfo($id) {
$query = mysqli_query($con, "SELECT * FROM users WHERE id = '$id'");
return mysqli_fetch_array($query);
}
Some random file:
require_once("dbcon.php");
$result = mysqli_query($con, "SELECT * FROM tablename");
while ($row = mysqli_fetch_assoc($result)) {
$userinfo = getUserInfo($row['userid']);
echo $userinfo['name'];
}
?>
I don't feel like this method of querying the database and displaying information is the neatest or most efficient way possible. I read this article about using classes to tamper with a database and call functions that I created in the class.
My first question is this: When I try to access $con in functions.php, it is undefined. How can I pass the variable from dbcon.php to functions.php over the require_once function?
I also would like to know what the best way to store my connection to the database is, and if there are any tutorials on how to set that up.
I hope you understood that lol.
You can do it like this way:-
Dbconnection.php:-
<?php
Class DbConnection{
function getdbconnect(){
$conn = mysqli_connect("host","username","password","database") or die("Couldn't connect");
return $conn;
}
}
?>
Function.php:-
<?php
require_once('Dbconnection.php');
Class WorkingExamples{
function getUserInfo($id) {
$Dbobj = new DbConnection();
$query = mysqli_query($Dbobj->getdbconnect(), "SELECT * FROM users WHERE id = '$id'");
return mysqli_fetch_array($query);
}
}
$data = new WorkingExamples();
echo "<pre/>";print_r($data->getUserInfo(3));
?>
Note:- this is an example, try it by changing values according to your requirement and get the result.
<?php
class DatabaseConnection
{
private $host = "127.0.0.1";
private $dbname = "online_english";
private $dbUsername = "root";
private $dbPass = "";
private $charset = 'utf8mb4';
private $dsn;
public function tryConnect(){
try{
$this->dsn = "mysql:host=$this->host;dbname=$this->dbname;charset=$this->charset";
$DBH = new PDO($this->dsn,$this->dbUsername,$this->dbPass);
$DBH->exec("set names utf8");
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $DBH;
}
catch (PDOException $e){
$e->getMessage();
}
}
}
?>
<?php
class Database{
const DB_HOSTNAME = 'localhost';
const DB_USERNAME = 'root';
const DB_PASSWORD = 'root';
const DB_NAME = 'stockganesha';
public $_db_connect;
protected $_sql;
protected $_result;
protected $_row;
function db_connect(){
$this->_db_connect = mysqli_connect(self::DB_HOSTNAME,self::DB_USERNAME,self::DB_PASSWORD,self::DB_NAME) or die(mysql_error());
return $this->_db_connect;
}
function sql(){
$this->_sql = 'SELECT * FROM customers';
}
function query(){
$this->_result = mysqli_query($this->_db_connect,$this->_sql);
}
function fetch_array(){
while($this->_row = mysqli_fetch_array($this->_result)){
$username = $this->_row['first_name'];
echo "<ul>";
echo "<li>".$username."</li>";
echo "</ul>";
}
}
function db_close(){
mysqli_close($this->_db_connect);
}
}
and Import this in another class
<?php
require_once('../Config/Dbconnection.php');
include './model.php';
class CustomerDTO{
private $mysql;
function __construct() {
$database = new Database();
$this->mysql = $database->db_connect();
}
function create($customer){
$firstName = $customer->getFirstName();
$lastName = $customer->getLastName();
$emailId = $customer->getEmailId();
$mobileNumber = $customer->getMobileNumber();
$dateOfBirth = $customer->getDateOfBirth();
$phoneNumber = $customer->getPhoneNumber();
$termAndCondtion = $customer->getTermAndCondition();
$result = mysqli_query($this->mysql, "Insert into customers (first_name,last_name,email_id,mobile_number,date_of_birth,phone_number,term_and_condition)
values('$firstName','$lastName','$emailId','$mobileNumber','$dateOfBirth','$phoneNumber','$termAndCondtion')");
return $result;
}
function read(){
$result = mysqli_query( $this->mysql, "Select * from customers");
return $result;
}
function update($id, $customer){
$result = mysqli_query($this->mysql, "update customers set
first_name = ".$customer->getFirstName()."
last_name = ".$customer->getLastName()."
email_id = ".$customer->getEmailId()."
mobile_number = ".$customer->getMobileNumber()."
date_of_birth = ".$customer->getDateOfBirth()."
phone_number = ".$customer->getPhoneNumber()."
term_and_condition = ".$customer->getTermAndCondition()."
where id = ".$customer->getId());
return $result;
}
public function delete($id){
$result = mysqli_query($this->mysql, "delete from customers where id =".$id);
return $result;
}
}
I'm trying to connect using a simle db class. For some reason it only print out
"Initiate DB class"
test.php
include 'db.class.php';
echo 'Initiate DB class';
$db = new DB();
echo 'DB class did load';
db.class.php
class DB extends mysqli {
private static $instance = null;
private function __construct () {
parent::init();
$host = 'localhost';
$user = 'root';
$pass = 'MY_PASS';
$dbse = 'MY_DB';
parent::real_connect($host, $user, $pass, $dbse);
if (0 !== $this->connect_errno):
die('MySQL Error: '. mysqli_connect_error());
//throw new Exception('MySQL Error: '. mysqli_connect_error());
endif;
}
public function fetch ($sql, $id = null, $one = false) {
$retval = array();
if ($res = $this->query($sql)):
$index = 0;
while ($rs = $res->fetch_assoc()):
if ($one):
$retval = $rs; break;
else:
$retval[$id ? $rs[$id] : $index++] = $rs;
endif;
endwhile;
$res->close();
endif;
return $retval;
}
}
I have tried to search my log files for error but they come out empty.
Ok got it,
In your call to db your calling new DB(); which mean you're trying to call the constructor of your DB class.
In your DB class it looks like you're trying to create a singleton, but something is missing normally there would be something to assign the instance the database connection, and something that asks the instance if it's empty create a new connection or if it's not use the same instance.
At the end of the day to make this work you can change your constructor to public.
Try this:
Db_class:
class Db_class{
/***********************CONNECT TO DB*********************/
public function db_connect(){
$user = '***';
$db = '***';
$password = '***';
$host = '***';
try {
$dbh = new PDO("mysql:host=$host;dbname=$db", $user, $password);
}
catch(PDOException $err) {
echo "Error: ".$err->getMessage()."<br/>";
die();
}
return $dbh;
}
/******************PREPARE AND EXECUTE SQL STATEMENTS*****/
public function query($statement){
$keyword = substr(strtoupper($statement), 0, strpos($statement, " "));
$dbh = $this->db_connect();
if($dbh){
try{
$sql = $dbh->prepare($statement);
$exe = $sql->execute();
}
catch(PDOException $err){
return $err->getMessage();
}
switch($keyword){
case "SELECT":
$result = array();
while($row = $sql->fetch(PDO::FETCH_ASSOC)){
$result[] = $row;
}
return $result;
break;
default:
return $exe;
break;
}
}
else{
return false;
}
}
Other PHP:
$db = new Db_class();
$sql = "SQL STATEMENT";
$result = $db->query($sql);
Your constructor is marked as private which means new DB will raise an error. I see you have a private property to store an instance, are you missing the singleton method to return a new object?