How do you consolidate repeated code within functions? - php

I tried to create a class to consolidate the following functions but I don't fully understand the approach, how would I approach the following functions to remove the need to query the DB on each occasion an just call the separate echo blocks?
function get_pages_new() {
$cxn = mysqli_connect('localhost', 'root', '', 'northern') or die(mysqli_error($cxn));
$query = ("SELECT * FROM `pages` ORDER BY `page_id` ASC") or die(mysqli_error($cxn));
$getnews = mysqli_query($cxn, $query);
while ($row = mysqli_fetch_assoc($getnews)) {
$page_id = $row['page_id'];
$page_title = $row['page_title'];
$admin = $row['admin_only'];
echo "<li>$page_title</li>";
}
};
function get_pages_edit() {
$cxn = mysqli_connect('localhost', 'root', '', 'northern') or die(mysqli_error($cxn));
$query = ("SELECT * FROM `pages` ORDER BY `page_id` ASC") or die(mysqli_error($cxn));
$getnews = mysqli_query($cxn, $query);
while ($row = mysqli_fetch_assoc($getnews)) {
$page_id = $row['page_id'];
$page_title = $row['page_title'];
$admin = $row['admin_only'];
echo "<li>$page_title</li> ";
}
};
function get_pages_delete() {
$cxn = mysqli_connect('localhost', 'root', '', 'northern') or die(mysqli_error($cxn));
$query = ("SELECT * FROM `pages` ORDER BY `page_id` ASC") or die(mysqli_error($cxn));
$getnews = mysqli_query($cxn, $query);
while ($row = mysqli_fetch_assoc($getnews)) {
$page_id = $row['page_id'];
$page_title = $row['page_title'];
$admin = $row['admin_only'];
echo "<li>$page_title</li>";
}
};
Thanks

Pass in a parameter that contains the link:
function get_pages($link) {
$cxn = mysqli_connect('localhost', 'root', '', 'northern') or die(mysqli_error($cxn));
$query = ("SELECT * FROM `pages` ORDER BY `page_id` ASC") or die(mysqli_error($cxn));
$getnews = mysqli_query($cxn, $query);
while ($row = mysqli_fetch_assoc($getnews)) {
$page_id = $row['page_id'];
$page_title = $row['page_title'];
$admin = $row['admin_only'];
echo "<li><a href='".$link."?page_id=".$page_id."'>".$page_title."</li></a>";
}
};
Where $link is add_page.php, edit_page.php or remove_page.php. Unless I've misread your code and each function is running a seperate query, this should work :)

