Random.dmx Random.dmx - 29 days ago 9
MySQL Question

How to pass table id to another table in PHP

There are

02
tables called
item
and
customer
.

item(item_id, item_name)
customer(cus_id, iid, cus_name)


I just tried to store
item_id
from
item
to the
iid
in the
customer
.
but it always showing
null
values.
My database is
item_sales
.

Here is my PHP code

<html>
<title></title>
<head></head>
<body>

<?php
$hostname = "localhost";
$database = "item_sales";
$username = "root";
$password = "";

$con = mysql_pconnect($hostname, $username, $password);

error_reporting(0);

?>

<form action="index.php" method="post" enctype="multipart/form-data">

<p>Customer Name : <input type="text" name="cus_name" /><br/><br/> </p>
<p>Select an Item:
<select name="iid">
<?php
$sql = mysql_query("SELECT * FROM item");
mysql_select_db($database,$con);
while($sqlv = mysql_fetch_array($sql))
{ ?>
<option id="<?php echo $sqlv['item_id']; ?>"><?php echo $sqlv['item_name']; ?></option>
<?php } ?>
</select>
</p>

<?php

if(isset($_POST['submit']))
{
$sql2 = "SELECT * FROM item WHERE iid='%item_id%'";
mysql_select_db($database,$con);
$mydata = mysql_query($sql2);

$cus_name = $_POST['cus_name'];


$sql3 = "INSERT INTO customer (cus_id, iid, cus_name) VALUES ('', '$_POST[iid]', '$cus_name')";
mysql_query($sql3);

}
?>



<input type="submit" name="submit" value="Add Sale" />
</form>


</body>
</html>

Answer Source

The correct code is following :

<html>
<title></title>
<head></head>
<body>

<?php 
$hostname = "localhost";
$database = "item_sales";
$username = "root";
$password = "";

$con = mysql_pconnect($hostname, $username, $password);

error_reporting(0);

?>

<form action="index.php" method="post" enctype="multipart/form-data">

<p>Customer Name : <input type="text" name="cus_name" /><br/><br/>  </p>
<p>Select an Item: 
<select name="iid">
        <?php
            $sql = mysql_query("SELECT * FROM item");
            mysql_select_db($database,$con);
            while($sqlv = mysql_fetch_array($sql)) 
            { ?>
                <option value="<?php echo $sqlv['item_id']; ?>"><?php echo $sqlv['item_name']; ?></option>
            <?php } ?>
    </select>
    </p>

  <?php

  if(isset($_POST['submit']))
  {
        $sql2 = "SELECT * FROM item";
        mysql_select_db($database,$con);
        $mydata = mysql_query($sql2);

        $cus_name = $_POST['cus_name'];
        $iid = $_GET['item_id'];


        $sql3 = "INSERT INTO customer (cus_id, iid, cus_name) VALUES ('', '$_POST[iid]', '$cus_name')";
        mysql_query($sql3);

    }
    ?>



    <input type="submit" name="submit" value="Add Sale" />
 </form>


 </body>
 </html>