Jump to content

Creating a php function and then calling it from a button


Adamhumbug

Recommended Posts

HI all,

 

I am pretty new to php and am trying to teach myself - i dont have any massive project in mind and have just been playing around.  I decided to make a POS like system.

 

I was quite proud of my self, i created some php that got information from the db and displayed a box per record returned.

 

The database is returning products that a bar might sell, beer, wine, spirits and each product regardless of catagory is being put in a box on the screen.

 

I wanted to have a button that when pressed only shows the items in the database with the product_catagory of wine - same with spirits and softdrinks.

 

I have added my buttons that i want to do the work but at this point i am stuck.

 

After doing quite a lot of reading it seems that i am going to need to use "AJAX" - is this the case?

 

 

Below is just a test page that has the button on that i will use to call the function

<!DOCTYPE html>
<html>
<head>
	<title>page</title>
	<link rel="stylesheet" type="text/css" href="style.css">
	<script type="text/javascript" src="java.js"></script>
		
</head>
<body>
	<?php include "dbconn.php" ?>
	<?php include "testing.php" ?>



<div id="spiritButton" style="width:100px;height:100px;background:red">Click Me</div>

</body>
</html>


Below is the fucntion that pulls back all of the products, i wanted to change the sql command depending on which button is pressed (as in only show spirits when you click "spirits" but change with other product catagorys)

<?php


$sql = "SELECT * FROM products";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $pro_id = productButton.$row["product_id"];
        $pro_display = $row["product_name"]. "<br/><br/>"."£". $row["product_price"];

        echo <<< "EOT"
        <div class="productButton" id="$pro_id">$pro_display</div>
EOT
;
    }
} else {
    echo "No results found";
}
$conn->close();



?>

I would really appreciate any help on this but please be as gentle as possible as my ability is likely much lesser than yours.

 

Kind Regards

 

Adam

Link to comment
Share on other sites

As things are right now, with what you have, yes: you would need AJAX for this. You don't actually need it in a more pure sense, in that you don't need AJAX to click a button and see a new page, but you're not quite set up to do those sorts of things.

 

However AJAX is a bit of an investment, so maybe we put that on hold for now and focus more on the learning aspect.

 

So it looks like you have buttons for each product, but you're talking about showing products per category. Can you get the buttons or whatever for the categories? You should generate a form that sends data to a script (like itself) including which category to search.

For example, this uses a dropdown list instead of buttons.

<form action="" method="post">
<p>Select category: <select name="category">
<?php

// here you have to output a bunch of
//   <option value="unique category identifier">category name</option>
// where the unique category identifier is either an ID (if you have one) or else the name
// this should involve a database query or two

?>
</select> <button type="submit" name="search">Search</button></p>
</form>
Can you get that part working? (Post your code.) If you want to change it to actual buttons, we can do that after.
Link to comment
Share on other sites

Hi.

 

Firstly thanks for your help, i will take that code and see if i can get it going.

 

In terms of getting the buttons - yes i have that working.

 

I have buttons down the side as a sidebar and buttons in a grid as the main part of the screen - this works.

 

The code that makes the buttons down the side looks for unique values in the product field and creates one button per unique catagory (spirits/soft drinks/etc)

 

The code that makes the prroduct buttons also works.

 

I will come back to you with what happens with the code that you have provided.

 

Kind Regards

 

Adam

Link to comment
Share on other sites

Hi,

 

This is the code that i have come up with.

 

It fills the dropdown with all of the product types

    <?php
    include 'dbconn.php';
    ?>


<!DOCTYPE html>
<html>
<head>
    <title>Register</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <script type="text/javascript" src="java.js"></script>
</head>
<body>
    <div class="headerBar">
        TOP
    </div>
    <div class="sideBar">
            <?php require 'productCatagory.php' ?>
    </div>
    <div class="mainArea">
        <form action="" method="post">
<p>Select category: <select name="category">

<?php


$sql = "SELECT DISTINCT(product_catagory) FROM `products`";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
    $pro_cat = $row["product_catagory"];

echo <<< "EOT"
<option value="$pro_cat">$pro_cat</option>
EOT
;
}
} else {
echo <<< "EOT"
<option value="None_Found">No Products Found</option>
EOT
;
}
// $conn->close();



?>
</select> <button type="submit" name="search">Search</button></p>
</form>



        <div class="buttonArea">
            <?php require 'productButtons.php' ?>
        </div>
        <div class="itemArea">
            <div class="itemisedArea">
                <textarea class="FormElement" name="term" id="term" style="width: 98%; height: 100%;"></textarea>
            </div>
            <div class="keypadArea">
            </div>
        </div>
    </div>
