Can someone explain
Why this did not works ?
<?php
class category
{
function __construct()
{
$con = new mysqli("localhost", "root", "", "whatever");
}
function show_all()
{
$sql = "SELECT id_kategori, nama_kategori FROM kategori";
$stmt = $con->prepare($sql);
$stmt->execute();
$stmt->bind_result($id, $cat);
while($stmt->fetch())
{
echo "<td>$id</td>";
echo "<td>$cat</td>";
echo "<td>Update</td>";
echo "<td>Delete</td>";
};
$stmt->close();
}
}
?>
But this works ?
<?php
class category
{
function show_all()
{
$con = new mysqli("localhost", "root", "", "whatever");
$sql = "SELECT id_kategori, nama_kategori FROM kategori";
$stmt = $con->prepare($sql);
$stmt->execute();
$stmt->bind_result($id, $cat);
while($stmt->fetch())
{
echo "<td>$id</td>";
echo "<td>$cat</td>";
echo "<td>Update</td>";
echo "<td>Delete</td>";
};
$stmt->close();
}
}
?>
Without construct, it works, with construct it's don't.
Can somebody show me, tell me, teach me how to include sql connection in a construct the right way ? I'm still new and learning by the way.
This is because of scoping. The $con variable should be defined to be used in the class exclusively rather than just locally inside the __construct.
When you define $con inside the __construct you are scoping this to be locally used inside the function __construct rather than in the class itself
Consider the following code
<?php
class category
{
private $con;
function __construct()
{
$this->con = new mysqli("localhost", "root", "", "whatever");
}
function show_all()
{
$sql = "SELECT id_kategori, nama_kategori FROM kategori";
$stmt = $this->con->prepare($sql);
$stmt->execute();
$stmt->bind_result($id, $cat);
while($stmt->fetch())
{
echo "<td>$id</td>";
echo "<td>$cat</td>";
echo "<td>Update</td>";
echo "<td>Delete</td>";
};
$stmt->close();
}
}
?>
$con is not a variable accessible in the class above: Try this:
<?php
class category
{
private $con = NULL;
function __construct()
{
$this->con = new mysqli("localhost", "root", "", "whatever");
}
function show_all()
{
$sql = "SELECT id_kategori, nama_kategori FROM kategori";
$stmt = $this->con->prepare($sql);
$stmt->execute();
$stmt->bind_result($id, $cat);
while($stmt->fetch())
{
echo "<td>$id</td>";
echo "<td>$cat</td>";
echo "<td>Update</td>";
echo "<td>Delete</td>";
};
$stmt->close();
}
}
?>
and look at documentation here:
http://php.net/manual/en/language.oop5.php
and look up php scope:
http://php.net/manual/en/language.variables.scope.php
Also if you are having questions always add this to your code:
This would have told you the variable is undefined:
error_reporting(E_ALL);
ini_set('display_errors', '1');
Related
I searched similar issues here but could not fix my problem.
I'm trying to add a search function to my website, but for some reason the search results are not displayed. In my error_log I get this error:
PHP Fatal error: Call to a member function prepare() on null in /home/..../search.php on line 9
which is this line:
$query = $pdo->prepare("SELECT * FROM subs WHERE sub_title LIKE '%$search%' LIMIT 0, 10");
Here is my search.php code:
<?php
require_once('includes/config.php');
include("includes/header.php");
// Search from MySQL database table
$search = $_POST['search'];
$query = $pdo->prepare("SELECT * FROM subs WHERE sub_title LIKE '%$search%' LIMIT 0, 10");
$query->bindValue(1, "%$search%", PDO::PARAM_STR);
$query->execute();
// Display search result
if(!$query->rowCount() == 0) {
echo "Search found:<br>";
echo "<table>";
echo "<tr><td>Title</td><td>Category></td><td>Language</td><td>Time</td><td>Download</td></tr>";
while($results = $query->fetch()) {
echo "<tr><td>";
echo $results['sub_title'];
echo "</td><td>";
echo $results['category'];
echo "</td><td>";
echo $results['sub_lang'];
echo "</td><td>";
echo $results['timestamp'];
echo "</td><td>";
echo $results['sub_data'];
echo "</td></tr>";
}
echo "</table>";
} else {
echo "Nothing found";
}
?>
Here is my config.php
<?php
$username = '------';
$password = '------';
try {
$conn = new PDO('mysql:host=localhost;dbname=-----', $username, $password, array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
}
catch(PDOException $e) {
echo "Failed to connect to database!" . "<br><br>";
echo $e->getMessage();
}
?>
and here is my search form which is in the header.php
<form class="form-inline" action="search.php" method="POST">
<input class="form-control" name="search" id="search" type="text" placeholder="Search">
</form>
you're using: $query = $pdo->prepare
It should be:
$query = $conn->prepare()
Because I am a lazy coder I made a new class to save a bit of time:
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;
}
}
I created a function to grab data from my database. I want this function to be reusable just by placing correct arguments for different tables. Here's what I've done :
public function selectdata($table, $arguments='*', $where = null){
if($this->isconnect){
//check whether users put column names in the select clause
if(is_array($arguments)){
$new_args = implode(',', $arguments);
$sql = 'SELECT '.$new_args.' FROM '.$table;
} else {
$sql = 'SELECT '.$arguments.' FROM '.$table;
}
//check whether users use the where clause
if($where != null && is_array($where)){
$where = implode(' ', $where);
$sql .= ' WHERE '.$where ;
}
$query = $this->db->query($sql);
$query -> SetFetchMode(PDO::FETCH_NUM);
while($row = $query->fetch()){
print_r($row);
}
} else {
echo 'failed, moron';
}
}
And this is the way to run the function :
$columnname = array('bookname');
$where = array('bookid','=','2');
echo $database-> selectdata('buku', $columnname, $where);
The code worked quite decently so far, but I'm wondering how I want to use $where but without $columnname in the function. How do I pass the arguments in the function?
And could you point to me the better way to create a function to grab data using PDO?
Just use a PDO class which can look like this:
<?php
class DB_Connect{
var $dbh;
function __construct(){
$host = "xxx";
$db = "xxx";
$user = "xxx";
$password = "xxx";
$this -> dbh = $this -> db_connect($host, $db, $user, $password);
}
public function getDBConnection(){
return $this -> dbh;
}
protected function db_connect($host, $db, $user, $password){
//var_dump($host, $db, $user, $password);exit();
try {
$dbh = new PDO("mysql:host=$host;dbname=$db", $user, $password);
}
catch(PDOException $err) {
echo "Error: ".$err->getMessage()."<br/>";
die();
}
return $dbh;
}
public function query($statement){
$keyword = substr(strtoupper($statement), 0, strpos($statement, " "));
$dbh = $this->getDBConnection();
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;
}
}
}
?>
Now you can include that class and create an object with $dbh = new DB_Connect; and call every statement you want just with the reference on $dbh->query($statement)
This is my prefered way to do this.
EDIT: If you want to use a statement on another Database, just use the __construct($db) method to pass your database name on object creation
I wonder whats the problem in my code? I tried all the sources I can search but it still gives me the same error which is still "Call to a member function bind_Param() on a non-object".here's my code.,hope someone can help me, thanks
$app->get('/students/:student_id',function () use($app){
$sql = "SELECT * FROM students WHERE student_id =:student_id";
try {
$db = connect_db();
$stmt = $db->prepare($sql);
$stmt->bind_Param("student_id", $student_id);
$stmt->execute();
$students = $stmt->fetchObject();
$db = null;
echo json_encode($students);
}
catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
});
This one works:
$app->get('/students/:student_id', function ($student_id) use($app){
$sql = "SELECT * FROM students WHERE student_id = ?";
try {
$db = connect_db();
$stmt = $db->prepare($sql);
$stmt->bind_Param("i", $student_id);
$stmt->execute();
$result = $stmt->get_result();
$students = $result->fetch_object();
$db = null;
echo json_encode($students);
}
catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
});
I assume that you're using this definition of the connect_db function:
function connect_db() {
$dbhost="localhost";
$dbuser="user";
$dbpass="pass";
$dbname="stackoverflow-33750846";
return new mysqli($dbhost, $dbuser, $dbpass, $dbname);;
}
Perhaps there is a bit of confusion using the database connection and read data from it, so I add some points:
Be sure to pass $student_id as a parameter to the callable function;
$stmt->bind_Param accepts a string that represents the type of the parameters and all the binding parameters;
fetchObject is a function of the mysqli_result class.
i have problem with function pdo, when it will take 1 record from the database, the result is null;
connect.php
<?php
class dbConn{
protected static $db;
private function __construct() {
try {
self::$db = new PDO( 'mysql:host=localhost;dbname=item', 'root', '' );
self::$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch (PDOException $e) {
echo "Connection Error " . $e->getMessage();
}
}
public static function getConnection() {
if (!self::$db) {
new dbConn();
}
return self::$db;
}
}
?>
function.php
<?php
include 'connect.php';
class ajax_table {
function detailitem($table){
$db = dbConn::getConnection();
$sql = "select * from ".$table."" or die(mysql_error());
$q = $db->query($sql) or die("failed!");
$res = $q->fetch(PDO::FETCH_ASSOC);
return $res;
//else echo "No records found";
}
}
?>
and to display
displayitem.php
<?php
$url = $_GET['url'];
$url=$url.'.html';
include 'connect.php';
include 'function.php';
$db = dbConn::getConnection();
$obj = new ajax_table();
$records = $obj->detailitem('product WHERE url = "$url"');
if($records){
echo $records['name'];
echo '<br>';
echo $records['type'];
}else{
echo 'no result';
} ?>
database is not empty, but result display
no error, and also does not display anything
If you see correctly on the following line :
$records = $obj->detailitem('product WHERE url = "$url"');
It passes the string as "$url" , not the value of $url variable.
So change it to :
$records = $obj->detailitem('product WHERE url = \''.$url.'\'');
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>