$Create a method for that instead of a class:
function extractIdTitleAdminFromEntry($entry) {
return [
'page_id' => $entry['page_id'],
'page_title' => $entry['page_title'],
'admin_only' => $entry['admin_only'],
];
}
Now you can do this inside your while loops:
list($page_id, $page_title, $admin_only) = extractIdTitleAdminFromEntry($row);
You can even modify it such that the list of properties is dynamic:
function extractIdTitleAdminFromEntry($entry, $properties) {
$values = [$key];
foreach ($properties as $key) {
$values[$key] = isset($entry[$key] ? $entry[$key] : null;
}
return $values;
}
list($page_id, $page_title, $admin_only) = extractIdTitleAdminFromEntry(
$row,
['page_id', 'page_title', 'admin_only']
);

Related

PHP Slim: multiple functions in one file cause errors

I am fairly new to PHP slim but it's working great for me actually. But I have a problem that I think is really strange! I have a PHP file with all my API functions to get or edit data in my database. Each of these functions works great seperatly but when I uncomment them all and they are all active I get a 404 error when I want to use them or when I surf directly to them in my browser.
Here you can see all the functions I want to use:
//PHPSLIM
require '.././libs/Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$categories = new \Slim\Slim();
$categories = \Slim\Slim::getInstance();
$categories->get('/categories', function(){
global $conn, $servername, $username, $password, $dbname;
mysql_connect($servername, $username, $password);
mysql_select_db($dbname);
$result = mysql_query("SELECT `categoryID`, `categoryName` FROM `category`");
while($line = mysql_fetch_array($result, MYSQL_NUM)) {
$cat[] = $line;
}
echoResponseCat(200, $cat);
});
function echoResponseCat($status_code, $response) {
global $categories;
$categories->status($status_code);
header('Content-Type: application/json');
$categories->contentType('application/json');
echo json_encode($response,JSON_NUMERIC_CHECK);
}
$categories->run();
//ALTER ORDER STATUS
$status = new \Slim\Slim();
$status = \Slim\Slim::getInstance();
$status->get('/orderPrepared/:orderID', function ($orderID) {
global $conn, $servername, $username, $password, $dbname;
if(isset($orderID)){
$sql = "UPDATE `order` SET `orderStatus`= 'done' WHERE `orderID` = '$orderID'";
mysql_connect($servername, $username, $password);
mysql_select_db($dbname);
$result = $conn->query($sql);
}
});
$status->run();
$app = new \Slim\Slim();
$app = \Slim\Slim::getInstance();
//GET ALL ORDERS
$app->get('/orders', function(){
$extranames = "";
$extrasprice = 0;
global $conn, $servername, $username, $password, $dbname;
$sql = "SELECT `orderID`, `customerID`, `storeID`, `orderDate`, `orderDeliveryDate`, `orderStatus` FROM `order`";
mysql_connect($servername, $username, $password);
mysql_select_db($dbname);
$query = mysql_query("SELECT `orderID`, `customerID`, `orderDate`, `orderDeliveryDate`, `orderStatus` FROM `order`");
$ordersall = array();
while($line = mysql_fetch_array($query, MYSQL_ASSOC)){
$orders[] = $line;
}
$count = 0;
$extrasprice = 0;
$ordersall = array();
$orderKeys = array('orderID', 'customerID', 'customerName', 'orderDate', 'orderDeliveryDate', 'orderStatus');
$orderKeys = array_combine($orderKeys, $orderKeys);
foreach($orders as $key => $looporders){
$extracounter = 1;
$sql = "SELECT `orderdetailID`, `productID`, `orderdetailAantal` FROM `orderdetail` WHERE `orderID` = '$looporders[orderID]'";
$result = $conn->query($sql);
//echo("orderID " . $looporders["orderID"] . " " . $result->num_rows ."/");
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$sql2 = "SELECT `productTitle`, `productPrijs` FROM `products` WHERE `productID` = '$row[productID]'";
$result2 = $conn->query($sql2);
if($result2->num_rows > 0) {
while($row2 = $result2->fetch_assoc()){
$productTitle = $row2["productTitle"];
$productPrijs = $row2["productPrijs"];
}
}
$sql3 = "SELECT `customerName` FROM `customers` WHERE `customerID` = '$looporders[customerID]'";
$result3 = $conn->query($sql3);
if($result3->num_rows > 0) {
while($row3 = $result3->fetch_assoc()){
$customerName = $row3["customerName"];
}
}
$sql4 = "SELECT `extraID` FROM `orderdetailextra` WHERE `orderdetailID` = '$row[orderdetailID]'";
$result4 = $conn->query($sql4);
if ($result4->num_rows > 0) {
while($row4 = $result4->fetch_assoc()) {
$sql5 = "SELECT `extraName`, `extraPrice` FROM `extra` WHERE `extraID` = '$row4[extraID]'";
$result5 = $conn->query($sql5);
if ($result5->num_rows > 0) {
while($row5 = $result5->fetch_assoc()) {
$extranames = $extranames . $row5["extraName"]. ', ';
$extrasprice += $row5["extraPrice"];
}
}
}
}
$orderID = $looporders["orderID"];
if(!isset($ordersall[$orderID])){
$ordersall[$orderID] = array_intersect_key($looporders,$orderKeys);
$ordersall[$orderID]["customerName"] = $customerName;
$ordersall[$orderID]['details'] = array();
$newdata = array(
"orderdetailID" => $row["orderdetailID"],
"productTitle" => $productTitle,
"productPrijs" => $productPrijs,
"aantal" => $row["orderdetailAantal"],
"extras" => substr($extranames, 0, -2),
"extrasPrice" => $extrasprice
);
array_push($ordersall[$orderID]['details'], $newdata);
}
else if(isset($ordersall[$orderID])){
$newdata = array(
"orderdetailID" => $row["orderdetailID"],
"productTitle" => $productTitle,
"productPrijs" => $productPrijs,
"aantal" => $row["orderdetailAantal"],
"extras" => substr($extranames, 0, -2),
"extrasPrice" => $extrasprice
);
array_push($ordersall[$orderID]['details'], $newdata);
}
$count++;
$extranames ="";
$extrasprice = 0;
}
}
}
echoResponse(200, $ordersall);
});
$app->run();
//GET ALL ORDERS FOR 1 CUSTOMER
$app->get('/orderoverview/:customerID', function ($customerID) {
global $conn, $servername, $username, $password, $dbname;
//1.1 GET ORDER (ID) AND NAME OF CUSTOMER
$sql = "SELECT `customerName` FROM `customers` WHERE `customerID` = $customerID";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$customername = $row["customerName"];
}
}
else {
echo "Customer name failure";
}
$sql = "SELECT `orderID` FROM `order` WHERE `customerID` = $customerID";
$result = $conn->query($sql);
if($result->num_rows > 1){
echo "You already have a pending order! <br>";
}
else if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$orderID = $row["orderID"];
}
step2($orderID, $customername);
} else {
echo "GET orderID failure";
}
});
$app->run();
Can someone tell me what I'm doing wrong?
You are calling run after each controller. But you only need to do this once. For your whole application
$app = new \Slim\Slim();
$app->get('/orderPrepared/:orderID', function ($orderID) {
});
.. assign all your controllers ..
$app->run();