</body>
</html>

The original code that i had to create the buttons was

<?php

$sql = "SELECT DISTINCT(product_catagory) FROM `products`";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
    $pro_cat = $row["product_catagory"];

echo <<< "EOT"
<div class="productCatagoryButton" id="$pro_cat">$pro_cat</div>
EOT
;
}
} else {
echo "0 results";
}
// $conn->close();

?>

I was thinking/hoping that somehow, i could change the sql command (on a button click) sothat runs and pulls all of the product buttons for each catagory.

 

I know how to pull for one catagory and i know how to pull for them all but the product buttons down the sidebar are generated pulling info from the database and echoing this with html to build the buttons

 

can this set a variable to change

SELECT * FROM products WHERE product_catagory = "Spirit"

 

to

SELECT * FROM products WHERE product_catagory = "Wine"

 

 

Am i looking at this the right way?

Link to comment
Share on other sites

Am i looking at this the right way?

Yup.

 

The name of the category chosen in the form will be in $_POST, if the form was submitted. But you can't just put the value directly into the query because of SQL injection: I, a malicious user, could manipulate the form and make it send whatever value I wanted, and that means I could completely change what your query actually does.

 

The safest way to deal with that is by using prepared statements. Looks like

$sql = "SELECT * FROM products WHERE product_catagory = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $_POST["category"]);
$stmt->execute();
$result = $stmt->get_result();
// then fetch with $result like normal
Remember that you can only do this if the form was submitted, so on the first page load you'll have to decide what you want to do. Showing nothing (yet) would be a good idea. The submit button was named "search" so you can

if (isset($_POST["search"])) {
	// submitted
} else {
	// not submitted
}
Link to comment
Share on other sites

Hi,

 

Thanks again for your response.

 

So forgive me if i am missing the point here but, how do i run my php function from the buttons, currenlty it is on page load but i have read that you cannot run a function from a button without AJAX.

 

Can i put an onclick on the button that will call the function.

<div onclick="show_spirits()">show spirits</div>

<div> onclick="show_soft_drinks()">show soft drinks</div>

Where you have put

 

 

$sql = "SELECT * FROM products WHERE product_catagory = ?";

 

how do i set the "?" to be the value that was pulled from the querey that set the button.

 

If my sql looked something like

$sql = "SELECT * FROM products WHERE product_catagory = $pro_cat";

and on clicking the button it set the $pro_cat to = the value of the div and then run the db querey?

 

Is this possible or am i over complicating matters here.

 

Kind Regards

 

Adam

Link to comment
Share on other sites

This as my prepared statement?


<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$stmt = $this->conn->prepare("SELECT * FROM products WHERE product_catagory=?");
$stmt->bind_param("s", $_POST["product_catagory"]);
$stmt->execute();
$result = $stmt->get_result();   
if($result->num_rows => 1) {    
    while ($data = $result->fetch_assoc()) {
        // echo my echo goes here
    }
}

I dont know how to get the value from the button

if (isset($_POST["search"])) {
	// submitted
} else {
	// not submitted
}

do i need to give it div value rather than the "search"

Link to comment
Share on other sites

The only "value" from the button is the text that's displayed on it. Why would you need that?

 

If $_POST['search'] is set (check using isset(), as shown), then the form has been submitted, i.e. the button has been clicked.

 

The click process causes the page to reload and set the $_POST['search'] and $_POST["product_category"] values. The $_POST["product_category"] value is the option that was chosen in the select, before the button was clicked.

 

So taking your code where you create the <select> and button, you'd need to add some PHP code to process those values once the button is clicked (submitting the form).

 

    <?php
    include 'dbconn.php';
    ?>


<!DOCTYPE html>
<html>
<head>
    <title>Register</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <script type="text/javascript" src="java.js"></script>
</head>
<body>
    <div class="headerBar">
        TOP
    </div>
    <div class="sideBar">
            <?php require 'productCatagory.php' ?>
    </div>
    <div class="mainArea">
        <form action="" method="post">
<p>Select category: <select name="category">

<?php


$sql = "SELECT DISTINCT(product_catagory) FROM `products`";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
    $pro_cat = $row["product_catagory"];

echo <<< "EOT"
<option value="$pro_cat">$pro_cat</option>
EOT
;
}
} else {
echo <<< "EOT"
<option value="None_Found">No Products Found</option>
EOT
;
}
// $conn->close();



?>
</select> <button type="submit" name="search">Search</button></p>
</form>

