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
Related
When I enter category name manually, I'm able to get its product but when I insert a variable to like the code, I get success but data is empty.
Connection file:
<?php
//cnnection.php
$server = "localhost";
$user = "root";
$password = "";
$db = "db_ecommerce_shoes";
$connect = new mysqli($server,$user,$password,$db);
Main script:
<?php
include '../connection.php';
With this, request is successful but data is empty
$name= 'name';
$sql = "SELECT * FROM tb_shoes
WHERE
catName ='$name'
";
With this, request is successful, data is loaded successful
$sql = "SELECT * FROM tb_shoes
WHERE
catName ='Ladies Shoe'
";
$result = $connect->query($sql);
if($result) {
$data = array();
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
echo json_encode(array(
"success"=>true,
"data"=> $data,
));
} else {
echo json_encode(array(
"success"=>false,
));
}
Any other way of doing this will be much appreciated.
Any other way of doing this will be much appreciated
You should never be directly concatenating variables into the SQL query making it vulnerable to SQL injections. That is a major security issue.
Read about a simple and easy to understand version of prepared statements here.
In your case, try this out
$category = "Ladies Shoe"
$statement = $connect->prepare("SELECT * FROM tb_shoes WHERE catName = ? ")
$statement ->bind_param("s", $category);
$statement ->execute();
$result = $statement ->get_result();
Then you can loop through the results as above. Check if it works!
Try to assign
$name = 'Ladies Shoe';
$sql = "SELECT * FROM tb_shoes
WHERE
catName ='$name'
";
Does this work?
I am trying to convert mysqli code to PDO way but I run into an issue.
It should behave: If deleted main parent delete his sub categories also, so that there are no "orphans" left in database.
The main parents are parent 0 in database, while sub categories are linked with parents ID.
This is working mysqli example :
// Delete
if(isset($_GET['delete']) && !empty($_GET['delete'])) {
$delete_id = (int)$_GET['delete'];
$delete_id = sanitize($delete_id);
/* Deleting a parent and its children to avoid orphaned categories in the database. */
$result = $db->query("SELECT * FROM categories WHERE id = '{$delete_id}'");
$category = mysqli_fetch_assoc($result);
if($category['parent'] == 0) {
$db->query("DELETE FROM categories WHERE parent = '{$delete_id}'");
header("Location: categories.php");
}
$db->query("DELETE FROM categories WHERE id = '{$delete_id}'");
header("Location: categories.php");
}
What I have tried with PDO way:
//delete Category
if(isset($_GET['delete']) && !empty($_GET['delete'])){
$delete_id = (int)$_GET['delete'];
$delete_id = sanitize($delete_id);
//Deleting sub-categories if parent is deleted
$sql= $veza->prepare ("SELECT * FROM categories WHERE id = '$delete_id'");
$result = $sql->execute();
$category = $result->fetch(PDO::FETCH_ASSOC);
if($category['parent'] == 0){
$sql = "DELETE FROM categories WHERE parent = '$delete_id'";
$sql->execute();
}
$dsql=$veza->prepare("DELETE FROM categories WHERE id = '$delete_id'");
$dsql->execute($_GET);
header("location: categories.php");
}
I can't find the solution.
I have Uncaught Error: Call to a member function fetch() on boolean
Try google prepared statement.
You have boolean in the $result
Usage:
$prep = $conn->prepare("SELECT * FROM table WHERE id=?");
The ? is not replaced!
Then use: $prep->bind_params('i', $id); $prep->execute()
And the result: $result = $prep->get_result();
Check if it is not false.
I found the solution by doing :
//delete Category
if(isset($_GET['delete']) && !empty($_GET['delete'])){
$delete_id = (int)$_GET['delete'];
$delete_id = sanitize($delete_id);
//Deleting sub-categories if parent is deleted
$sql= $veza->prepare ("SELECT * FROM categories WHERE id = $delete_id");
$sql->execute(array('delete_id' => $delete_id));
$category = $sql->fetch(PDO::FETCH_ASSOC);
if($category['parent'] == 0){
$sql= $veza->prepare("DELETE FROM categories WHERE parent = $delete_id");
$sql->execute();
}
$dsql=$veza->prepare("DELETE FROM categories WHERE id = '$delete_id'");
$dsql->execute($_GET);
header("location: categories.php");
}
i wrote a function to create an array with category_id and all subcategories ides, the main category should be selected from the page url example pages.php?category_id = 1,
then the array should be like 1,23,25
"25 is a subcategory for parent 23 and 23 is a subcategory for 1",
i'll use this later to show items with item_cat exist in array example
SELECT * FROM items WHERE item_cat IN (1,23,25)
the problem is my function is echo in the page, and i'm not sure i wrote it in a correct way here is my function code
$category_id=$_REQUEST['category_id'];
function categoriesIdes($parentId, $connection) {
global $category_id;
$sqlCategories = "SELECT * FROM categories
WHERE category_parent = ".$parentId." ";
$rsCategories = mysql_query($sqlCategories, $connection);
$totalCategoriesRows = mysql_num_rows($rsCategories);
while($rowsCategories = mysql_fetch_assoc($rsCategories)) {
$catId = $rowsCategories['category_id'];
echo ''.$catId.',' ;
categoriesIdes($catId, $connection);
}
}
$ides = categoriesIdes($category_id, $connection);
$idesall = ''.$category_id.','.$ides.'';
$idesall = substr($idesall,0,-1);
Possibly try this:
<?php
$category_id=$_REQUEST['category_id'];
function categoriesIdes($parentId, $connection) {
//not sure why you're using this
global $category_id;
//select all the childeren
$sqlCategories = "SELECT * FROM categories
WHERE category_parent = ".$parentId." ";
//query
$rsCategories = mysql_query($sqlCategories, $connection);
$totalCategoriesRows = mysql_num_rows($rsCategories);
//will hold categoryIDs found
$categoryIDs = array();
//for every child
while($rowsCategories = mysql_fetch_assoc($rsCategories)) {
//child id
$catID = $rowsCategories['category_id'];
//add to array
$categoryIDs[] = $catID;
//debug
echo ''.$catID.',' ;
//find and add the childeren
$categoryIDs = array_merge($categoryIDs, categoriesIdes($catID, $connection));
}
return $categoryIDs;
}
$ides = categoriesIdes($category_id, $connection);
$ids = '';
if (count ($ides) > 0){
$ids = $category_id .','. implode(',',$ides);
}
else{
//only 1 id
$ids = $category_id;
}
echo $ids;
?>
So the problem I am having is with this basic database application exercise I'm doing from a book. Basically, when you try to add a product to the database, as the code below shows, it checks to make sure all the fields are filled out. But then, at the end when it's performed the query and I have the include('home.php'), something is happening that when I am returned to the home.php page and I click one of the links on that page, I am getting the error I would get if one of the fields is left blank. Any ideas?
<?php
// Get the product data
$category_id = $_POST['category_id'];
$code = $_POST['code'];
$name = $_POST['name'];
$price = $_POST['price'];
// Validate inputs
if (empty($code) || empty($name) || empty($price) ) {
$error = "Invalid product data. Check all fields and try again.";
include('error.php');
} else {
// If valid, add the product to the database
require_once('database.php');
$query = "INSERT INTO products
(categoryID, productCode, productName, listPrice)
VALUES
('$category_id', '$code', '$name', '$price')";
$db->exec($query);
// Display the Product List page
include('home.php') ;
}
?>
home.php without the html/css
<?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);
?>
In the file home.php, your using $_GET instead of $_POST:
Change this:
$category_id = $_GET['category_id'];
To:
$category_id = $_POST['category_id'];
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