Link to home
Start Free TrialLog in
Avatar of Mitchell Wakura
Mitchell Wakura

asked on

How to fix

<?php include('db.php'); ?>
<?php session_start(); ?>
<?php //print_r($_SESSION['cart']); ?>
<?php date_default_timezone_set('Asia/Manila'); ?>
<?php
    $jim = new Data();
    $countproduct = $jim->countproduct();
   
    $cat = $jim->getcategory();
    class Data {
        function countproduct(){
            $count = 0;
            $cart = isset($_SESSION['cart']) ? $_SESSION['cart']:array();
            foreach($cart as $row):
                if($row['qty']!=0){
                    $count = $count + 1;
                }
            endforeach;
           
            return $count;
        }
        function getcategory(){
            $result = mysqli_query("SELECT * FROM category");
            return $result;
        }
    }



when i try to run that code am getting the following error




Warning: mysqli_query() expects at least 2 parameters, 1 given in C:\xampp\htdocs\epicsites\shop\include\home\header.php on line 23

am stuck here guys need hepl please and am an armature  to PHP if you are to provide help please do your best in getting it more detailed
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

mysqli_query takes 2 arguments - the connection to the DB and the query string

$result = mysqli_query("SELECT * FROM category", $conn);

where $conn is whatever you've called you connection in your db.php file.

Be aware that $result won't be a list of categories - it will be a DB results set which you will need to loop through to get the actual data

Having said that, you should be aware that mysql* functions are deprecated in PHP5 and removed completely from PHP7, so now would be a very good time to switch to either mysqli or PDO
Avatar of Mitchell Wakura
Mitchell Wakura

ASKER

Below i attached my db.php which one are you calling $conn. Am trying to learn thanks
Hey Mitchell,

Nothing attrached, so I can;t check it.

When you create a connection to a DB, you usually assign the connection to a variable, such as:

$conn = new mysqli("host", "user", "pass", "db");

That would give you a connection called $conn. mysqli_query needs to have that variable name passed into it. Because you're using a class, you'll probably need to pass the connection into the class in order for it to work correctly.
Sorry thought i attached
db.php
OK. In your DB file, you seem to be creating 2 connections - one using mysql* and one using PDO. Delete the one for mysql*. These functions are deprecated and removed in PHP7.

That should just leave you with the PDO connection:

$db = new PDO('mysql:host='.$mysql_hostname.';dbname='.$mysql_database, $mysql_user, $mysql_password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

Open in new window

So from that you can see that your Database connection is stored in a variable called $db.

However, you then have a couple of other problems. Firstly, you are creating you connection outside of your Data class, so it won't be available inside the class. You can do one of 2 things. Either move the connection so that it's inside of the class, or dependency inject it into the class. As you already have a DB Connection, it makes sense to dependency inject it into your Class, and to do that you will need to create a class constructor (ctor)

Secondly, you are creating a PDO connection, but then in your getcategory() function, you are trying to use the mysqli_query method. That won't work. On a PDO connection, you need to use the PDO query methods, not the mysqli ones.

Your class should look like this:

class Data {

    private $db;

    function __construct($dbConnection) {
        $this->db = $dbConnection;
    }

    function getcategory() {
        $stmt = $this->db->query("SELECT * FROM category");
        return $stmt->fetchAll(PDO::FETCH_OBJ);
    }
}

Open in new window

You can see that the Database connection is passed into the class as an argument and then stored internally to the class in a private variable called $db. The getcategory() function then uses that internal PDO Db connection to run the query, and return the results as an array of objects, so to use it, you would need to do this:

include('db.php');
$jim = new Data($db); // pass the DB Connection into the class constructor.
$cat = $jim->getcategory();

foreach ($cat as $category): // loop through the returned array of objects
    echo $category->someProperty; // someProperty is a column name from your DB Table
endforeach;

Open in new window

thanks it did worked but am having troubles changing queries from mysql to pdo
OK. You only had one query in your original class and I've shown you the code for that using PDO. If you're struggling with something else, let me know :)

The actual SQL statements that you need to run are exactly the same between mysqli and PDO so converting from one to the other should be straight forward
in that piece of code i get it but to other part of the code i'm failing to change form mysql to pdo for this example

<?php                          
                            $q = "Select * from category order by title asc";
                            $r = mysql_query($q);

                            if($r){
                                while($row = mysql_fetch_array($r)){
                                    echo '<a href="category.php?filter='.$row['title'].'" class="list-group-item">'.$row['title'].'</a>';
                                                }
                                          }
                        ?>

Iam failing to change that mysql to pdo
OK. For PDO, it would look something like this:

$result = $db->query("Select * from category order by title asc");

if ($result) {
    while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
        echo '<a href="category.php?filter='.$row['title'].'" class="list-group-item">'.$row['title'].'</a>';
    }
}

Open in new window

As previously discussed, it assumes you have a PDO connection stored in the $db variable. If you're using this in your Data class like your getcategory() method, then use $this->db->query() instead of $db->query()
so i will include the db.php file or i will just work it like that
Oh it worked fine with out including the db.php file thank you. Do you have any learning resource that you can recommend me i really want to do web dis and dev
Hey Mitchell,

You do need to include the db.php file at the start of your page to make the connection to the DB. That then creates the $db variable that you can use throughout your page.

As for learning resources, there are plenty online, so just do a search and you'll find loads of tutorials for all things WebDev - HTML / CSS / Javacssript / PHP etc.

Something I would advise if you're going to be learning and developing is to set up your own local webserver. If you're on a Windows computer, you can install WAMPServer, and this will allow you to test and run websites using PHP and MySQL on your local machine, rather than using an online host.

Good luck with it :)
This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.