<?php
//Assuming it's okay to show the results of clicking the button here?
if(isset($_POST['search'])) {

  $stmt = $this->conn->prepare("SELECT * FROM products WHERE product_category=?");
  $stmt->bind_param("s", $_POST["product_category"]);
  $stmt->execute();
  $result = $stmt->get_result();   
  if($result->num_rows => 1) {    
    echo 'Results: ';
    while ($data = $result->fetch_assoc()) {
      // your echo goes here, showing whatever you want from the database query
  } else {
    echo 'No results found';
  }
}

?>

        <div class="buttonArea">
            <?php require 'productButtons.php' ?>
        </div>
        <div class="itemArea">
            <div class="itemisedArea">
                <textarea class="FormElement" name="term" id="term" style="width: 98%; height: 100%;"></textarea>
            </div>
            <div class="keypadArea">
            </div>
        </div>
    </div>
</body>
</html>
Watch your spelling on category (vs catagory), by the way.

 

I think the flow Req. is taking you through, btw, is to get the basic functionality working with vanilla HTML and PHP. Then you can start moving parts of this to specific PHP scripts that can receive and send data via AJAX calls. Then you'll have to move into JavaScript to receive the data and modify the page to show the results.

Link to comment
Share on other sites

Hi all,

 

I have been totally lost with this and have done some reading around the topic.

 

I have made some changes but i am still having no luck in getting it to work.

 

This is my Register.php

<!DOCTYPE html>
<html>
	<head>
		<title>Register</title>
		<link rel="stylesheet" type="text/css" href="style.css">
		<script type="text/javascript" src="java.js"></script>

		<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function() {

	//##### send add record Ajax request to response.php #########
	$("#Spirit").click(function (e) {
			e.preventDefault();
			if($("#textfield").val()==='')
			{
				alert("Please enter some text!");
				return false;
			}
			
		
			
		 	var myData = 'content_txt='+ $("#textfield").val(); //build a post data structure
			jQuery.ajax({
			type: "POST", // HTTP method POST or GET
			url: "response.php", //Where to make Ajax calls
			dataType:"text", // Data type, HTML, json etc.
			data:myData, //Form variables
			success:function(response){
				$("#buttonArea").append(response);
				$("#textfield").val(''); //empty text field on successful
				$("#Spirit").show(); //show submit button

			},
			error:function (xhr, ajaxOptions, thrownError){
				$("#Spirit").show(); //show submit button
				alert(thrownError);
			}
			});
	});
</script>

	</head>
	<body>
		<div class="headerBar">
			TOP
		</div>
		<div class="sideBar">
			<div class="productCatagoryButton" id="sideBarSettings">Settings</div>
			<form method="post">
				<?php require 'productCatagory.php' ?>
			</form>
			
		</div>
		<div class="mainArea">
			
			<div class="buttonArea" id="buttonArea">
				<?php /*require 'productButtons.php'*/ ?>
				<?php require_once 'response.php' ?>
				<input type="text" name="textfield">
			</div>
			<div class="itemArea">
				<div class="itemisedArea">
					<table style="width:100%;">
						<tr>
							<th style="width:70%;">Product</th>
							<th>Price</th>
						</tr>
					</table>
				</div>
				<div class="keypadArea">
					<div class="payButton">PAY</div>
				</div>
			</div>
		</div>
	</body>
</html>

This is my response.php

<?php 

include_once("dbconn.php");

if(isset($_POST["textfield"]))
{
	$pro_cat_from_button = $_POST["textfield"];
	$sql = "SELECT * FROM products WHERE product_catagory = '$pro_cat_from_button'";
	$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
    	$pro_id = "productButton".$row["product_id"];
    	$pro_display = $row["product_name"]. "<br/><br/>"."£". $row["product_price"];

        echo <<< "EOT"
        <div class="productButton" id="$pro_id">$pro_display</div>
EOT
;
    }
} else {
    echo "No results found";
}
$conn->close();
}

 ?>

This is my dbconn.php


<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "register";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

This is my productcatagory.php that creates the sidebar buttons that i want to use to show other buttons when clicked.

<?php 

include 'dbconn.php';

$sql = "SELECT DISTINCT(product_catagory) FROM `products`";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
    	$pro_cat = $row["product_catagory"];

        echo <<< "Escaped"
        <input type="submit" name="productCatagoryButton" class="productCatagoryButton" id="$pro_cat" value="$pro_cat"/>
        
Escaped
;
    }
} else {
    echo "0 results";
}
$conn->close();

?>

this is my productbuttons.php file that i have included to show an example of what i want to happen.

