Jump to content

php function didn't work on mysqli


gongpex

Recommended Posts

Hello everyone

 

Since I use mysqli I often found a problem, one of them is about php function

 

I think I need to show example code on you:

<?php        $result=mysqli_query($connect,"select name from products where id='$pid'");        $row=mysqli_fetch_array($result);        echo $row['name'];?>	

this will show value of $row['name']

 

but when I put this code on function like this :

<?php       function test($pid) {        $result=mysqli_query($connect,"select name from products where id='$pid'");		$row=mysqli_fetch_array($result);		echo $row['name'];	}  test($pid);?>

This didn't show anything

 

Q : what's mistake on my function code?

 

please someone help me

 

Thanks

Edited by gong
Link to comment
Share on other sites

You are not sending value for $pid with test(); the function is expecting a argument for ($pid), if $pid is global remove it from function, OR send it when you call the function.

 

$pid = 99999;

 

function test() {$result=mysqli_query($connect,"select name from products where id='$pid'");$row=mysqli_fetch_array($result);echo $row['name']; }

 

test();

 

OR

 

$pid= 99999;

 

function test($pid) { //expects argument to be sent$result=mysqli_query($connect,"select name from products where id='$pid'");$row=mysqli_fetch_array($result);echo $row['name']; }

 

test($pid);

Link to comment
Share on other sites

I had try using 'GET[]' to take value from $pid but the result still same,

 

Even I test my code like this :

function test() {$result=mysqli_query($connect,"select name from products where id='1'");$row=mysqli_fetch_array($result);echo $row['name'];    }test();

I deliberately change $pid using value ='1'

 

but the result still same it's didn't show anything. Except I delete function code.

 

please someone help me

 

Thanks

Link to comment
Share on other sites

It is a scope problem, at present $result, $connect, $row are ALL local to function only, $pid asnd $connect have no ref to the variables of the same name on the outside of this function, so they remain blank or null, no connection ref means no connection to database.

 

try adding

global $pid;

global $connection;

at the beginning of function, this should now give access to global variables declared outside function.

      function test() {            global $connect;            global $pid;            $result = mysqli_query($connect, "SELECT name FROM products WHERE id='$pid'");            $row = mysqli_fetch_array($result);            echo $row['Name'];        }        test();

if you are using $_GET, you need to setup some error catching, or default value to use, when a $_GET is not set.

Edited by dsonesuk
Link to comment
Share on other sites

  • 2 weeks later...

I had told before about this, please see on post #3If I use :function test() {$result=mysqli_query($connect,"select name from products where id='1'");$row=mysqli_fetch_array($result);echo $row['name']; }test();it won't show anything,but if I delete the function like this :$result=mysqli_query($connect,"select name from products where id='1'");$row=mysqli_fetch_array($result);echo $row['name']; it will show value of product pid '1',So, please help me at least if I use function it can be display the value of pidThanks

Link to comment
Share on other sites

It maybe didn't work because of echo $row['Name']; (should be echo $row['name']; You should have code similar to this

<?phprequire_once('/Connections/product-connection.php');// will have connection details (database, password, user, host) $connect variable?><!DOCTYPE html><html>    <head>        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">        <meta name="viewport" id="viewport" content="target-densitydpi=high-dpi,initial-scale=1.0,user-scalable=no" />        <title>Document Title</title>        <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>        <script  type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>        <script type="text/javascript">        </script>        <style type="text/css">        </style>    </head>    <body>        <?php              if (filter_input(INPUT_GET, 'pid', FILTER_VALIDATE_INT)) {            $pid = filter_input(INPUT_GET, 'pid', FILTER_VALIDATE_INT);        }        function test() {            global $connect;            global $pid;            $sql = "SELECT name FROM products WHERE id=$pid";            $result = mysqli_query($connect, $sql);            $row = mysqli_fetch_array($result);            if ($result->num_rows > 0) {                echo $row['name'];            } else {                echo "NO records Found";            }        }        test();        ?>    </body></html>

The quotes around int value will work, it just take minuscule bit longer as it converts from string to int value, it good practice to remove quotes around number value.

Link to comment
Share on other sites

  • 2 weeks later...

Hello everyone,

 

allright I think I need to post my true problem about this topic:

 

product.php :

<?php	include("includes/db.php");	include("includes/functions.php");		if($_REQUEST['command']=='add' && $_REQUEST['productid']>0){		$pid=$_REQUEST['productid'];		addtocart($pid,1);		header("location:shoppingcart.php");		exit();	}	   /*     $result=mysqli_query($connect,"select name from products where serial='2'");		$row=mysqli_fetch_array($result);		echo $row['name'];	 */?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>Products</title><script language="javascript">	function addtocart(pid){		document.form1.productid.value=pid;		document.form1.command.value='add';		document.form1.submit();	}</script></head><body><form name="form1">	<input type="hidden" name="productid" />    <input type="hidden" name="command" /></form><div align="center">	<h1 align="center">Products</h1>	<table border="0" cellpadding="2px" width="600px">		<?php			$result=mysqli_query($connect,"select * from products");			while($row=mysqli_fetch_array($result)){		?>    	<tr>        	<td><img src="<?php echo $row['picture'];?>" /></td>            <td>   	<b><?php echo $row['name'];?></b><br />            		<?php echo $row['description'];?><br />                    Price:<big style="color:green">                    	$<?php echo $row['price'];?></big><br /><br />                    <input type="button" value="Add to Cart" onclick="addtocart(<?php echo $row['serial'];?>)" />			</td>		</tr>        <tr><td colspan="2"><hr size="1" /></td>        <?php } ?>    </table></div></body></html>

function.php

<?php	function get_product_name($pid){	    global $connect;		global $pid;		$result=mysqli_query($connect,"select name from products where serial=$pid");		$row=mysqli_fetch_array($result);		echo $row['name'];	}	function get_price($pid){	    global $connect;		global $pid;		$result=mysqli_query($connect,"select price from products where serial=$pid");		$row=mysqli_fetch_array($result);		echo $row['price'];	}	function remove_product($pid){		$pid=intval($pid);		$max=count($_SESSION['cart']);		for($i=0;$i<$max;$i++){			if($pid==$_SESSION['cart'][$i]['productid']){				unset($_SESSION['cart'][$i]);				break;			}		}		$_SESSION['cart']=array_values($_SESSION['cart']);	}	function get_order_total(){		$max=count($_SESSION['cart']);		$sum=0;		for($i=0;$i<$max;$i++){			$pid=$_SESSION['cart'][$i]['productid'];			$q=$_SESSION['cart'][$i]['qty'];			$price=get_price($pid);			$sum+=$price*$q;		}		return $sum;	}	function addtocart($pid,$q){		if($pid<1 or $q<1) return;				if(is_array($_SESSION['cart'])){			if(product_exists($pid)) return;			$max=count($_SESSION['cart']);			$_SESSION['cart'][$max]['productid']=$pid;			$_SESSION['cart'][$max]['qty']=$q;		}		else{			$_SESSION['cart']=array();			$_SESSION['cart'][0]['productid']=$pid;			$_SESSION['cart'][0]['qty']=$q;		}	}	function product_exists($pid){		$pid=intval($pid);		$max=count($_SESSION['cart']);		$flag=0;		for($i=0;$i<$max;$i++){			if($pid==$_SESSION['cart'][$i]['productid']){				$flag=1;				break;			}		}		return $flag;	}		function test() {	$result=mysqli_query($connect,"select name from products where serial='1'");		$row=mysqli_fetch_array($connect,$result);		echo $row['name'];	}?>

shoppingcart.php

<?php	include("includes/db.php");	include("includes/functions.php");		if($_REQUEST['command']=='delete' && $_REQUEST['pid']>0){		remove_product($_REQUEST['pid']);	}	else if($_REQUEST['command']=='clear'){		unset($_SESSION['cart']);	}	else if($_REQUEST['command']=='update'){		$max=count($_SESSION['cart']);		for($i=0;$i<$max;$i++){			$pid=$_SESSION['cart'][$i]['productid'];			$q=intval($_REQUEST['product'.$pid]);			if($q>0 && $q<=999){				$_SESSION['cart'][$i]['qty']=$q;			}			else{				$msg='Some proudcts not updated!, quantity must be a number between 1 and 999';			}		}	}	?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>Shopping Cart</title><script language="javascript">	function del(pid){		if(confirm('Do you really mean to delete this item')){			document.form1.pid.value=pid;			document.form1.command.value='delete';			document.form1.submit();		}	}	function clear_cart(){		if(confirm('This will empty your shopping cart, continue?')){			document.form1.command.value='clear';			document.form1.submit();		}	}	function update_cart(){		document.form1.command.value='update';		document.form1.submit();	}</script></head><body><form name="form1" method="post"><input type="hidden" name="pid" /><input type="hidden" name="command" />	<div style="margin:0px auto; width:600px;" >    <div style="padding-bottom:10px">    	<h1 align="center">Your Shopping Cart</h1>    <input type="button" value="Continue Shopping" onclick="window.location='products.php'" />    </div>    	<div style="color:#F00"><?php echo $msg;?></div>    	<table border="0" cellpadding="5px" cellspacing="1px" style="font-family:Verdana, Geneva, sans-serif; font-size:11px; background-color:#E1E1E1" width="100%">    	<?php			if(is_array($_SESSION['cart'])){            	echo '<tr bgcolor="#FFFFFF" style="font-weight:bold"><td>Serial</td><td>Name</td><td>Price</td><td>Qty</td><td>Amount</td><td>Options</td></tr>';				$max=count($_SESSION['cart']);				for($i=0;$i<$max;$i++){					$pid=$_SESSION['cart'][$i]['productid'];					$q=$_SESSION['cart'][$i]['qty'];					//$pname=get_product_name($pid);					if($q==0) continue;			?>            		<tr bgcolor="#FFFFFF"><td><?php echo $i+1;?></td><td><?php get_product_name($pid) ;?></td>                    <td>$ <?php get_price($pid);?></td>                    <td><input type="text" name="product<?php echo $pid;?>" value="<?php echo $q;?>" maxlength="3" size="2" /></td>                                        <td>$ <?php get_price($pid)*$q ?></td>                    <td><a href="javascript:del(<?php echo $pid;?>)">Remove</a></td></tr>            <?php									}			?>				<tr><td><b>Order Total: $<?php get_order_total();?></b></td><td colspan="5" align="right"><input type="button" value="Clear Cart" onclick="clear_cart()"><input type="button" value="Update Cart" onclick="update_cart()"><input type="button" value="Place Order" onclick="window.location='billing.php'"></td></tr>			<?php            }			else{				echo "<tr bgColor='#FFFFFF'><td>There are no items in your shopping cart!</td>";			}		?>        </table>    </div></form></body></html>

and this db.php

<?php	$connect = mysqli_connect("localhost","root","abcdefghi") or die("Demo is not available, please try again later");	@mysqli_select_db($connect,"cart_test") or die("Demo is not available, please try again later");	session_start();?>

please see on function.php code:

 

I had add :

 

global $connect;global $pid;

 

on function get_product_name($pid) and on function get_price($pid)

 

it can generate session but product name and price not display please see image on attachment :

post-55622-0-88515000-1417952307_thumb.png

 

This code is about shopping cart and actually I got this code from : http://www.qualitycodes.com/tutorial.php?articleid=25&title=Tutorial-Building-a-shopping-cart-in-PHP

 

please someone help me

 

Thanks

 

 

Link to comment
Share on other sites

Q : So, what I must do so that it can be pass the value?

 

this code work well on mysql tags, but after I change on mysqli this code didn't work.

 

please help me

 

Thanks

Edited by gong
Link to comment
Share on other sites

Just pass the parameter. Don't declare it as global. If you have this function:

function func($test1) {  global $test1;  ...}
Does $test1 hold the value that was passed to the function, or does it hold the value of a global variable? It can't hold both. If you're passing values, don't say they are actually global variables.
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...