New programmer here, I asked a similar question last night but thought I should make a new question with updated attributes.
The code below is based on an old tutorial that I have been modifying. When I run a test script off the mysql connection script it shows me that it does connect to the database and shows the one test table I created to set this up. Table was made with PHPmyadmin and has the Primary key as id.
- The variables in the lower part of the document come back as undefined, I'm assuming because it is not validating or inserting the data from my table correctly? I've tried removing the while loop and seem to get the same result each time. Does anyone have any other ideas on this one?
- Secondly I just recently found out about SQL Injection and have tried modifying the code in such a way to adhere to these sanitation protocols. Could some nice fellow inform me of anything I am doing incorrectly or something further I need to make the code more secure?
<?php
if (isset($_GET['id'])) {
include 'storescripts/mysqli.php';
$id = preg_replace('#[^0-9]#i', '', $_GET['id']);
$query = $mysqli->prepare("SELECT * FROM products WHERE id='?' LIMIT 1");
$query->bind_param("s", $id);
$query->execute();
$sql = $query->get_result()->fetch_assoc();
$productCount = mysqli_num_rows($sql);
if ($productCount > 0) {
while($row = mysqli_fetch_array($sql)){
$product_name = $row["product_name"];
$price = $row["price"];
$details = $row["details"];
$category = $row["category"];
$subcategory = $row["subcategory"];
}
} else {
echo "That item does not exist.";
exit();
}
} else {
echo "Data to render this page is missing.";
exit();
}
?>
<!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><?php echo $product_name; ?></title>
<link rel="stylesheet" href="style/style.css" type="text/css" media="screen" />
</head>
<body>
<div align="center" id="mainWrapper">
<?php include_once("template_header.php");?>
<div id="pageContent">
<table width="100%" border="0" cellspacing="0" cellpadding="15">
<tr>
<td width="19%" valign="top"><img src="inventory_images/<?php echo $id; ?>.jpg" width="142" height="188" alt="<?php echo $product_name; ?>" /><br />
<a href="inventory_images/<?php echo $id; ?>.jpg">View Full Size Image</a></td>
<td width="81%" valign="top"><h3><?php echo $product_name; ?></h3>
<p><?php echo "$".$price; ?><br />
<br />
<?php echo "$subcategory $category"; ?> <br />
<br />
<?php echo $details; ?>
<br />
</p>
<form id="form1" name="form1" method="post" action="cart.php">
<input type="hidden" name="pid" id="pid" value="<?php echo $id; ?>" />
<input type="submit" name="button" id="button" value="Add to Shopping Cart" />
</form>
</td>
</tr>
</table>
</div>
<?php include_once("template_footer.php");?>
</div>
</body>
</html>