<?php 

include 'dbconn.php';

$sql = "SELECT * FROM products WHERE product_catagory = 'Spirit'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
    	$pro_id = "productButton".$row["product_id"];
    	$pro_display = $row["product_name"]. "<br/><br/>"."£". $row["product_price"];

        echo <<< "EOT"
        <div class="productButton" id="$pro_id">$pro_display</div>
EOT
;
    }
} else {
    echo "No results found";
}
$conn->close();

?>


So obviously this isnt working but let me explain what i would like it to do.

 

The prouct catagory buttons are populated in a side bar when the page loads - the sql selects all of the different product catagories and creates a button for each unique value in the table.

 

I want to - when these buttons are clicked run a query that shows all of the products that match the product type that the button represents.

(I know that my code isnt doing that, it is currently looking at a text box which i tried to utilise to understand where i was going wrong.  This text box will not be part of the final product)

 

So if you click the Spirit button, all of the products in the table with the product_catagory "Spirit" should be displayed.

 

I can get the products to display when the page loads, but am struggling to get this to happen from a button click.

 

I know you guys have tried to guide me before and i really appreciate it - can we start again with what i have?

 

Kind Regards

 

Adam

Link to comment
Share on other sites

I'm a bit late to the party but let me add this one line:

 

You cannot execute a PHP function directly from an HTML button/submit. The button is on the client. The PHP function is on the server.

 

So - with that said you need to think of your approach a bit differently. Your button has to trigger a PHP Script which can then make a decision as to what is to be done. If all you have to do is pass a single parameter to this script then an anchor tag in the shape of a button (use CSS) could be your solution. When you build each of those elements into your HTML page, just supply the script name (and path) along with a GET parm that passes the value you need to relate to that particular button. Another way could be with a separate form for each logical piece of the pie that supplies a hidden input element containing the value you need to pass. Of if your HTML page can be written to contain only a single form element, then your buttons could be developed using an appropriate value for each that tells your script what to do.

 

In any of these cases, the script will be run and it will make a decision as to what button was clicked based upon either the value of that button or the GET parm that was passed to the script. From that point on your script will be written to know how to handle the situation.

 

I hope this gives you something to think about and helps you to see how the HTML has to pass data to the PHP and that it is not a 'direct' thing but more of a handoff of the client's control of things to the server's control of things. And yes as was mentioned very early on, you can do this with AJAX but you may not be ready for that kind of work or understanding.

 

Good luck.

Link to comment
Share on other sites

i'll be a bit more basic.

 

because what you are doing is determining what will be displayed on a page, you need to do this on a single page. this will simplify and reduce all the program logic. you also need to use a $_GET parameter to control what the page will display, i.e. $_GET['product_category']

 

if you want to use buttons, make them links, with a get parameter on the end of the url that indicates the category. you should actually have a category database table that assigns category id's, then use the id in the products table and in the links/form and you would query this table to build the category links/form. if you want to use a form, use a get method form and make the form sticky (pre-select the option choice that matches any exiting category selection.)

 

the logic to determine what data to GET in order (speaking of which, any select query that can match more than one row needs and ORDER BY ... term) to display the product data on the page will first check if there a $_GET['product_category'] at all, it's not empty, and it is one of the expected choices (you would use the same data being retrieved to build the links/form for this validation step.) for each of these conditions, you need to decide what the code will do. if there's no $_GET['product_category'], it would either mean that no category has been selected or you have a programming error somewhere. if a category selection is 'required', but there is none, you would set up a prompt message and display that where the product data is to be displayed. if $_GET['product_category'] is empty or is not one of the expected choices, this is an error, either due to a programming error somewhere or someone is submitting a category that doesn't (currently) exist. you would either setup an error message and output it or you would treat this the same as having no $_GET['product_category'] at all.

 

if you determine that you have a usable $_GET['product_category'] value, you would query for the matching product data, using a prepared query.

 

if the query matches no rows, you would set up and display an appropriate message. if the query matches any row(s), you should fetch the data into a php array variable, then use this variable in the section of code producing the html output. you should also pre-fetch the category choices into a php array variable, then use this variable in the section of code producing the links/form. fetching  all the data from SELECT queries and storing it in php variable(s) will separate your database specific php code from the presentation code. this will make it easier to design, write, and test your code, make it easier if you need to switch the php database extension, and for the case of validating the submitted product category, you can use the array of fetched category choices.

 

edit - btw DISTINCT is not a mysql function and the ( ) you have after it don't serve any purpose. just use SELECT DISTINCT product_catagory ...

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.