Using recurssion in deleting parent and child relationship in mysql table - php

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

Related

SQLSRV bind param thats in mysql

I'm trying to convert this mysql code to work using sqlsrv
$planeId = $_GET["pid"];
$conn = OpenCon();
$sql = "SELECT id, pid, fullname, tat, date, engine1, engine2, engine3, engine4 FROM oil WHERE pid = ? order by date desc";
$stmnt = $conn->prepare($sql);
$stmnt->bind_param("s", $planeId);
$stmnt->bind_result($id, $pid, $fullname, $tat, $date, $engine1, $engine2, $engine3, $engine4);
$stmnt->execute();
$theRows = Array();
while ( $stmnt->fetch() )
{
$aRow['id'] = "$id";
$aRow['pid'] = "$pid";
$aRow['fullname'] = $fullname;
$aRow['tat'] = $tat;
$aRow['date'] = $date;
$aRow['engine1'] = $engine1;
$aRow['engine2'] = $engine2;
$aRow['engine3'] = $engine3;
$aRow['engine4'] = $engine4;
$theRows[] = $aRow;
}
$stmnt->close();
echo json_encode($theRows);
CloseCon($conn);
This I what I've done so far but I'm missing the bind-param function not sure how to implement that. Because the output keeps coming out like this
[{"id":"","pid":"","fullname":null,"tat":null,"date":null,"engine1":null,"engine2":null,"engine3":null,"engine4":null}]
Even though I know there's an entry in Microsoft DB
$planeId = $_GET["pid"];
$theRows = Array();
$conn = OpenCon();
$query = "SELECT id, pid, fullname, tat, date, engine1, engine2, engine3, engine4 FROM oil WHERE pid = ? order by date desc";
//$stmnt = $conn->prepare($query);
$stmnt = sqlsrv_prepare($conn, $query, array(&$planeId));
if (sqlsrv_execute($stmnt) === false){
die( print_r( sqlsrv_errors(), true));
}
else{
while ( sqlsrv_fetch($stmnt) )
{
$aRow['id'] = "$id";
$aRow['pid'] = "$pid";
$aRow['fullname'] = $fullname;
$aRow['tat'] = $tat;
$aRow['date'] = $date;
$aRow['engine1'] = $engine1;
$aRow['engine2'] = $engine2;
$aRow['engine3'] = $engine3;
$aRow['engine4'] = $engine4;
$theRows[] = $aRow;
}
echo json_encode($theRows);
}
CloseCon($conn);

Comparison for in SQL row selection not working?

This is the code that is not working:
$query = "SELECT * FROM $table WHERE text_id > '$last_id'"; //SELECT NEW MESSAGES
$result = mysqli_query($connection,$query);
if ($result && mysqli_num_rows($result) > 0)
{
//THIS SHOULD NOT BE RUNNING
}
I've verified over and over in phpMyAdmin and the text_id in the table and $last_id are both the integer value '1'. That being said, the condition equates to true every time the code runs.
Am I messing this code up, or is my thinking improper?
Here is entire script:
<?php
session_start();
$alias = $_SESSION['username'];
$host = 'localhost';
$user = '*';
$pass = '*';
$database = 'vethergen_db_accounts';
$table = 'table_messages';
$last_id_table = 'table_chat_sync';
$connection = mysqli_connect($host, $user, $pass) or die ("Unable to connect!");
mysqli_select_db($connection,$database) or die ("Unable to select database!");
$last_id_query = "SELECT alias FROM $last_id_table WHERE alias = '$alias'";
$last_id_result = mysqli_query($connection,$last_id_query);
$last_id_rows = mysqli_fetch_array($last_id_result);
if ($last_id_rows['alias'] === $alias)
{
$last_id = $last_id_rows['last_id'];
$query = "SELECT * FROM $table WHERE text_id > '$last_id'"; //SELECT NEW MESSAGES
$result = mysqli_query($connection,$query);
if ($result && mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
if ($row['alias'] === "Vether")
{
echo '<p id = "chat_text">'.'<b>'.$row['alias'].'</b>'.': '.$row['text']."</p>";
echo '<p id = "time_stamp">'.$row['time'].'</p>';
echo '<p id = "chat_number">'.$row['text_id'].'</p>';
}
else
{
echo '<p id = "chat_text">'.'<b class = "bold_green">'.$row['alias'].'</b>'.': '.$row['text']."</p>";
echo '<p id = "time_stamp">'.$row['time'].'</p>';
echo '<p id = "chat_number">'.$row['text_id'].'</p>';
}
echo '<hr class = "chat_line"></hr>';
$last_row_id = $row['text_id'];
}
}
//UPDATE LAST SYNC ID
$update_query = "UPDATE $last_id_table SET last_id = '$last_row_id' WHERE alias = '$alias'";
mysqli_query($connection,$update_query);
}
else
{
$update_query = "INSERT INTO $last_id_table (alias, last_id) VALUES('$alias','-1')";
mysqli_query($connection,$update_query);
}
?>
You should change ;
WHERE text_id > '$last_id'
to
WHERE text_id > $last_id
text_id column is integer and can't be compared like string.

PHP PDO for getting MySQL fileds name

