php code to a class? [closed] - php

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>

Related

Fatal Error while running a CMS program

i get this error while running my program.
Fatal error: Uncaught Error: Call to undefined method
CarModel::InsertCar() in
C:\xampp\htdocs\CoffeeWebsite\Controller\CarController.php:119 Stack
trace: #0 C:\xampp\htdocs\CoffeeWebsite\CarAdd.php(43):
CarController->InsertCar() #1 {main} thrown in
C:\xampp\htdocs\CoffeeWebsite\Controller\CarController.php on line 119
//Source code for CarModel and CarController
<?php
require ("Entities/CarEntity.php");
//Contains database related code for the Car page.
class CarModel {
//Get all car types from the database and return them in an array.
function GetCarTypes() {
require 'Credentials.php';
//Open connection and Select database.
$con = mysqli_connect($host, $user, $passwd) or die(mysqli_error($con));
$sql = mysqli_select_db($con,$database);
$result = mysqli_query($con,"SELECT DISTINCT type FROM car") or die(mysqli_error($con));
$types = array();
//Get data from database.
while ($row = mysqli_fetch_array($result)) {
array_push($types, $row[0]);
}
//Close connection and return result.
mysqli_close($con);
return $types;
}
//Get carEntity objects from the database and return them in an array.
function GetCarByType($type) {
require 'Credentials.php';
//Open connection and Select database.
$con = mysqli_connect($host, $user, $passwd) or die(mysqli_error($con));
$sql = mysqli_select_db($con,$database);
$query = "SELECT * FROM car WHERE type LIKE '$type'";
$result = mysqli_query($con,$query) or die(mysqli_error($con));
$carArray = array();
//Get data from database.
while ($row = mysqli_fetch_array($result)) {
$name = $row[1];
$type = $row[2];
$price = $row[3];
$colour = $row[4];
$details = $row[5];
$image = $row[6];
$review = $row[7];
//Create car objects and store them in an array.
$car = new CarEntity(-1, $name, $type, $price, $colour, $details, $image, $review);
array_push($carArray, $car);
}
//Close connection and return result
mysqli_close($con);
return $carArray;
}
function GetCarByID($id)
{
require 'Credentials.php';
//Open connection and Select database.
$con = mysqli_connect($host, $user, $passwd) or die(mysqli_error($con));
$sql = mysqli_select_db($con,$database);
$query = "SELECT * FROM car WHERE id=$id";
$result = mysqli_query($con,$query) or die(mysqli_error($con));
//Get data from database.
while ($row = mysqli_fetch_array($result)) {
$name = $row[1];
$type = $row[2];
$price = $row[3];
$colour = $row[4];
$details = $row[5];
$image = $row[6];
$review = $row[7];
//Create car
$car = new CarEntity($id, $name, $type, $price, $colour, $details, $image, $review);
}
//Close connection and return result
mysqli_close($con);
return $car;
}
}
function InsertCar(CarEntity $car) {
$query = sprintf("INSERT INTO car
(name, type, price,colour,details,image,review)
VALUES
('%s','%s','%s','%s','%s','%s','%s')",
mysqli_real_escape_string($car->name),
mysqli_real_escape_string($car->type),
mysqli_real_escape_string($car->price),
mysqli_real_escape_string($car->colour),
mysqli_real_escape_string($car->details),
mysqli_real_escape_string("Images/Coffee/" . $car->image),
mysqli_real_escape_string($car->review));
$this->PerformQuery($query);
}
function UpdateCar($id, CarEntity $car) {
$query = sprintf("UPDATE car
SET name = '%s', type = '%s', price = '%s', colour = '%s',
details = '%s', image = '%s', review = '%s'
WHERE id = $id",
mysqli_real_escape_string($car->name),
mysqli_real_escape_string($car->type),
mysqli_real_escape_string($car->price),
mysqli_real_escape_string($car->colour),
mysqli_real_escape_string($car->details),
mysqli_real_escape_string("Images/Coffee/" . $car->image),
mysqli_real_escape_string($car->review));
$this->PerformQuery($query);
}
function DeleteCar($id) {
$query = "DELETE FROM car WHERE id = $id";
$this->PerformQuery($query);
}
function PerformQuery($query) {
require ('Credentials.php');
$con=mysqli_connect($host, $user, $passwd) or die(mysqli_error($con));
mysqli_select_db($con,$database);
//Execute query and close connection
mysqli_query($query) or die(mysqli_error($con));
mysqli_close($con);
}
?>
<?php
require ("Model/CarModel.php");
//Contains non-database related function for the Coffee page
class CarController {
function CreateCarDropdownList() {
$carModel = new CarModel();
$result = "<form action = '' method = 'post' width = '200px'>
Please select a type:
<select name = 'types' >
<option value = '%' >All</option>
" . $this->CreateOptionValues($carModel->GetCarTypes()) .
"</select>
<input type = 'submit' value = 'Search' />
</form>";
return $result;
}
function CreateOptionValues(array $valueArray) {
$result = "";
foreach ($valueArray as $value) {
$result = $result . "<option value='$value'>$value</option>";
}
return $result;
}
function CreateCarTables($types)
{
$carModel = new CarModel();
$carArray = $carModel->GetCarByType($types);
$result = "";
//Generate a carTable for each carEntity in array
foreach ($carArray as $key => $car)
{
$result = $result .
"<table class = 'carTable'>
<tr>
<th rowspan='6' width = '150px' ><img runat = 'server' src = '$car->image' /></th>
<th width = '75px' >Name: </th>
<td>$car->name</td>
</tr>
<tr>
<th>Type: </th>
<td>$car->type</td>
</tr>
<tr>
<th>Price: </th>
<td>$car->price</td>
</tr>
<tr>
<th>Colour: </th>
<td>$car->colour</td>
</tr>
<tr>
<th>Details: </th>
<td>$car->details</td>
</tr>
<tr>
<th>Review: </th>
<td colspan='2' >$car->review</td>
</tr>
</table>";
}
return $result;
}
function GetImages() {
//Select folder to scan
$handle = opendir("Images/Coffee");
//Read all files and store names in array
while ($image = readdir($handle)) {
$images[] = $image;
}
closedir($handle);
//Exclude all filenames where filename length < 3
$imageArray = array();
foreach ($images as $image) {
if (strlen($image) > 2) {
array_push($imageArray, $image);
}
}
//Create <select><option> Values and return result
$result = $this->CreateOptionValues($imageArray);
return $result;
}
//<editor-fold desc="Set Methods">
function InsertCar() {
$name = $_POST["txtName"];
$type = $_POST["ddlType"];
$price = $_POST["txtPrice"];
$colour = $_POST["txtColour"];
$details = $_POST["txtDetails"];
$image = $_POST["ddlImage"];
$review = $_POST["txtReview"];
$car = new CarEntity(-1, $name, $type, $price, $colour, $details, $image, $review);
$carModel = new CarModel();
$carModel->InsertCar($car);
}
function UpdateCar($id) {
}
function DeleteCar($id) {
}
//</editor-fold>
//<editor-fold desc="Get Methods">
function GetCarById($id) {
$carModel = new CarModel();
return $carModel->GetCarById($id);
}
function GetCarByType($type) {
$carModel = new CarModel();
return $carModel->GetCarByType($type);
}
function GetCarTypes() {
$carModel = new CarModel();
return $carModel->GetCarTypes();
}
//</editor-fold>
}
?>
To elaborate on my comment.
First you want to use Prepared statements. Here is an example:
/* Connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* Check connection */
if ($mysqli->connect_errno)
{
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
if($stmt = $mysqli->prepare("UPDATE..."))
{
/* Bind your params */
$stmt->bind_param('ss', $username, $password);
/* Error handling if execute failed */
if (!$stmt->execute())
{
die('execute() failed: ' . htmlspecialchars($stmt->error));
}
}
else
{
/* Error handling if Prepare failed */
die('prepare() failed: ' . htmlspecialchars($DBConnect->error));
}
$stmt->close();
Read more about returning result here
Now since you want to pass in args from your functions which are unknown to the PerformQuery function, you'll want to dynamically generate the Bind Params for use of using prepared statements. I've done something similar for dynamically generating the Bind Params using Reflection.
If you pass an Args value into the PerformQuery function you could have a function that looks like this:
public function PerformQuery($sql, $args = null)
{
/* Connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* Check connection */
if ($mysqli->connect_errno)
{
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
if($stmt = $mysqli->prepare($sql))
{
/* Bind your params dynamically */
if (isset($args))
{
$method = new \ReflectionMethod('mysqli_stmt', 'bind_param');
$method->invokeArgs($stmt, $this->refValues($args));
}
/* Error handling if execute failed */
if (!$stmt->execute())
{
die('execute() failed: ' . htmlspecialchars($stmt->error));
}
}
else
{
/* Error handling if Prepare failed */
die('prepare() failed: ' . htmlspecialchars($mysqli->error));
}
$stmt->close();
}
For the dynamic binding to work you'll also need the following function
private function refValues($arr)
{
if (strnatcmp(phpversion(),'5.3') >= 0) //Reference is required for PHP 5.3+
{
$refs = array();
foreach($arr as $key => $value)
$refs[$key] = &$arr[$key];
return $refs;
}
return $arr;
}
Now from your other methods, for example DeleteCar you'd pass in the query and args as follows:
public function DeleteCar($id)
{
$query = "DELETE FROM car WHERE id = ?"; // ? to show where mysqli will bind
$args = array('i', $id); // i means an int
$this->PerformQuery($query, args);
}
Using prepared statements will make your code much more secure and dynamically binding the variants in the Preform Query function means that you don't have to completely refactor your code to pass a connection around so you can use mysqli_real_escape_string.
Good luck :)

Iterating through a Multidimensional Array in php without known keys

I am writing a web application and I believe one of the parts requires a
multidimensional array. The array holds a list of applications in a database.
I want to be able to display the list of applications by the individuals name or
a unique ID. I have this part working. Then I want to click on an individual
application and only pull up that particular row of information to fill in a form.
Currently when I do this it either brings up all of the rows from the database or
the first row only. Does anyone have any suggestions?
I am not great with explanations so I am including parts of my code. I am sorry
it's so long. I tried to reduce it as much as possible. Even though its included
in the code, i didn't include config.php because it's just my database connection.
userList.php:
<?php
include("config.php");
?>
<!DOCTYPE html>
<html>
<body>
<h1>Test</h1>
<p><b><u>Users</b></u></p>
</body>
</html>
<?php
require_once("/class/users.php");
$rowt = array(array());
$rowt = users::fillForm($rowt);
foreach($rowt as $test) {
if(is_array($test))
{
echo "<a href='userDisplay.php'>".$test['name']."</a><br/>";
}
}
?>
userDisplay.php:
<!DOCTYPE html>
<html>
<body>
<h1>Tester</h1>
<?php
include("config.php");
//declare array
$rowt = array(array());
//pass array into class function
//since functions can't return more than one variable, you have to pass the
//array and set it equal to the original variable while calling the pdo function
$rowt = users::fillForm($rowt);
foreach($rowt as $test=> $rowt){
?>
<h2>Application for <?php echo $rowt['name']?></h2>
<table>
<tr><th><b>Name</b></th>
<th><b>Phone Number</b></th>
<th><b>Best Time to Call<b></th>
</tr>
<tr></tr>
<tr><td><output type='text' maxlength="30" required name='name'><?php echo $rowt['name']?></output></td>
<td><output type="text" maxlenth="30" required name="p_num"><?php echo $rowt['phone_number']?></output></td>
<td><output type='text' maxlength="30" required name='bc_time'><?php echo $rowt['best_call_time']?></output></td></tr>
<tr></tr>
<tr>
<th><b>Visa Status<b></th>
<th><b>IT Experience<b></th>
<th><b>Relevant Experience<b></th>
</tr>
<tr></tr>
<tr><td><output type='text' maxlength="30" required name='v_status'><?php echo $rowt['visa_status']?></output></td>
<td><output type='text' maxlength="30" required name='it_exp'><?php echo $rowt['it_exp']?></output></td>
<td><output type='text' maxlength="30" required name='rel_exp'><?php echo $rowt['relevant_exp']?></output></td>
</tr>
<tr></tr>
<tr>
<th colspan="3"><b>Description<b></th>
</tr>
<tr></tr>
<tr>
<td colspan="3"><output name="description" rows="4" cols="100"></output><?php echo $rowt['description']?>></td>
</tr>
</table>
</body>
</html>
<?php
}
echo "<a href='userList.php'>Back</a>";
?>
Functions from users.php users class:
public function insertForm() {
$correct = false;
try {
$con = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO user(name, phone_number, best_call_time, description,
visa_status, it_exp, relevant_exp) VALUES(:name, :p_num, :bc_time, :description,
:v_status, :it_exp, :rel_exp)";
$stmt = $con->prepare($sql);
$stmt->bindValue("name", $this->name, PDO::PARAM_STR);
$stmt->bindValue("p_num", $this->p_num, PDO::PARAM_STR);
$stmt->bindValue("bc_time", $this->bc_time, PDO::PARAM_STR);
$stmt->bindValue("v_status", $this->v_status, PDO::PARAM_STR);
$stmt->bindValue("it_exp", $this->it_exp, PDO::PARAM_STR);
$stmt->bindValue("rel_exp", $this->rel_exp, PDO::PARAM_STR);
$stmt->bindValue("description", $this->description, PDO::PARAM_STR);
$stmt->execute();
return "Entry Successful <br/> <a href='userForm.php'>Home</a>";
}catch(PDOException $e) {
return $e->getMessage();
}
}
public static function fillForm($rowt) {
$successt = false;
try{
$conn = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql1 = "SELECT * FROM user";
$stmt1 = $conn->prepare($sql1);
$stmt1->execute();
$rowt = $stmt1->fetchAll(PDO::FETCH_NUM&PDO::FETCH_ASSOC);
return $rowt;
}catch (PDOException $et) {
echo $et->getMessage();
return $successt;
}
}
There is a lot going on here, but if I get the gist of your question you want to be able to return one individual user when a row in a list of users is clicked. To do that you would need to update your SQL query to pull a particular user. Something along the lines of:
// Formatting into a class to cut down on repetition.
<?php
class User {
private $dbConnect;
// functionally these two are similar but I separated users and user
// for clarity of purpose.
public function getUsers()
{
// Enumerating your select columns is clearer, and more efficient.
$sql = "SELECT name, phone_number, best_call_time, description,
visa_status, it_exp, relevant_exp
FROM user";
$result = $this->makeQuery($sql);
return ($result) ? $result : array();
}
public function getUser($name)
{
// Enumerating your select columns is clearer, and more efficient.
$sql = "SELECT name, phone_number, best_call_time, description,
visa_status, it_exp, relevant_exp
FROM user
WHERE name = :name";
$param = $this->prepareUserInfo(array('name' => $name));
$result = $this->makeQuery($sql, $param);
return ($result) ? $result : array();
}
public function createUser($userInfo)
{
$sql = "INSERT INTO user(name, phone_number, best_call_time, description,
visa_status, it_exp, relevant_exp) VALUES(:name, :p_num, :bc_time, :description,
:v_status, :it_exp, :rel_exp)";
$params = $this->prepareUserInfo($userInfo);
try {
$this->connect();
$stmt = $this->dbConnect->prepare($sql);
$stmt = $this->bindParams($stmt, $data);
$stmt->execute();
return "Entry Successful <br/> <a href='userForm.php'>Home</a>";
} catch(PDOException $e) {
return $e->getMessage();
}
}
private function prepareUserInfo($userInfo)
{
$infoArray = array();
foreach ($userInfo as $key => $value) {
// Going with your original code I'm hardcoding param type here, but
// you could easily write a check for data type and set param dynamically.
$infoArray[] = array(
'key' => $key,
'value' => $value,
'type' => PDO::PARAM_STR,
);
}
return $infoArray;
}
private function makeQuery($sql, $data = array())
{
try{
$this->connect();
$stmt = $this->dbConnect->prepare($sql);
if (!empty($data)) {
$stmt = $this->bindParams($stmt, $data);
}
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_NUM&PDO::FETCH_ASSOC);
return (!empty($result)) ? $result : false;
} catch (PDOException $e) {
echo $e->getMessage();
return false;
}
}
private function bindParams($stmt, $data)
{
foreach ($data as $item) {
$stmt->bindValue("name", $this->name, PDO::PARAM_STR);
$stmt->bindValue($item['key'], $item['value'], $item['type']);
}
return $stmt;
}
private function connect()
{
$dbConnect = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD);
$dbConnect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->dbConnect = $dbConnect;
}
}
?>
From there your click handler would need to trigger a User->getUser('some name'); request. You could take this abstraction further by separating your PDO connect into it's own class and handle query building and execution from there.
Seconding the above comment about not mixing your presentation with your data layer. Check out a templating engine like Twig or (less advisable but sometimes necessary) roll your own by building a view loader that loads template files to an output buffer, adds dynamic variables, and returns a rendered string.

Why function __construct is not working in PHP?

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');

Get name from user with specific id PHP, SQL

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(); ?>

PHP Class Parameters used twice

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);
?>

Categories