ConorMcC ConorMcC - 1 year ago 61
MySQL Question

PHP MYSQL: display contents of table then add into another table

I am developing a wish list website using PHP and MySQL that displays products in a table. The user has the option to add each product to their own wish list.

I can display the products no problem but once the user clicks on the option to add to their own list I am getting nothing. The server I am running on also does not flag an error so I have no idea what I am doing wrong.

Any help would be greatly appreciated. I have included the code below.

//connect to db

//get results from db
$result = mysql_query("SELECT * FROM coffee_machines")
or die(mysql_error());

echo "<table border= '1' cellpadding='10'>";
echo "<tr> <th>ID</th> <th>Brand</th> <th>Description</th> <th>Price(£)</th> <th>image</th> </tr>";

$img_url = "http://localhost:8080/";
//loop through results of db query so items are displayed
while($row = mysql_fetch_array($result)){

// echo out contents of each row
echo '<tr>';
echo '<tr>';
echo '<td>'.$row["Product_ID"].'</td>';
echo '<td>'.$row["Brand"].'</td>';
echo '<td>'.$row["Description"].'</td>';
echo '<td>'.$row["Price"].'</td>';
echo '<td>'.'<img src="'.$img_url.$row['image'].'" /></td>';
echo '<td>'.'<a href = "?Add To List">Add To List</a></td>';
echo '</tr';
echo '</tr';

$add_to_list = "INSERT INTO andrew VALUES('".$row["Product_ID"]."', '".$row["Brand"]."', '".$row["Description"]."', '".$row["Price"]."', '".$row["image"]."')";
if(isset($_POST['Add To List'])){
//close table
echo "</table>";

Answer Source
  • You should change $_POST['Add To List'] to $_GET['Add To List'] since a click in a link generates a GET request.
  • with ?Add To List you are creating a variable, and you should not create variable names with spaces
  • you are not passing an id as a parameter or any way of identifying the specific row, so if the user clicks the link, the variable will be set and for all the elements on the loop will be an insertion in the andrew table. you should receive the id and make a new query to the db

A quick example, your link should be:

echo '<td>'.'<a href = "?id='.$row["Product_ID"].'">Add To List</a></td>'; 

then place your if out of the loop, like


    $result = mysql_query("SELECT * FROM coffee_machines Where id=".$_GET['id']." LIMIT 1");
    $row = mysql_fetch_array($result); 
    if ($row) {
       $add_to_list = "INSERT INTO andrew VALUES('".$row["Product_ID"]."', '".$row["Brand"]."', '".$row["Description"]."', '".$row["Price"]."', '".$row["image"]."')";


but as have been said, you will try to look soon for a replacement for mysql_* functions

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download