I am new to OOP in PHP and i am trying to create a class, and then query the database. ATM the code looks like this and i am stuck in the query part. The query is ok, but it should use the class created. Can anyone help me please?
<?php
class Products {
//objekto kintamieji
public $category_id;
public $product_id;
public function __construct($category_id, $product_id){
$this->category_id = $category_id;
$this->product_id = $product_id;
}
public function query_the_database() {
if($xml->action == 'getProducts') {
$query = mysql_query("SELECT * FROM product WHERE category_id = 1 ORDER BY product_id");
while($row = mysql_fetch_object($query)){
$row->pvm = $row->price - round($row->price*100/121, 2);
$prod[] = $row;
}
}
}
}
You really should be using MySQLi or, even better, PDO on your class.
And, I highly recommend that you establish your connection in a separate class. So you have two pages: db.class.php and products.class.php.
Well, basic tutorial:
Establishing a connection:
$db=new PDO("mysql:host=HOST_NAME;port=PORT;dbname=DB_NAME");
Executing normal queries:
$db->execute("select * from table");
Executing queries with parameters (prepared statements):
$sql=$db->prepare("select * from table where param1=:p1 and param2=:p2");
$sql->bindParam(":p1", $p1); //bindParam only accepts variables
$sql->bindValue(":p2", "Value"); //bindValue only accepts raw values
$sql->execute();
Fetching values of prepared statements:
$array=$sql->fetchAll(); //that will be an array containing values in column names that are in row numbers. Like this: Array([0]=>Array([0]=>"value1" [column1]=>"value1") [1]=>Array([0]=>"value2" [column1]=>"value2"))
But please, go read about it since it will help you A LOT.
Related
Since a few weeks I use prepared statements in PHP with the fetch_object(className:: class). I really like this way because of the autocomplete in my controllers and in my view(Twig), but some times I need an inner join (One to many).
Now I do it like below. Luckily I have only a few results in the projects where I use this so the number of queries is low. But on a large result, this will create a lot of queries. To improve performance I store the $returnResult in apcu / Redis in the controller or save it in a JSON file when I can't use the other cache method.
My question is: can I do this on a better way to reduce the number of queries but still use the fetch_object(className:: class)
Thanks in advance for the help.
public function getAll()
{
// Create database connection
$db = DB::connect();
$stmt = $db->prepare("SELECT * FROM dataroom_category ORDER BY display_order");
$stmt->execute();
$returnResult = [];
$categoryResult = $stmt->get_result();
$stmt2 = $db->prepare("SELECT * FROM dataroom_file WHERE dataroom_category_id = ? ORDER BY display_order");
$stmt2->bind_param('i', $id);
/** #var data $category */
while ($category = $categoryResult->fetch_object(data::class)) {
$id = $category->getId();
$stmt2->execute();
$filesResult = $stmt2->get_result();
while ($file = $filesResult->fetch_object(DataroomFile::class)) {
// Add the file to the setFiles array with $file->getid() as key
$category->setFiles($file);
}
// I noticed by using mysqli_free_result the server used alot less memory at the end
mysqli_free_result($filesResult);
$returnResult[$category->getId()] = $category;
}
mysqli_free_result($categoryResult);
$stmt2->close();
$stmt->close();
// Return the categories with the files for usage in the controller and view
return $returnResult;
}
Im learning, and am still struggling to get the hang of many OOP concepts so please keep that in mind when reading / answering the question.
So one of the primary purposes of object orientated programming is not to repeat yourself right. However, when I am creating methods, I constantly find myself repeating the same statements when querying the database. As can be seen in the below code taken from class I created.
function getCategory()
{
$sql = "SELECT * FROM jobs";
$stmnt = $db->prepare($sql);
$stmnt->execute();
$results = $stmnt->fetchAll();
foreach ($results as $result) {
$cat[] = $result['category'];
}
return $this->category = $cat
}
function selectCategory($selectedCategory){
$sql = "SELECT * FROM jobs
WHERE category =:category";
$stmnt = $db->prepare($sql);
$stmnt->bindValue(':category', $selectedCategory);
$stmnt->execute();
$results = $stmnt->fetchAll();
foreach($results as $result){
$result= array('category' => $result['category'], 'headline' => $result['headline']);
}
return $this->category = $result
}// selectCategory
My question.
Is there a way / what should I do to avoid having to continuously write the same database queries in my methods? I feel im a little out of depth here, however its not going to stop me from trying. Any help, advice welcomed (please keep in mind im a beginner)
You can run the query to get all data, then extract the data from fetched data using PHP.
But I don't like it, and it is not efficient.
You have 2 different query , so you need to calls, just improve your code a little more, you can make a model like this:
class Category
{
private $db;
public function __construct(PDO $db)
{
$this->db = $db;
}
function getAll()
{
return $this->db->query('SELECT * FROM jobs');
}
function getByCategory($category){
$stmt = $this->db->prepare(
"SELECT * FROM jobs WHERE category =:category"
);
$stmt->bindValue(':category', $category);
$stmt->execute();
return $stmt->fetchAll();
}
}
This is perfectly fine, and it is not really repeating
Hi this is kind of an upgraded version of this question:
query mysql database from inside a class
The difference from the previous question, is i need a dynamic query not a static one or l$query = "SELECT col_1 FROM db.table"; So in order to have a dynamic query i need to use properties (or variables) so i can call different tables from that same class, or something like this "SELECT ‘$data’ FROM ‘$table’ ";
So far my class looks like this, similar to the previous question:
$mysqli = new mysqli("localhost", "root", "", "intranetpugle");
class crudmum {
private $table;
private $data;
private $mysqli;
function __construct($mysqli) {
$this->mysqli = $mysqli;
}
function runQuery($data2, $table2)
{
$this->table = $table2; $this->data = $data2;
$query = "SELECT '$this->data' FROM '$this->table' ";
$stmt = $this->mysqli->prepare($query);
$stmt->execute();
$stmt->bind_result($r);
while($stmt->fetch())
{
echo "<option>" . $r . "</option>";
}
}
};
This is how i run it:
$showme = new crudmum($mysqli);
$showme->runQuery("priority", "trackboards" );
Note: When i dont use variables or properties inside the query or somethng like this, SELECT priority FROM trackboards, the query does work, only when i input the properties or variables (like the given example) it does not work.
I get this error:
Fatal error: Call to a member function prepare() on a non-object in C:\xampp\htdocs\devserv\i+d\bootstrap\functions.php on line 76
Anyone see what am i doing wrong, of course there is a mistake with the database query any ideas on how to query the database right in a dynamic way within a class, sorry new with OOP with PHP!
found the mistake which was to add 'quotes' on the variables, like shown below:
$query = "SELECT '$this->data' FROM '$this->table' ";
The correct way would be to take out those 'quotes' on the variables or like this:
$query = "SELECT $this->data FROM $this->table ";
With that fix, the query runs just fine, guess i lacked attention to detail, thanx everyone for their help.
Ok, similar questions has been asked and answered before. However, I want to count prepared queries as well. I thought I could just use the prepare() function to increment the query count but that provided me some questionable results. Right now, it's telling me 10 queries are being executed... Generally I only use prepared statements unless the data is static or cannot be modified in anyway.
I found this code from another question that was identical to this. Except that the code only was counting queries that were executed using the query() and exec() functions. I tried to modify it but as I said before it isn't counting any prepared queries but the queries are still executed and return results...
class PDOEx extends PDO
{
private $queryCount = 0;
public function query($query)
{
++$this->queryCount;
return parent::query($query);
}
public function exec($statement)
{
++$this->queryCount;
return parent::exec($statement);
}
public function execute($args = null)
{
++$this->queryCount;
if (!is_array($args)) {
$args = func_get_args();
}
return parent::execute($args);
}
public function GetCount()
{
return $this->queryCount;
}
}
I just want to say thanks in advance. Please, if you can point me in the right direction it would be much appreciated, thanks!
The reason prepared queries aren't being counted is because it returns a PDOStatement, which is different than PDO. You could just ask the database how many queries were run on a given session, so as long as you don't keep create new \PDO objects then the result will be correct. Keep in mind even that query is counted as a query, so if you want to exclude it subtract 1 from the value.
Code
$db = new \PDO('mysql:host=127.0.0.1;dbname=sandbox', 'localuser', 'password');
$db->query('SELECT * FROM user WHERE id = 5');
$db->query('UPDATE user SET name = 'Demo' WHERE id = 5');
$db->query('DELETE FROM user WHERE id = 5');
echo $db->query('SHOW SESSION STATUS LIKE "Questions"')->fetchColumn(1);
Output
4
So i have a function thats supposed to handle all data execute operations: sql
function loadResult($sql)
{
$this->connect();
$sth = mysql_query($sql);
$rows = array();
while($r = mysql_fetch_object($sth)) {$rows[] = $r;}
$this->disconnect();
return $rows;
}
I want to convert it to pdo and this is what i have so far: pdo
function loadResult($sql)
{
$this->connect();
$sth = $this->con->prepare($sql);
//execute bind values here
$sth->execute();
$rows = array();
while ( $r = $sth->fetch(PDO::FETCH_OBJ) ) {$rows[] = $r;}
$this->disconnect();
return $rows;
}
Here is an example of a function on how am using it to view data from the database:
function viewtodolist()
{
$db=$this->getDbo(); //connect to database
$sql="SELECT * FROM mcms_todolist_tasks";
//maybe the bind values are pushed into an array and sent to the function below together with the sql statement
$rows=$db->loadResult($sql);
foreach($rows as $row){echo $row->title; //echo some data here }
}
I have just pulled out the important snippets so some variables and methods are from other php classes. Somehow, the mysql query works fine, but the PDO query is giving me headaches on how to include bindValue paremeters most probably in the viewtodolist() function to make it reusable. Any suggestions/recommendations are welcome.
Since your existing function accepts a fully-formed SQL string, with no placeholders, you don't need to use prepare + bind. Your code as written should work fine, or you could use PDO::query() to execute the SQL in one step.
If you want to use parameterised queries, then your loadResult function is going to have to change a bit, as is the way you write your SQL. The example SQL you give doesn't actually have anything in that could be turned into a parameter (column names and table names can't be parameters as discussed here), but I'll use an imaginary variation:
// Get the todo tasks for a particular user; the actual user ID is a parameter of the SQL
$sql = "SELECT * FROM mcms_todolist_tasks WHERE user_id = :current_user_id";
// Execute that SQL, with the :current_user_id parameter pulled from user input
$rows = $db->loadResult($sql, array(':current_user_id' => $_GET['user']));
This is a nice secure way of putting the user input into the query, as MySQL knows which parts are parameters and which are part of the SQL itself, and the SQL part has no variables that anyone can interfere with.
The simplest way of making this work with your existing loadResult function would be something like this:
// Function now takes an optional second argument
// if not passed, it will default to an empty array, so existing code won't cause errors
function loadResult($sql, $params=array())
{
$this->connect();
$sth = $this->con->prepare($sql);
// pass the parameters straight to the execute call
$sth->execute($params);
// rest of function remains the same...
There are cleverer things you can do with parameterised queries - e.g. binding variables to output parameters, preparing a query once and executing it multiple times with different parameters - but those will require more changes to the way your calling code works.