I have a function from class that gets data from MySQL. All works OK but I also want to know how I can get the column names for MySQL data.
Here is my code :
public static function getTickets(){
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "select tickets.*,customers.* from tickets,customers where
(tickets.ticket_customer_id = customers.customer_id) order by tickets.ticket_open_date desc ";
$st = $conn->prepare($sql);
$st->execute();
$list = array();
while($row=$st->fetch()) {
$tickets = New Tickets($row);
$list[] = $tickets;
}
//total rows of customer
$sql = "select FOUND_ROWS() as totalRows";
$totalRows = $conn->query($sql)->fetch();
$conn=null;
$columnCount = $st->columnCount();
//pass the values to page
return (array("results"=>$list ,"totalRows"=>$totalRows,"columnCount"=>$columnCount));
}
It's hard to tell what you need here, but looking at your code I would say that everything you need you can get from the very data you are fetching
public static function getTickets($conn){
$sql = "select tickets.*,customers.* from tickets,customers where
(tickets.ticket_customer_id = customers.customer_id) order by tickets.ticket_open_date desc ";
$st = $conn->query($sql);
$list = array();
while($row=$st->fetch(PDO::FETCH_ASSOC)) {
$list[] = New Tickets($row);
$columnNames = array_keys($row);
}
//total rows of customer
$totalRows = count($list);
$columnCount = count($columnNames);
//pass the values to page
return (array("results"=>$list ,"totalRows"=>$totalRows,"columnCount"=>$columnCount));
}

Computing sum of 2 fields in a table using MySQL fetch function in PHP

I have a table having the following fields: id(Autoincrement/Primary Key)/Integer1/Integer2/Sum/Product). I have filled integer1 and integer2 with the following code:
for ($i=1;$i<=1000;$i++)
{
$x2=rand(0,100);
$x3=rand(0,100);
$sql="INSERT INTO data(integer1,integer2) VALUES ($x2,$x3)";
$conn->query($sql);
}
I need help to prepare a function which uses MySQLFetch and computes sum of integer1 and integer2 and assigns the value in sum and product. I know it can be done using a simple loop, but would really like to get an understanding of fetching data.
Assuming you are using mysqli which is how it appears with the use of $conn->query() then this might be of interest.
/* establish db connection */
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'xxx';
$conn = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
/* select records to to perform sum & product upon */
$sql='select * from `data`';
$res=$conn->query( $sql );
if( $res ){
/* prepare a new sql statement to update db records */
$sql='update `data` set `sum`=?, `product`=? where `id`=?;';
$stmt=$conn->prepare( $sql );
while( $rs=$res->fetch_object() ){
/* make some variables with records for each record */
$id=$rs->id;
$int_1=$rs->integer1;
$int_2=$rs->integer2;
/* basic maths operations */
$sum=$int_1+$int_2;
$product=$int_1 * $int_2;
/* bind the variables into declared statement & execute */
$stmt->bind_param( 'iii', $sum, $product, $id );
$stmt->execute();
}
/* tidy up */
$stmt->close();
$conn->close();
}
Kindly try the following example :
$db = new mysqli('localhost', 'root', 123456, 'data');
$query = 'SELCT * FROM tableName';
$objResult = $db->query($query);
while ($resultRow = $objResult->fetch_object()) {
$id = $resultRow->id;
$integer1 = $resultRow->integer1;
$integer2 = $resultRow->integer2;
$result = sumProduct($integer1, $integer2);
$sum = $result[0];
$product = $result[1];
$query = "UPDATE tableName SET
sum = '$sum',
product = '$product'
WHERE
id = $id";
$db->query($query);
$db->close();
}
function sumProduct($int1, $int2) {
$sum = $int1 + $int2;
$product = $int1 * $int2;
return array($sum, $product);
}
Is this way you expected?
$query = "SELECT * FROM data";
$row = mysql_query($query);
while($result = mysql_fetch_assoc($row))
{
$id = $result['id'];
$integer1 = $result['integer1'];
$integer2 = $result['integer2'];
$sum = $integer1 + $integer2;
$prod = $integer1 * $integer2;
mysql_query("UPDATE data SET sum=$sum,product=$prod WHERE id=$id");
}

Error with fetch() method

I am getting the error statement:
Call to a member function fetch() on a non-object in /home/content/26/11794426/html/practice/home.php on line 16
Based off this, I believe that the mysql query isn't making an object. However, I am copying my code directly from a book so I am confused why I'm getting an error. Is it the fetch() part itself or the query?
Also, the database I copied and pasted the sql query into the phpmyadmin so I don't think there is an error there, but I'm not ruling it out.
Any ideas?
<?php
require_once('database.php');
// Get category ID
if(!isset($category_id)) {
$category_id = $_GET['category_id'];
if (!isset($category_id)) {
$category_id = 1;
}
}
// Get name for current category
$query = "SELECT * FROM categories
WHERE categoryID = $category_id";
$category = $db->query($query);
$category = $category->fetch();
$category_name = $category['categoryName'];
// Get all categories
$query = 'SELECT * FROM categories
ORDER BY categoryID';
$categories = $db->query($query);
// Get products for selected category
$query = "SELECT * FROM products
WHERE categoryID = $category_id
ORDER BY productID";
$products = $db->query($query);
?>
this is what my database.php file looks like:
<?php
$dsn = 'mysql:host=guitarshop27.db.11794426.hostedresource.com;dbname = guitarshop27';
$username = 'changed';
$password = 'changed';
try {
$db = new PDO($dsn, $username, $password);
}catch (PDOException $e) {
$error_message = $e->getMessage();
include('database_error.php');
exit();
}
?>
$category = $db->query($query);
$categorys = $category->fetch();
$category_name = $categorys['categoryName'];
You can try it with fetch_assoc();
$query = "SELECT * FROM categories
WHERE categoryID = $category_id";
$category = $db->query($query);
$category = $category->fetch_assoc();
$category_name = $category['categoryName'];
But the problem is the database conection. Where is it defined?
Try to debug your Code and also add this add this Code
// Get name for current category
$query = "SELECT * FROM categories
WHERE categoryID = $category_id";
$category = $db->query($query);
echo mysql_nun_rows($category);
$categories = $category->fetch();
$category_name = $categories['categoryName'];
if you find still error then check your database connection

Categories