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 :)
Related
I have a custom class that takes a sql connection as a parameter. I use that to populate the class, and then I'm trying to use it again to modify the results on screen. But after the first use, I can't use it anymore.
connection.php:
$conn = new mysqli('localhost', 'root', '', 'loveConnections');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
personalityProfile.php (front end)
if (!isset($_SESSION['interests'])) {
$interests = new Interests($conn, $_SESSION['id']);
$_SESSION['interests'] = $interests;
} else {
$interests = $_SESSION['interests'];
}
interestsObject.php
class Interests {
// properties
public $conn;
public $id;
public $interestsArray = [];
public function __construct($conn, $memberId = null, $intArray = [
'basketball' => false,
'bowling' => false,
'movies' => false,
]) {
$this->conn = $conn;
$this->id = $memberId;
$this->interestsArray = $intArray;
$this->popArraySql();
}
public function popArraySql() {
$memInterests = [];
$sql = "SELECT i.interest
FROM memberInfo m
Join MemberInterestLink mi on (mi.memberID_FK = m.memberID_PK)
Join interests i on (mi.interestID_FK = i.interestID_PK)
WHERE memberID_PK = $this->id";
$result = $this->conn->query($sql);
$this->conn works perfectly here
foreach ($result as $row) {
array_push($memInterests, $row['interest']);
}
foreach ($this->interestsArray as $key => $value) {
for ($i=0; $i<sizeof($memInterests); $i++) {
if ($memInterests[$i] === $key) {
$this->interestsArray[$key] = true;
}
}
}
}
public function insertUpdateQuery() {
var_dump($this->conn);
foreach ($this->interestsArray as $key => $val) {
echo $key . "<br>";
$select = "SELECT interestID_PK from interests where interest = '" . $key . "'";
echo $select;
$result = $this->conn->query($select);
when I try and use it later though, I get a Warning: mysqli::query(): Couldn't fetch mysqli. Additionally, if I try and var_dump it, I get Warning: var_dump(): Property access is not allowed yet
var_dump($result);
if ($val === true) {
$insert = "INSERT INTO MemberInterestLink (memberID_FK, interestID_FK) VALUES ($this->id, $interestKey)";
$this->conn->query($insert);
} else {
$delete = "DELETE FROM MemberInterestLink WHERE interestID_FK = $interestKey";
$this->conn->query($delete);
}
}
}
}
I never close the connection, which is what most of the related answers suggested the cause may be. It's like my $conn variable just stops working after the first use.
i am developing a search option using php. there i need to do search using user given criteria user can be search when user give id,name,status any of combination of these three parameters.below is my code
if(isset($_POST['search']))
{
echo "<script> document.getElementById('tblsearch').style.display = 'block' </script> ";
$serviceNumber=$_POST['serviceNumber'];
$name=$_POST['name'];
$pendingfrom=$_POST['pendingfrom'];
$status=$_POST['status'];
$datefrom=$_POST['datefrom'];
$dateto=$_POST['dateto'];
$searchkey='serviceNumber';
$mysqli = new mysqli("localhost", "root", "", "user_management");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = 'SELECT * FROM user WHERE ';
$where = array();
$values = array();
$types = '';
if (!empty($_POST['serviceNumber'])) {
$where[] = 'serviceNumber = ?';
$values[] = $_POST['serviceNumber'];
$types .= 'i';
}
if (!empty($_POST['name'])) {
$where[] = 'Username = ?';
$values[] = $_POST['name'];
$types .= 's';
}
if (!empty($_POST['status'])) {
$where[] = 'status = ?';
$values[] = $_POST['status'];
$types .= 's';
}
$query .= implode(' AND ',$where);
printf("rows inserted: %d\n", $query);
printf("rows inserted: %d\n", $values);
/* prepare statement */
if ($stmt = $mysqli->prepare($query)) {
/* Bind variable for placeholder */
$stmt->bind_param($types,$values);
/* execute statement */
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
printf("rows inserted: %d\n", $stmt->num_rows);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
below line i was going confused,because $values is an array.i need to pass user given paremeters to this in order to execute.
$stmt->bind_param($types,$values);
so in order to get correct results how do i need to do this.
You can use call_user_func_array() to call a function with an array of parameters. The parameters need to be stored as references in order to be passed to the bind_param method. Long story short, you need an array where the 1st value is a string and the rest are references to your parameters.
For example:
$bindParams = [$types];
foreach ($values as $key => $value) {
$bindParams[$key] = &$value;
}
call_user_func_array(
[$stmt, 'bind_param'], //array with the object and the method - callable
$bindParams
);
Try using below:
if(isset($_POST['search']))
{
echo "<script> document.getElementById('tblsearch').style.display = 'block' </script> ";
$serviceNumber=$_POST['serviceNumber'];
$name=$_POST['name'];
$pendingfrom=$_POST['pendingfrom'];
$status=$_POST['status'];
$datefrom=$_POST['datefrom'];
$dateto=$_POST['dateto'];
$searchkey='serviceNumber';
$mysqli = new mysqli("localhost", "root", "", "user_management");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = 'SELECT * FROM user WHERE ';
if (!empty($_POST['serviceNumber'])) {
$query .="serviceNumber='$searchkey' ";
}
if (!empty($_POST['name'])) {
$query .="and Username='$name' ";
}
if (!empty($_POST['status'])) {
$where[] = 'status = ?';
$values[] = $_POST['status'];
$query .=" and status='$status' ";
}
/* prepare statement */
if ($stmt = $mysqli->prepare($query)) {
/* Bind variable for placeholder */
$stmt->bind_param($types,$values);
/* execute statement */
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
printf("rows inserted: %d\n", $stmt->num_rows);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
Hope this helps.
I want to make a sendmail function on my program. But first, I want to store the information: send_to, subject, and message in a table in another database(mes) where automail is performed. The problem is data fetched from another database(pqap) are not being added on the table(email_queue) in database(mes).
In this code, I have a table where all databases in the server are stored. I made a query to select a specific database.
$sql5 = "SELECT pl.database, pl.name FROM product_line pl WHERE visible = 1 AND name='PQ AP'";
$dbh = db_connect("mes");
$stmt5 = $dbh->prepare($sql5);
$stmt5->execute();
$data = $stmt5->fetchAll(PDO::FETCH_ASSOC);
$dbh=null;
Then after selecting the database,it has a query for selecting the information in the table on the selected database. Here's the code.
foreach ($data as $row5) GenerateEmail($row5['database'], $row5['name']);
Then this is part (I think) is not working. I don't know what's the problem.
function GenerateEmail($database, $line) {
$sql6 = "SELECT * FROM invalid_invoice WHERE ID=:id6";
$dbh = db_connect($database);
$stmt6 = $dbh->prepare($sql6);
$stmt6->bindParam(':id6', $_POST['idtxt'], PDO::PARAM_INT);
$stmt6->execute();
$data = $stmt6->fetchAll(PDO::FETCH_ASSOC);
$dbh=null;
foreach ($data as $row6) {
$invnumb=$row6['Invoice_Number'];
$partnumb=$row6['Part_Number'];
$issue=$row6['Issues'];
$pic=$row6['PIC_Comments'];
$emailadd= $row6['PersoninCharge'];
if($row6['Status']=="Open") {
$message = "<html><b>Invoice Number: {$invnumb}.</b><br><br>";
$message .= "<b>Part Number:</b><br><xmp>{$partnumb}</xmp><br><br>";
$message .= "<b>Issues:</b><br><xmp>{$issue}</xmp><br>";
$message .= "<b>{$pic}<b><br>";
$message .= "</html>";
if(!empty($emailadd)) {
dbInsertEmailMessage($emailadd, "Invoice Number: {$invnumb} - {$issue}.", $message);
$dbh=null;
}
}
}
}
function dbInsertEmailMessage($send_to, $subject, $message) {
$sql7 = "INSERT INTO email_queue (Send_to, Subject, Message) VALUES (:send_to, :subject, :message)";
$dbh = db_connect("mes");
$stmt7 = $dbh->prepare($sql7);
$stmt7->bindParam(':send_to', $send_to, PDO::PARAM_STR);
$stmt7->bindParam(':subject', $subject, PDO::PARAM_STR);
$stmt7->bindParam(':message', $message, PDO::PARAM_STR);
$stmt7->execute();
$dbh=null;
}
Here's my db connection:
function db_connect($DATABASE) {
session_start();
// Connection data (server_address, database, username, password)
$servername = '*****';
//$namedb = '****';
$userdb = '*****';
$passdb = '*****';
// Display message if successfully connect, otherwise retains and outputs the potential error
try {
$dbh = new PDO("mysql:host=$servername; dbname=$DATABASE", $userdb, $passdb, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
return $dbh;
//echo 'Connected to database';
}
catch(PDOException $e) {
echo $e->getMessage();
}
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
There are a couple things that may help with your failed inserts. See if this is what you are looking for, I have notated important points to consider:
<?php
// take session_start() out of your database connection function
// it draws an error when you call it more than once
session_start();
// Create a connection class
class DBConnect
{
public function connect($settings = false)
{
$host = (!empty($settings['host']))? $settings['host'] : false;
$username = (!empty($settings['username']))? $settings['username'] : false;
$password = (!empty($settings['password']))? $settings['password'] : false;
$database = (!empty($settings['database']))? $settings['database'] : false;
try {
$dbh = new PDO("mysql:host=$host; dbname=$database", $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
// You return the connection before it hits that setting
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbh;
}
catch(PDOException $e) {
// Only return the error if an admin is logged in
// you may reveal too much about your database on failure
return false;
//echo $e->getMessage();
}
}
}
// Make a specific connection selector
// Put in your database credentials for all your connections
function use_db($database = false)
{
$con = new DBConnect();
if($database == 'mes')
return $con->connect(array("database"=>"db1","username"=>"u1","password"=>"p1","host"=>"localhost"));
else
return $con->connect(array("database"=>"db2","username"=>"u2","password"=>"p2","host"=>"localhost"));
}
// Create a query class to return selects
function query($con,$sql,$bind=false)
{
if(empty($bind))
$query = $con->query($sql);
else {
foreach($bind as $key => $value) {
$kBind = ":{$key}";
$bindVals[$kBind] = $value;
}
$query = $con->prepare($sql);
$query->execute($bindVals);
}
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$result[] = $row;
}
return (!empty($result))? $result:0;
}
// Create a write function that will write to database
function write($con,$sql,$bind=false)
{
if(empty($bind))
$query = $con->query($sql);
else {
foreach($bind as $key => $value) {
$kBind = ":{$key}";
$bindVals[$kBind] = $value;
}
$query = $con->prepare($sql);
$query->execute($bindVals);
}
}
// Do not create connections in your function(s), rather pass them into the functions
// so you can use the same db in and out of functions
// Also do not null the connections out
function GenerateEmail($con,$conMes,$line = false)
{
if(empty($_POST['idtxt']) || (!empty($_POST['idtxt']) && !is_numeric($_POST['idtxt'])))
return false;
$data = query($con,"SELECT * FROM `invalid_invoice` WHERE `ID` = :0", array($_POST['idtxt']));
if($data == 0)
return false;
// Instead of creating a bunch of inserts, instead create an array
// to build multiple rows, then insert only once
$i = 0;
foreach ($data as $row) {
$invnumb = $row['Invoice_Number'];
$partnumb = $row['Part_Number'];
$issue = $row['Issues'];
$pic = $row['PIC_Comments'];
$emailadd = $row['PersoninCharge'];
if($row['Status']=="Open") {
ob_start();
?><html>
<b>Invoice Number: <?php echo $invnumb;?></b><br><br>
<b>Part Number:</b><br><xmp><?php echo $partnumb; ?></xmp><br><br>
<b>Issues:</b><br><xmp><?php echo $issue; ?></xmp><br>
<b><?php echo $pic; ?><b><br>
</html>
<?php
$message = ob_get_contents();
ob_end_clean();
if(!empty($emailadd)) {
$bind["{$i}to"] = $emailadd;
$bind["{$i}subj"] = "Invoice Number: {$invnumb} - {$issue}.";
$bind["{$i}msg"] = htmlspecialchars($message,ENT_QUOTES);
$sql[] = "(:{$i}to, :{$i}subj, :{$i}msg)";
}
}
$i++;
}
if(!empty($sql))
return dbInsertEmailMessage($conMes,$sql,$bind);
return false;
}
function dbInsertEmailMessage($con,$sql_array,$bind)
{
if(!is_array($sql_array))
return false;
write($con,"INSERT INTO `email_queue` (`Send_to`, `Subject`, `Message`) VALUES ".implode(", ",$sql_array),$bind);
return true;
}
// Create connections
$con = use_db();
$conMes = use_db('mes');
GenerateEmail($con,$conMes);
I am trying to establish a data connection to the MySql and create prepared statements, where the query_f function takes in any number of parameters, where the first parameter is the sql statement, and the other parameters are the values that would be substituted in the prepared statement.
Here is what I have. The first error I got is when I am trying to bind the values to the statement.
function query_f(/* query, [...] */){
$user = "root";
$pass = "root";
$host = "localhost";
$database = "mcnair";
$conn = mysqli_connect($host,$user,$pass);
if(!$conn)
{
echo "Cannot connect to Database";
}
else
{
mysqli_select_db($conn, $database);
}
// store query
$query = func_get_arg(0);
$parameters = array_slice(func_get_args(), 1);
$param = "'".implode("','",$parameters)."'";
// Prepare the statement
$stmt = mysqli_prepare($conn, $query);
if ($stmt == false)
{
echo "The statement could not be created";
exit;
}
// Bind the parameters
$bind = mysqli_stmt_bind_param($stmt, 's', $param);
echo mysqli_stmt_error($stmt);
if ($bind == false)
{
echo "Could not bind";
}
else
{
echo "Bind successful";
}
// Execute the statement
$execute = mysqli_stmt_execute($stmt);
if ($execute = false)
{
echo "Could not execute";
}
// fetch the data
$fetch = mysqli_stmt_fetch($stmt)
if ($fetch == false)
{
echo "Could not fetch data";
}
else
{
return $fetch;
}
}
And the function call I am using is:
query_f("SELECT Hash FROM alumni WHERE Username = '?'", "zm123");
How about using a class (instead of a function) and using mysqli in the OO way and not in the procedural way?
This is a simplified version of what I use. Not perfect, so if anyone would like to suggest improvements, I'm all ears.
class Connection {
private $connection;
public function __construct()
{
//better yet - move these to a different file
$dbhost = '';
$dbuname = '';
$dbpass = '';
$dbname = '';
$this->connection = new mysqli($dbhost, $dbuname, $dbpass, $dbname);
}
/*
* This is the main function.
*
* #param $arrayParams = array (0 => array('s' => 'Example string'), 1 => array('s' => 'Another string'), 2 => array('i' => 2), 3 => array('d' => 3.5) )
*/
public function executePrepared($sql, $arrayParams)
{
$statement = $this->prepareStatement($sql);
if ($statement) {
$this->bindParameter($statement, $arrayParams);
$this->executePreparedStatement($statement);
$result = $this->getArrayResultFromPreparedStatement($statement);
//only close if you are done with the statement
//$this->closePreparedStatement($statement);
} else {
$result = false;
}
return $result;
}
public function prepareStatement($sql)
{
$statement = $this->connection->prepare($sql) or $this->throwSqlError($this->connection->error);
return $statement;
}
public function bindParameter(&$statement, $arrayTypeValues)
{
$stringTypes = '';
$arrayParameters = array();
$arrayParameters[] = $stringTypes;
foreach ($arrayTypeValues as $currentTypeVale) {
foreach ($currentTypeVale as $type => $value) {
$stringTypes .= $type;
$arrayParameters[] = &$value;
}
}
$arrayParameters[0] = $stringTypes;
call_user_func_array(array($statement, "bind_param"), $arrayParameters);
}
public function getArrayResultFromPreparedStatement(&$statement)
{
$statement->store_result();
$variables = array();
$data = array();
$meta = $statement->result_metadata();
while($field = $meta->fetch_field())
$variables[] = &$data[$field->name]; // pass by reference
call_user_func_array(array($statement, 'bind_result'), $variables);
$i = 0;
$arrayResults = array();
while($statement->fetch())
{
$arrayResults[$i] = array();
foreach($data as $k=>$v)
{
$arrayResults[$i][$k] = $v;
}
$i++;
}
return $arrayResults;
}
public function executePreparedStatement($statement)
{
$result = $statement->execute() or $this->throwSqlError($statement->error);
return $result;
}
public function closePreparedStatement($statement)
{
$statement->close();
}
public function throwSqlError()
{ ... }
}
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>