Help making function

Hello everyone… I’m still new to php… and started to use functions lately… And I wanna make a function called etc

function products() {
   $select = return "SELECT * FROM Products";
   $insert = return "INSERT INTO Products SET ProductsName='$productsName'";
   $update = return "UPDATE ProductsName FROM Products WHERE ProductID='$productID'";
   $delete = return "DELETE * FROM  Products WHERE ProductID='$productID'";


//is that function made right, and if I then wanna select from the db.. should I then just call


wondering that a little :open_mouth: I tried to ask on already, but no answer :confused:

What you’re trying to achieve can be achieved using various approaches.

But first I’ll start with why your current code isn’t working. First of all, you didn’t define a parameter for the function. If a function has something passed to it (above you’ve passed $select) then it should have a way of handling that, e.g.:

function products($action){

Secondly, variables are variable. When you call the products function on your bottom line, you pass $select as a variable. But $select hasn’t been given a value.

Thirdly, when you use the = operator, it means ‘assign’. So basically, $Name = ‘Bob’ would mean that everywhere you use $Name afterwards, unless it is changed again, it’s the same thing as putting ‘Bob’. So the four lines in the function are assigning $select to the return of a string, which doesn’t make more sense. What you are trying to do is change the outcome of a function based on what’s given to it. I’ll show you how in a moment.

The fourth major thing is that $productsName and $productID aren’t set as anything, so the function would attempt to plug values in which it doesn’t have.

So, here’s my suggestion based on your code above. There are other methods but they might be a little tricky to grasp without knowing about functions.

There are a couple of things I could suggest. The first is using constants. Define constants that have a unique value. The best method with this approach, because it wouldn’t make sense to use an addition of multiple values, is to use consecutive numbers:

define('SELECT', 1);
define('INSERT', 2);
define('UPDATE', 3);
define('DELETE', 4);

The 2 benefits of using constants here are that they always hold the same value as long as they have been previously defined and that they are available everywhere in the application. This is different from variables because at different places in the application they can have different values and, therefore, functions can’t use them without them being passed to them because they wouldn’t know which instance of the variable they are supposed to be using. Constants are written in uppercase to make it obvious that they are constants and not a typo which should have been a variable or a string.

Next stage is to write a function which is given a parameter. Essentially this parameter holds a number, defined above, which can be compared with the above constants. So if the number 1 (which is now equal to the constant SELECT) is passed to it, it will return the select query etc. The second parameter will be optional and will hold the name or ID if expected:

function products($Action, $Parameter = false){ //If you set a value in the parameter, it will be that value unless something has been passed
    if($Parameter !== false){
        $Parameter = mysql_real_escape_string($Parameter); //ALWAYS escape your data to prevent MySQL injection. If you're using a different database system than MySQL, use the equivalent function.
    switch($Action){ //the switch statement is like an if/or but with one variable with multiple possibilities.
        case SELECT:
            return "SELECT * FROM Products";
        case INSERT:
            if($Parameter === false){ //if no parameter is given, error out.
                throw new Exception("No product name given to the INSERT query");
                return "INSERT INTO Products SET ProductsName='{$Parameter}'";
        case UPDATE:
            if($Parameter === false){
                throw new Exception("No product ID given to the UPDATE query");
                return "UPDATE ProductsName FROM Products WHERE ProductID='{$Parameter}'";
        case DELETE:
            if($Parameter === false){
                throw new Exception("No product ID given to the DELETE query");
                return "DELETE * FROM  Products WHERE ProductID='{$Parameter}'";
    return false; //An unknown action has been passed

That function may include a lot of new stuff so read the comments and the PHP manual if you’re unsure on anything.

From then, all you need to do is make calls to the function like the following:

products(SELECT); //returns the select query string
products(INSERT); //errors out because you haven't given a name
products(INSERT, 'someproduct'); //returns the insert query to insert a product with the name 'someproduct'
products(UPDATE, 1); //returns the beginning of the update query string for product #1
products(DELETE, 1); //returns the query string to delete product #1

If you’re no happy with using constants, then replace the constants with strings, such as products(“Select”), making changes to the switch() statement to look for strings not constants.

Hope I didn’t go through it too fast for you there, if you have any problems or questions just ask ahead :slight_smile:

WooW a long answer o.O But I’m thinking a little… If I’m using constants, what if I then have another function called Customers(); etc… and I have SELECT, INSERT, DELETE and UPDATE?

I know I could define like define(‘select’, 5); and so on… but then it would be hard to remember what select that is to what function :open_mouth:

You can still use the same constants again. All they are is a unique value which no other constant (which you’ll be using for similar purposes) holds.

You wouldn’t need to redefine them, just use them the same way as above.

Ohh okay, thank you Jake… But may I ask then…

if I have:

$CategoryID = 1;

function getProductsByCategoryID() {
        return "SELECT ProductID, ProductName, SupplierID, CategoryID, QuantityPerUnit, UnitPrice, UnitsInStock, UnitsOnOrder, ReorderLevel, Discontinued FROM Products WHERE CategoryID='$CategoryID'";

Why will it not return anything then? - because if I do like

function getProductsByCategoryID() {
        return "SELECT ProductID, ProductName, SupplierID, CategoryID, QuantityPerUnit, UnitPrice, UnitsInStock, UnitsOnOrder, ReorderLevel, Discontinued FROM Products WHERE CategoryID=1";

it works just fine and will get the results I need :S

you need to get a handle on variable scope - the first two examples should explain it.

Sorry don’t understand fully :frowning:

My classes.php code is:

function loadData($result) {
        while ($row = mysql_fetch_array($result)) {
            $productID = $row['ProductID'];
            $productName = $row['ProductName'];
            $supplierID = $row['SupplierID'];
            $categoryID = $row['CategoryID'];
            $quantityPerUnit = $row['QuantityPerUnit'];
            $unitPrice = $row['UnitPrice'];
            $unitsInStock = $row['UnitsInStock'];
            $unitsOnOrder = $row['UnitsOnOrder'];
            $reorderLevel = $row['ReorderLevel'];
            $discontinued = $row['Discontinued'];
            if($ctr == 1)
               echo("<tr class='row'><td>$productID</td><td>$productName</td><td>$supplierID</td>
               $ctr = 0;
            } else {

//Database Classes
function getProductsByCategoryID() {
        return "SELECT ProductID, ProductName, SupplierID, CategoryID, QuantityPerUnit, UnitPrice, UnitsInStock, UnitsOnOrder, ReorderLevel, Discontinued FROM Products WHERE CategoryID='$category'";

And my index.php:


$category = 1;

$result = mysql_query(getProductsByCategoryID()) or die(mysql_error());

<!DOCTYPE html>
	<meta http-equiv="Content-type" content="text/html;">
	<title>HTML5 starter</title>
	<style type="text/css">
		h2 {
			text-align: center;
		p {
			text-align: left;
			padding: 10px;

		#wrapper {
			width: 1009px;
			margin: 0 auto;

		table { border-collapse: collapse; }

		.row {background-color: #999;}

		thead td {background-color: #999;}
	<div id="wrapper">
		<table border="1">
				<?php loaddata($result); ?>

Again, you need to look up “scope”. This is the word used to basically mean where a variable can be accessed.

Essentially the following will not work, and can not work:

$Var = 'Hello World';
function somefunction(){
    echo $Var;

This is because $Var is only available outside the function. When using OOP this concept changes a little but for the basics, it cannot work.

So instead make a function which accepts var as a parameter:

function somefunction($Var){
    echo $Var;
somefunction('Hello World!');

I’ll just add a little bit about functions.

when you declare a function, it usually has a variable(s) passed into it. so when you write,
function hello_world($hello) that function will only have one variable to work with called $hello. There are several ways to call the function.
hello_world(‘Hello World’);

These will all work and the function will just convert any of those to the variable $hello once it is called.

You can also use globals

$goodbye = 'see ya';
function hello_world($hello){
global $goodbye;
echo $hello.' '.$goodbye;
hello_world('hi ya');