select query through function.. to fetch data from db

How do I fetch data from db using select query in a function?
Example
function ec_select_query($student, $row = '', $fields=array()) {
$qry = "SELECT * FROM student";
$qry = mysql_query($qry);
while($row = mysql_fetch_assoc($qry)){}
return $row;
}
If you want to return all rows then first save it in an array in while loop then return this array.
function ec_select_query($student,$row='',$fields=array())
{
$qry = "SELECT * FROM student";
$qry = mysql_query($qry);
$result = array();
while($row = mysql_fetch_assoc($qry))
{
$result[] = $row;
}
return $result;
}
Its is running code. Modify it according to your needs
$con = mysql_connect('localhost','root','') or die("Unable to connect to MySQL");
mysql_select_db('demo', $con) or die("Database not found");
function ec_select_query($student)
{
$query = "SELECT * FROM $student";
$result = mysql_query($query);
$row = array();
$getData = array();
while($row = mysql_fetch_array($result))
{
$getData[]=$row;
}
return $getData;
}
$information = ec_select_query('accountplans');
echo "<pre>"; print_r($information); die;
Try it
function select_query($table, $where=array(),$fields=array()){
$select_fields = $table."*";
if(!empty($fields) && is_array($fields)){
$select_fields = implode(",", $fields);
}
$sql = "select ".$select_fields." from ".$table." where 1=1 ";
if(!empty($where) && is_array($where)){
foreach ($where as $key => $value) {
$sql .= " AND ".$value;
}
}
$query = mysql_query($sql);
$result = array();
while($row = mysql_fetch_assoc($result)){
$result[] = $row;
}
return $result;
}
Call Function
$fields = array("id","name","city");
$where = array('name = "abc"','city like "aaa"');
$students = select_query("studendts", $where, $fields);
This code might help you :
function ec_select_query($student,$row='',$fields=array())
{
$q = "SELECT * FROM student";
$q = mysql_query($qry);
while($row = mysql_fetch_array($qry))
{
return $row;
}
}
It is easiest way to produce entire data in array
function db_set_recordset($sql) {
$qry = mysql_query($sql);
$row= array();
while($out = mysql_fetch_assoc($qry)) {
$row[] = $out;
}
return $row;
}
$qry = "SELECT * FROM student";
$result = db_set_recordset($qry);

How to return a multidimensional array keys as a tree?

I am working on an MLM application in which i need to show all users as a tree. For this is implemented parent child relationship among the users. my table structure is here :-
I had retrieve the id's of users in a multidimensional array as per the relation. Here is array:-
For this i used this code :-
<?php
$con = mysql_connect('localhost', 'root', '');
mysql_select_db('testapp', $con);
function create_tree( $parent_id = 0 )
{
$result_array = array();
$Query = 'SELECT * FROM `user` WHERE `parent`=\''.$parent_id.'\';';
$query_result = mysql_query($Query);
if(mysql_num_rows($query_result)>0)
{
while($row = mysql_fetch_assoc($query_result))
{
if(!array_key_exists($row['user_id'], $result_array))
{
//$result_array[$row['user_id']] = $row;
$result_array[$row['user_id']] = create_tree($row['user_id']);
}
}
}
return $result_array;
}
$tree = create_tree();
print_r($tree);
Now, i need to show the data in a tree structure like :-
Any hint will be helpful. I am very near to complete this...
Yes, you are so near..!!
Try below it will be work for you..
<?php
$con = mysql_connect('localhost', 'root', '');
mysql_select_db('testapp', $con);
function create_tree( $parent_id = 0 ,$result_array = array())
{
$Query = 'SELECT * FROM `user` WHERE `parent`=\''.$parent_id.'\';';
$query_result = mysql_query($Query);
if(mysql_num_rows($query_result)>0)
{
while($row = mysql_fetch_assoc($query_result))
{
if(!array_key_exists($row['user_id'], $result_array))
{
//$result_array[$row['user_id']] = $row;
$result_array[$row['user_id']] = create_tree($row['user_id'],$result_array);
}
}
}
return $result_array;
}
$tree = create_tree();
print_r($tree);
?>
If this will not work for you than let me know..!!
Thanks..
try that, it should give you the structure;
function create_tree( $parent_id = 0 , $result_array = array() )
{
//$result_array = array();
$Query = 'SELECT * FROM `user` WHERE `parent`=\''.$parent_id.'\';';
$query_result = mysql_query($Query);
if(mysql_num_rows($query_result)>0)
{
while($row = mysql_fetch_assoc($query_result))
{
if(!array_key_exists($row['user_id'], $result_array))
{
//$result_array[$row['user_id']] = $row;
$result_array[$row['user_id']] = create_tree($row['user_id'], $result_array[$row['user_id']]);
}
}
}
return $result_array;
}
edit; forgot the remove result_array in function

