I want to get a Firstname (Voornaam), and Lastname (Achternaam) from my database with a specific ID.
And I want to put it in my a function.
I made the following function in functions.php:
<?php
/* Naam opvragen */
include('gegevens.php');
function getName($getID)
{
$getname = 'SELECT * FROM KlantGegevens WHERE ID = ' . $getID;
$query = $conn->query($getname);
while($show = $query->fetch_assoc()) {
$voornaam = $show["Voornaam"];
return $voornaam;
}
}
/* Eind naam opvragen */
?>
And i call the function with ($getID (=1)):
<?php getName($getID); ?>
My error is:
Fatal error: Call to a member function query() on a non-object in /home/thijsgp51/domains/thijskempers.nl/public_html/beheer/functions/functions.php on line 8
What am i doing wrong here?
<?php
/* Naam opvragen */
function getName($getID)
{
$db = new PDO('mysql:host=localhost;port=3307;dbname=test', 'root', 'usbw');
$stmt = $db->prepare("SELECT * FROM klantgegevens WHERE ID ='$getID' ");
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$voornaam = $row["voornaam"];
return $voornaam;
}
}
$id = 1;
echo getName($id);
?>
I used PDO for the connection try it. Also read this post on sqlinjection very helpful.
In the code i changed your query a bit and put the connection in the function like Till Helge said.
Happy coding!
Try It.
<?php
/* Naam opvragen */
function getName($getID)
{
$db = new PDO('mysql:host=localhost;port=3307;dbname=test', 'root', 'usbw');
$stmt = $db->prepare("SELECT * FROM klantgegevens WHERE ID ='%s",$getID);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$voornaam = $row["voornaam"];
return $voornaam;
}
}
$id = 1;
echo getName($id);
?>
Your funcion get 2 arguments
function getName($voornaam, $achternaam)
you should remove the areguments as you are not using it.
function getName() {
....
}
Change your function definition, remove those 2 arguments, and change concatenation from + to .:
function getName()//or with optional arguments: function getName($voornaam='', $achternaam='')
{
$conn = new mysqli('localhost', 'user', 'pass', 'database');
$getID = 1;
$getname = 'SELECT Voornaam, Achternaam FROM KlantGegevens WHERE ID = ' . $getID;
$query = $conn->query($getname);
while($row = $query->fetch_assoc()) {
$voornaam = $row["Voornaam"];
$achternaam = $row["Achternaam"];
return $voornaam.' '.$achternaam;
}
}
You don't need name and forename in function definition parameters because you get it from database.
As Till Helge pointed out, you still need to open connection to database - either put it as an argument, or call as the first thing inside your function (I have already put that there after edition):
$conn = new mysqli('localhost', 'user', 'pass', 'database');
you didn't pass parameters in your function,
<?php getName(); ?>
Related
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;
}
}
unable to delete i row using PDO in php. Here is my code given below
this is inc.common.php
<?php
#session_start();
include_once '../common/inc.config.php';
include_once '../common/inc.globalConstants.php';
$db = new PDO("mysql:host=$mdbhost;dbname=$mdbname",$mdbuser,$mdbpass );
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
include_once '../classes/cls.common.php';
$Cobj=new common($db);
?>
this my cls.class.php
<?php
class common {
public function common($dbcon) {
$this->dbCon = $dbcon;
}
public function getCustomData($tableName,$fields, $conditions = "") {
$stmt = "";
$sql = "";
$sql = "SELECT $fields FROM $tableName $conditions ";
$stmt = $this->dbCon->query($sql);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
public function delet($tableName, $class_id){
$inputArray['classId']=$class_id;
$count = $this->$dbCon->prepare("DELETE FROM $tableName WHERE classId =:classId");
$result = $stmt->execute($inputArray);
return $result;
}
?>
this is my addinfo.php
<?php
include '../common/inc.common.php';
$class_id=$_POST['refid'];
if(isset($_POST['mode']))
{
$tableName="class";
$class_id=$_POST['refid'];
$res=$Cobj->delet($tableName, $class_id);
}
?>
on passing variables using AJAX call i couldn't able to delete the row .Ajax call is success . only problem with PDO delete.
$.ajax({
url: "../masters/addinfo.php",
type: "POST",
data:"refid="+class_id+"&mode=delete",
});
my class table has 4 fields classId,name,date,stat.
The $stmt variable in function delet() is not defined.
public function delet($tableName, $class_id){
$inputArray['classId']=$class_id;
$stmt = $this->$dbCon->prepare("DELETE FROM $tableName WHERE classId =:classId");
$result = $stmt->execute($inputArray);
return $result;
}
Will fix this. Note what changed; $count changed to $stmt
I am new to OOP, and I am switching all of my websites code to it! I am currently writing a class that grabs a user's information, and will eventually update it.
The code I am using is below:
<?php
require("C:\wamp\www\postin'\db_connection.php");
session_start();
class user {
public function __construct($userid, $connection, $information) {
$this->userid = $userid;
$this->connection = $connection;
$this->information = $information;
}
public function user_information($userid, $connection, $information) {
$query = "SELECT * FROM users WHERE id = :id";
$params = array(':id' => $userid);
try{
$stmt = $connection->prepare($query);
$result = $stmt->execute($params);
}
catch(PDOException $ex){
echo ("Failed to run query: " . $ex->getMessage());
}
$columns = $stmt->fetch();
return $columns["$information"];
}
}
$username = new user($_SESSION["logged_in"], $connection, "username");
echo $username->user_information($_SESSION["logged_in"], $connection, "username");
?>
Now as you can see on the last two lines of code (one from the end) I have to use the parameters twice. Basically the first parameter says what the ID is, second says what the $connection is, and the third is what I want to grab from the database. So what am I doing wrong? Did I define something I did not need to?
EDIT
Would the following be valid as well?
<?php
require("C:\wamp\www\postin'\db_connection.php");
session_start();
class user {
public function user_information($userid, $connection, $information) {
$query = "SELECT * FROM users WHERE id = :id";
$params = array(':id' => $userid);
try{
$stmt = $connection->prepare($query);
$result = $stmt->execute($params);
}
catch(PDOException $ex){
echo ("Failed to run query: " . $ex->getMessage());
}
$columns = $stmt->fetch();
return $columns["$information"];
}
}
$username = new user();
echo $username->user_information($_SESSION["logged_in"], $connection, "username");
?>
Like is this in-properer, or wrong...?
If the user class has all the information it needs as data members, then user_information doesn't need to take any arguments:
public function user_information() {
$query = "SELECT * FROM users WHERE id = :id";
$params = array(':id' => $this->userid);
try{
$stmt = $this->connection->prepare($query);
$result = $stmt->execute($params);
}
catch(PDOException $ex){
echo ("Failed to run query: " . $ex->getMessage());
}
$columns = $stmt->fetch();
return $columns[$this->information];
}
Since you have a lot of questions about the way a class works and about OOP I will try to give you a little direction.
There is no standard way of building your class. You are the one that decides what goes where in terms of what belongs to the class and what needs to be injected. This is just to tell you that you cannot pin yourself down. You need to get a feel for it and build a logic.
I took your class and rebuild it some with added comments. Hope that will help you some. Good luck!
<?php
require ("C:\wamp\www\postin'\db_connection.php");
session_start();
class user {
public $dbconnection;
public function __construct($connection) {
/**
* Your user class interacts with the database.
* Inject the connection here and set your
* global class variable.
*/
$this -> dbconnection = $connection;
}
public function user_information($userid, $column) {
/**
* The userid and column are specific for this
* method action. No need to set these variables
* in the global scope of the class.
*/
$query = "SELECT" . $column . " FROM users WHERE id = :id";
$params = array(':id' => $userid);
try {
$stmt = $this -> dbconnection -> prepare($query);
$stmt -> execute($params);
} catch(PDOException $ex) {
echo("Failed to run query: " . $ex -> getMessage());
}
$result = $stmt -> fetch();
return $result;
}
}
$username = new user($connection);
echo $username -> user_information($_SESSION["logged_in"], $information);
?>
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 8 years ago.
Improve this question
How can I put those two code snippets in a class so the databasehandling is in a class? Like a PDO connection or put all that have to do with database is in a class, how would you guys do it?
Here are two parts of the code from different files. I am trying to develop a blog application.
<?php
mysql_connect("localhost", "root", "")or die(mysql_error());
mysql_select_db("blogg1")or die(mysql_error());
if(isset($_POST["submit"])){
$title = $_POST["title"];
$category = $_POST["category"];
$content = $_POST ["content"];
mysql_query("INSERT INTO blogdata(title , category , content) VALUES('$title', '$category', '$content')");
}else{
?>
<?php
mysql_connect("localhost", "root", "")or die(mysql_error());
mysql_select_db("blogg1")or die(mysql_error());
$sql = mysql_query("SELECT * FROM blogdata ORDER BY id DESC")or die(mysql_error());;
while($row = mysql_fetch_array($sql)){
$title = $row["title"];
$category = $row["category"];
$content = $row["content"];
?>
<table border = "1">
<tr><td><?php echo $title; ?></td><td><?php echo $category; ?></td></tr>
<tr><td colspan="2"><?php echo $content; ?></td></tr>
</table>
<?php
}
?>
First, you should keep your database credentials in a separate PHP file in a folder not accessible by the web, for example ~/lib/db.php
<?php
define('SQL_HOST', 'localhost');
define('SQL_DATABASE', 'your-db-name');
define('SQL_USER', 'your-db-user');
define('SQL_PASS', 'your-db-password');
?>
Then your Database class (also in ~/lib):
<?php
require_once('~/lib/db.php');
require_once('~/lib/BlogData.php');
class Database
{
protected $db = null;
function __construct()
{
// db connection options
$driverOptions = array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'",
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
PDO::ATTR_EMULATE_PREPARES => false
);
// set new connection
$this->db = PDO(
"mysql:dbname=".SQL_DATABASE.";host=".SQL_HOST,
SQL_USER, SQL_PASS, $driverOptions
);
}
// This function lets you fetch blog data using any sort order you'd like and any WHERE criteria you want
function getBlogData($where = "1", $orderBy = "id DESC")
{
$stmt = $this->db->prepare("
SELECT *
FROM {'blogdata'} WHERE $where
ORDER BY $orderBy
");
$blogData = Array();
if ($stmt->execute())
{
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$oneBlogData = new BlogData($this);
$oneBlogData->init($row);
$blogData[] = $oneBlogData;
}
}
return $blogData;
}
function insertBlogData(BlogData $blogData)
{
$stmt = $this->db->prepare("
INSERT INTO {'blogdata'} (title , category , content) VALUES
(:title, :category, :content);
");
$stmt->bindParam(':title', $blogData->title, PDO::PARAM_STR);
$stmt->bindParam(':category', $blogData->category, PDO::PARAM_STR);
$stmt->bindParam(':content', $blogData->content, PDO::PARAM_STR);
$stmt->execute();
}
}
?>
Then I would define another class for your blog data:
<?php
class BlogData {
public $title;
public $category;
public $content;
private $db;
function __construct(Database $db)
{
$this->db = $db;
}
function init($dbRow)
{
$this->title = $dbRow['title'];
$this->category = $dbRow['category'];
$this->content = $dbRow['content'];
}
function save()
{
// TODO: Write sql statement to save the row...
}
}
?>
Then your first block of code could create a new BlogData entry like this:
<?php
require_once('~/lib/Database.php');
$db = new Database();
if(isset($_POST["submit"]))
{
$blogData = new BlogData($db);
$blogData->title = $_POST["title"];
$blogData->category = $_POST["category"];
$blogData->content = $_POST["content"];
$db->insertBlogData($blogData);
}
?>
And your second block of code could look like this:
<?php
require_once('~/lib/Database.php');
$db = new Database();
$blogDataArray = $db->getBlogData("1", "id DESC");
echo "<table border = '1'>";
foreach($blogDataArray as $blogData)
{
echo "<tr><td>" . $blogData->title . "</td><td>" . $blogData->category . "</td></tr>";
echo "<tr><td colspan='2'>" . $blogData->content . "</td></tr>";
}
echo "</table>";
?>
This also makes it really easy to modify BlogData entries - just fetch the blog data from the Database using the getBlogData function, modify the object by simply changing it's values and calling save. For example:
<?php
// ...
$newContent = "New Content";
$blogData = $db->getBlogData("id='1'");
$blogData->content = $newContent;
$blogData->save();
?>
I should also point out the obvious that you need some unique field for your blog data entries. With some id, it'd be easier to write addToDatabase and save in one function.
Please see below for the code example:
class SomeClass {
protected $db = null;
protected $table = 'blogdata';
public function __construct()
{
// db connection options
$driverOptions = array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'",
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
);
// set new connection
$this->db = PDO(
"mysql:dbname=blogg1;host=localhost",
'root', '', $driverOptions
);
}
public function save($data)
{
// prepare your data
$title = $data["title"];
$category = $data["category"];
$content = $data ["content"];
// prepare statement
$stmt = $this->db->prepare("
INSERT INTO {$this->table} (title , category , content) VALUES
(:title, :category, :content);
");
$stmt->bindParam(':title', $title, PDO::PARAM_STR);
$stmt->bindParam(':category', $category, PDO::PARAM_STR);
$stmt->bindParam(':content', $content, PDO::PARAM_STR);
$stmt->execute();
}
public function getRecords()
{
$stmt = $this->db->prepare("
SELECT *
FROM {$this->table}
ORDER BY id DESC
");
$stmt->execute();
return $stmt->fetchAll();
}
}
And a usage example:
<?php
require_once('SomeClass.php');
$ent = new SomeClass();
if (isset($_POST["submit"])) {
$ent->save($_POST);
}
else {
// get and output
$records = $ent->getRecords();
if (count($records) > 0) {
?>
<table>
<?php
foreach ($records as $record) {
echo "<tr><td>{$record->title}</td><td>{$record->category}</td></tr>
<tr><td colspan='2'>{$record->content}</td></tr>";
}
?>
</table>