Using recurssion in deleting parent and child relationship in mysql table

I'm having trouble getting this function work. This is my database design
I'm working in an application wherein when a user deletes a parent category, all the subcategory would also be deleted, and so on and so fort..
For example:
When the user clicks on the "Test1" category in my application, the "Test1.1" and "Test1.1.1" would be deleted since it is under the "Test1" category.
This is my database design(above).
This is the code that I wrote:
function DeleteProjectPhotos( $cat_id ) {
$sql = "SELECT * FROM project_category WHERE category_id = '$cat_id'";
$query = mysql_query( $sql ) or die( mysql_error() );
if( mysql_num_rows( $query ) > 0 ) {
$sql = "SELECT * FROM project_category WHERE parent_id = '$cat_id'";
$query = mysql_query( $sql ) or die( mysql_error() );
if( mysql_num_rows( $query ) > 0 ) {
while( $row = mysql_fetch_assoc( $query ) ) {
$this->DeleteProjectPhotos( $row['category_id'] );
}
} else {
$sql = "DELETE FROM project_category WHERE category_id = '$cat_id'";
$query = mysql_query( $sql ) or die( mysql_error() );
}
}
}
But I think the whole logic here is wrong because when I try to delete the category_id 33, everything won't be deleted. Kindly teach me how to do this one.
Your help would be greatly appreciated and rewarded!
Thanks! :)
<?php
$catID = $_GET['catID'];
deleteCategory($catID);
function connect(){
$host = 'localhost';
$dbName = 'sony';
$userName = 'root';
$password = '';
$conn = new PDO("mysql:host=$host;dbname=$dbName",$userName,$password);
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
return $conn;
}
$stmt = '';
function deleteCategory($catID){
$conn = connect();
$tableName = 'childparent';
$sql = "select catID from $tableName where parentID = :catID";
global $stmt;
$stmt = $conn->prepare($sql);
$idsToDelete = getChilds($catID);
$idsToDelete[] = $catID;
//print_r($idsToDelete);
$delExp = '';
foreach($idsToDelete as $id)
$delExp .= " catID=$id or";
$delExp = preg_replace('/or$/','',$delExp);
if($delExp != ''){
$delSql = "delete from $tableName where $delExp";
//echo $delSql;
$delStmt = $conn->prepare($delSql);
$delStmt->execute();
}
}
$collectedIDs = array();
function getChilds($catID){
global $stmt,$collectedIDs;
$stmt->bindValue(':catID',$catID);
$stmt->execute();
$childCatIDs = array();
while($row = $stmt->fetch(pdo::FETCH_ASSOC)){
$childCatIDs[] = $row['catID'];
$collectedIDs[] = $row['catID'];
}
//print_r($childCatIDs);
//die();
if(!empty($childCatIDs)){
foreach($childCatIDs as $cid)
getChilds($cid);
}
return $collectedIDs;
}
?>
If you don't want triggers you can try http://php.net/manual/en/function.mysql-affected-rows.php on delete category you get it`s id and while there is a return you try to delete by cathegory or by parent

How do I pass more than one variable via URL in php?

I am trying to pass multiple variables in a URL in PHP to GET some info, but I don't think it's working.
$allowedFunctions = array(
'returnAllProducts',
'refreshCurrentProduct'
);
$IDNUM = $_GET[ 'idNum' ];
$functionName = $_GET[ 'func' ];
if( in_array( $functionName, $allowedFunctions ) && function_exists( $functionName ) )
{
$functionName();
}
Then I have the refreshCurrentProduct function:
function refreshCurrentProduct() {
$dbh=mysql_connect ("DATABASE","USER", "PASS") or die('I cannot connect to the database because:'. mysql_error());
mysql_select_db("TABLE");
$query = "SELECT `ID` FROM `PRODUCTS`";
$result = mysql_query($query) or die('Query failed:'.mysql_error());
$DB_STOCK = mysql_query("SELECT `STOCK` FROM `PRODUCTS`") or die('Query failed:'.mysql_error());
$DB_SHORT = mysql_query("SELECT `MYNAME` FROM `PRODUCTS`") or die('Query failed:'.mysql_error());
$DB_LONG = mysql_query("SELECT `DESCRIPTION` FROM `PRODUCTS`") or die('Query failed:'.mysql_error());
$DB_PRICE = mysql_query("SELECT `PRICE` FROM `PRODUCTS`") or die('Query failed:'.mysql_error());
$DB_SHIP = mysql_query("SELECT `SHIPPING` FROM `PRODUCTS`") or die('Query failed:'.mysql_error());
$ID = mysql_result($result,$IDNUM,"ID");
$STOCK = mysql_result($DB_STOCK,$IDNUM,"STOCK");
$SHORT = mysql_result($DB_SHORT,$IDNUM,"MYNAME");
$LONG = mysql_result($DB_LONG,$IDNUM,"DESCRIPTION");
$PRICE = mysql_result($DB_PRICE,$IDNUM,"PRICE");
$SHIP = mysql_result($DB_SHIP,$IDNUM,"SHIPPING");
echo '
//echo $STOCK, $SHORT, etc....
';
}
The URL I am using is products.php?func=refreshCurrentProduct&idNum=4
In theory, that should display from the row with 4 in it, however, it only displays the info from the first row. If I do a $IDNUM=5 within the function, it will display the 5th row, so something is wrong with how I pass the information.
Also, how do I create (for instance) $STOCK without having to have so much code in $DB_STOCK? Seems like there has to be a better way...
Why don't you do (as others already mentioned , $IDNUM is not in the scope of the function):
function refreshCurrentProduct() {
$dbh=mysql_connect ("DATABASE","USER", "PASS") or die('I cannot connect to the database because:'. mysql_error());
mysql_select_db("TABLE");
// If $_GET['idNum'] is not a number use 0
$rowNumber = is_numeric($_GET['idNum']) ? $_GET['idNum'] : 0;
$query = "SELECT ID, STOCK, MYNAME, DESCRIPTION, PRICE, SHIPPING FROM `PRODUCTS`";
$result = mysql_query($query);
if(mysql_data_seek($result, $rowNumber)) {
// The result set has indeed at least $rowNumber rows
$row = mysql_fetch_assoc($result);
echo $row['ID'];
echo $row['STOCK'];
// ... etc ....
}
else {
echo "No such row!";
}
}
No need to hit the database six times! Of course you need to add error handling.
Btw. is the parameter idNum the same as the ID of the record in the database? If so, you can even further simplify:
function refreshCurrentProduct() {
$dbh=mysql_connect ("DATABASE","USER", "PASS") or die('I cannot connect to the database because:'. mysql_error());
mysql_select_db("TABLE");
// If $_GET['idNum'] is not a number use 0
$id = is_numeric($_GET['idNum']) ? $_GET['idNum'] : 0;
$query = "SELECT ID, STOCK, MYNAME, DESCRIPTION, PRICE, SHIPPING FROM `PRODUCTS` WHERE ID = $id";
$result = mysql_query($query);
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print";
return;
}
$row = mysql_fetch_assoc($result);
echo $row['ID'];
echo $row['STOCK'];
// ... etc ....
}
Take a look at call_user_func.
$functionName = $_GET[ 'func' ];
if( in_array( $functionName, $allowedFunctions ) && function_exists( $functionName ) )
{
call_user_func($functionName);
}
Also, if I'm reading your code right, you could get all of the info in a single query:
$query = "SELECT `ID`,`STOCK`,`MYNAME`,`DESCRIPTION`,`PRICE`,`SHIPPING` FROM `PRODUCTS`";
$result = mysql_query($query) or die('Query failed:'.mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$ID=$row['ID'];
//etc.
}
Your $IDNUM variable is outside the scope of your function. You either need to pass that into your function as a variable or you should be able to set it within the function by setting it inside.
function refreshCurrentProduct() {
$IDNUM = $_GET[ 'idNum' ];
...
}

Categories