I am new to php and programming,, I have been following a tutorial but I've ran into a problem when trying to display the products onto a web page, This is the code am testing
<?php
if (isset($_GET['id'])) {
include "storescripts/connect_to_mysql.php";
$id = preg_replace('#[^0-9]#i', '', $_GET['id']);
$sql = mysql_query("SELECT * FROM products WHERE id='$id' LIMIT 1");
$productCount = mysql_num_rows($sql);
if ($productCount > 0) {
while($row = mysql_fetch_array($sql)){
$product_name = $row["product_name"];
$price = $row["price"];
$details = $row["details"];
$category = $row["category"];
$subcategory = $row["subcategory"];
$date_added = strftime("%b %d, %Y", strtotime($row["date_added"]));
}
} else {
echo "That item does not exist.";
exit();
}
} else {
echo "Data to render this page is missing.";
exit();
}
mysql_close();
?>
When I try to view the page through my browser I get the message "Data to render this page is missing"
I understand that it''s something to do with
if (isset($_GET['id'])) {
And am assuming maybe it's something to do with the 'id' But I cant work out how to fix it. Any pointers and help would be appreciated, sorry if this seems basic but like I said I am new and cant work this problem out. I've been trying all day
Thanks
Obviously, $_GET['id'] isn't set. If your link was something like http://www.example.com/index.php?id=32, it would be set.
Second, do not use GET/POST variables in queries without sanitising them!
And third, don't use mysql_query in the first place, but PDO or mysqli instead
When you see $_GET it's looking for a parameter in the URL. So:
http://localhost/yourphpscript.php?id=123
...is what it's expecting. Some ID must be defined in the URL.
You could try this code:
<?php
if (isset($_GET['id'])){ //Someone submitted a form or just prepended parameter to link
include "storescripts/connect_to_mysql.php"; //Include script with mysql connection
$id = preg_replace('#[^0-9]#i', '', $_GET['id']); //Sanitize input - remove everything besides numbers
$result = mysql_query("SELECT * FROM products WHERE id='$id' LIMIT 1"); //Execute query. Only 1 product because of LIMIT 1
if (mysql_num_rows($result)==1){ //If the product is found
$product = mysql_fetch_assoc($result) ; //Take the product
foreach ($product as $property => $value){ //Go through each property of product
echo "<div> {$property} : {$value} </div>" ;
}
}
} else {?>
<form method="get" action="<?php $_SERVER['PHP_SELF'] ; ?>">
<input type="text" name="id" />
<input type="submit" value="Submit product ID"/>
</form>
<?php
}
?>
Just ask if you have any questions.
learn to track your id. sanitize and check the url sending the id for correct value passed and again in the begining check the value as in
<?php
echo $_GET['id'];
?>
use this to know what it is your id value
Related
I am having a problem.
I am creating a script that allows a person to select a record by it's primary ID and then delete the row by clicking a confirmation button.
This is the code with the form:
"confirmdelete.php"
<?php
include("dbinfo.php");
$sel_record = $_POST[sel_record];
//SQL statement to select info where the ID is the same as what was just passed in
$sql = "SELECT * FROM contacts WHERE id = '$sel_record'";
//execute SELECT statement to get the result
$result = mysql_query($sql, $db) or die (mysql_error());//search dat db
if (!$result){// if a problem
echo 'something has gone wrong!';
}
else{
//loop through and get dem records
while($record = mysql_fetch_array($result)){
//assign values of fields to var names
$id = $record['ID'];
$email = $record['email'];
$first = $record['first'];
$last = $record['last'];
$status = $record['status'];
$image = $record['image'];
$filename = "images/$image";
}
$pageTitle = "Delete a Monkey";
include('header.php');
echo <<<HERE
Are you sure you want to delete this record?<br/>
It will be permanently removed:</br>
<img src="$filename" />
<ul>
<li>ID: $id</li>
<li>Name: $first $last</li>
<li>E-mail: $email</li>
<li>Status: $status</li>
</ul>
<p><br/>
<form method="post" action="reallydelete.php">
<input type="hidden" name="id" value="$id">
<input type="submit" name="reallydelete" value="really truly delete"/>
<input type="button" name="cancel" value="cancel" onClick="location.href='index.php'" /></a>
</p></form>
HERE;
}//close else
//when button is clicked takes user back to index
?>
and here is the reallydelete.php code it calls upon
<?php
include ("dbinfo.php");
$id = $_POST[id];//get value from confirmdelete.php and assign to ID
$sql = "SELECT * FROM contacts WHERE id = '$id'";//where primary key is equal to $id (or what was passed in)
$result=mysql_query($sql) or die (mysql_error());
//get values from DB and display from db before deleting it
while ($row=mysql_fetch_array($result)){
$id = $row["id"];
$email = $row["email"];
$first= $row["first"];
$last = $row["last"];
$status = $row["status"];
include ("header.php");
//displays here
echo "<p>$id, $first, $last, $email, $status has been deleted permanently</p>";
}
$sql="DELETE FROM contacts WHERE id = '$id'";
//actually deletes
$result = mysql_query($sql) or die (mysql_error());
?>
The problem is that it never actually ends up going into the "while" loop
The connection is absolutely fine.
Any help would be much appreciated.
1: It should not be $_POST[id]; it should be $_POST['id'];
Try after changing this.
if it does not still work try a var_dump() to your results to see if it is returning any rows.
if it is empty or no rows than it is absolutely normal that it is not working.
and make sure id is reaching to your php page properly.
Ok as you are just starting, take care of these syntax, and later try switching to PDO or mysqli_* instead of mysql..
Two major syntax error in your code:
Parameters must be written in ''
E.g:
$_POST['id'] and not $_POST[id]
Secondly you must use the connecting dots for echoing variables:
E.g:
echo "Nane:".$nane; or echo $name; but not echo "Name: $name";
Similarly in mysql_query
E.g:
$sql = "SELECT * FROM table_name WHERE id="'.$id.'";
I hope you get it..take care of these stuff..
I'm currently designing a shopping cart following a tutorial online.
I have followed as much as I can down to each detail, with some changes such as variable names etc changing.
I have checked through the code below, however when I clicked "Add To Cart" it doesn't display the added item in the side bar.
Any suggestions as to what the issue may be? (The code is only the segment relating to the sidebar, the products php is in a separate php file.)
<div id="sidebar">
<h1>Cart</h1>
<?php
if(isset($_SESSION['cart'])){
$sql = "SELECT * FROM products WHERE SKU IN(";
foreach($_SESSION['cart'] as $id => $value){
$sql .= $id. ",";
}
$sql = substr($sql,0,-1) . ") ORDER BY SKU ASC";
$query = mysql_query($sql);
while($row = mysql_fetch_assoc($query)){
?>
<p><?php echo $row['name']; ?><?php echo $_SESSION['cart'][$row['SKU']]['quantity']; ?></p>
Go To Cart
<?php
}
}else {
echo "<p>Your part is empty. <br />Please add some products</p>";
}
?>
</div>
Section of code from products PHP file which does the adding:
<?php
if(isset($_GET['action']) && $_GET['action'] == "add"){
$id = $_GET['id'];
if(isset($_SESSION['cart'][$id])){
$_SESSION['cart'][$id]['quantity']++;
} else {
$sql2 = "SELECT * FROM products WHERE SKU=$id";
$query2 = mysql_query($sql2);
if(mysql_num_rows($query2) != 0){
$row2 = mysql_fetch_array($qery2);
$_SESSION['cart'][$row2['SKU']] = array("quantity" => 1, "price" => $row2['price']);
} else {
$message = "This product ID is invalid";
}
}
}
?>
You have brackets in your query.
Change
$sql2 = "SELECT * FROM products WHERE SKU=[$id]";
to
$sql2 = "SELECT * FROM products WHERE SKU=$id";
My guess is that if(isset($_SESSION['cart'])) is returning false .. based on your code, nothing would be output if this is correct.
edit:
I see actually echo "<p>Your part is empty. <br />Please add some products</p>"; would be executed, but still - I don't see $_SESSION['cart'] being initialised/set anywhere..
Well it's been my very first initiative to build a dynamic page in php. As i'm a newbie in php, i don't know much about php programming. i've made a database named "dynamic" and it's table name "answer" after that i've inserted four fields namely 'id', 'A1','A2', 'A3'.
I inserted the value in id=1 which are A1=1,A2 and A3-0,
In id=2, i have inserted A1=0, A2=1, A3=0
In id-3, i have inserted A1 and A2=0 A3=1
So now what i wanted is whenever i will click on the link of id=1 then it will display the content of id=1 and so on...
What i've done so far are:-
$conn= mysql_connect("localhost","root", "");
$db= mysql_select_db("dynamic", $conn);
$id=$_GET['id'];
$sql= "select * from answer order by id";
$query= mysql_query($sql);
while($row=mysql_fetch_array($query, MYSQL_ASSOC))
{
echo "<a href='dynamic.php?lc_URL=".$row['id']."'>Click Here</a>";
if($row['A1']==1)
{
echo "A1 is 1";
}
else if($row['A2']==1)
{
echo "A2 is 1";
}
else if($row['A3']==1)
{
echo "A3 is 1";
}
else {
echo "Wrong query";
}
}
?>
When i've executed this codes then it is showing me the exact id and it is going to the exact id but the values has not been changing..
I want whenever i will click on the id then it will display the exact value like if i click on id=2 then it will echo out "A2 is 1" nothing else....
Can anyone please help me out?
I also have noticed about
$id=$_GET['id'];
what is it and how to use it. Can anyone explain me out..
Thanks alot in advance:)
It may be best to start here to get a good understanding of php, before diving so deep. But to answer the specific questions you asked here...
The php $_GET variable is defined pretty well here:
In PHP, the predefined $_GET variable is used to collect values in a
form with method="get".
What this means is that any parameters passed via the query string (on a GET request) in the URL will be accessible through the $_GET variable in php. For example, a request for dynamic.php?id=1 would allow you to access the id by $_GET['id'].
From this we can derive a simple solution. In the following solution we use the same php page to show the list of items from the answer table in your database or single row if the id parameter is passed as part of the url.
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
$mysqli = new mysqli("localhost", "user", "password", "dynamic");
$query = 'SELECT * FROM answer';
if ($_GET['id']) {
$query .= ' WHERE id = '.$_GET['id'];
} else {
$query .= ' ORDER BY id';
}
$res = $mysqli->query($query);
if ($res->num_rows == 0) {
echo '<p>No Results</p>';
} else if ($res->num_rows == 1) {
// Display Answer
$row = $res->fetch_assoc();
echo '<h3>Answer for '.$row['id'].'</h3>';
echo '<ul>';
echo '<li>A1 = '.$row['A1'].'</li>';
echo '<li>A2 = '.$row['A2'].'</li>';
echo '<li>A3 = '.$row['A3'].'</li>';
echo '</ul>';
} else {
// Display List
echo '<ul>';
while ($row = $res->fetch_assoc()) {
echo '<li>Answers for '.$row['id'].'</li>';
}
echo '</ul>';
}
?>
</body>
</html>
OK, this might not be exactly what you are looking for, but it should help you gain a little better understanding of how things work. If we add a little javascript to our page then we can show/hide the answers without using the GET parameters and the extra page request.
<!DOCTYPE HTML>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<?php
$mysqli = new mysqli("localhost", "user", "password", "dynamic");
$query = 'SELECT * FROM answer ORDER BY id';
$res = $mysqli->query($query);
if ($res->num_rows == 0) {
echo '<p>No Results</p>';
} else {
// Display List
echo '<ul>';
while ($row = $res->fetch_assoc()) {
echo '<li>Answers for '.$row['id'].'';
echo '<ul id="answers_'.$row['id'].'" style="display:none;">';
echo '<li>A1 = '.$row['A1'].'</li>';
echo '<li>A2 = '.$row['A2'].'</li>';
echo '<li>A3 = '.$row['A3'].'</li>';
echo '</ul>';
echo '</li>';
}
echo '</ul>';
}
?>
<script>
function toggleAnswers(answer) {
$('#answers_' + answer).toggle();
}
</script>
</body>
</html>
There are many more solutions, each more complicated that what I've presented here. For example we could set up an ajax request to load the answers into the list page only when an item is clicked. My advice is to go through some beginner tutorials on php and look at some of the popular PHP frameworks: Zend, CodeIgniter, CakePHP, etc. Depending on what you overall goal is, one of these might really help you get there faster.
Be warned that the code provided here is only an example of how to accomplish what you were asking. It definitely does not follow all (if any) best practices.
I'm working on a small board/forum. I have topic posting done; it's visible in the database and all that jazz. Now I'm working on retrieving the topic list and so that when you click a topic you can view it. That's working fine, except that when I click on it the page goes blank and nothing is being shown. I know the issue is that I can't get the id of the post I clicked on because it's in the if-else statement with a while loop. Here is my code now.
<?php
require('init.php');
$get_threads = mysql_query("SELECT * FROM GOT ORDER BY time");
if (!isset($_GET['view_thread'])) {
$get_threads = mysql_query("SELECT * FROM GOT ORDER BY time");
while ($select_threads = mysql_fetch_assoc($get_threads)) {
$title = $select_threads['title'];
$time = $select_threads['time'];
$user = $select_threads['user'];
$id = $select_threads['id'];
$form = '<center>
<form method="get" action="">
<input type="submit" name="view_thread" id="view_thread" value="'.$title.'" />
<input type="hidden" name="thread_id" id="thread_id" value="'.$id.'" />
</form>
</center>';
echo '<div id="post_info">'.$form.'<hr>Posted by: <b>'.$user.'</b> '.$time.'</div>';
}
} else {
$get_posts = mysql_query("SELECT * FROM GOT WHERE id='$id'");
$select_posts = mysql_fetch_assoc($get_posts);
$content = $select_posts['content'];
echo $content;
}
?>
I need to get that $id so I can grab the post and later all the replies from the database. I'm new to php so I'm probably missing something. Thanks for any help!
first: your parameter is named "thread_id", so your query should be
$get_posts = mysql_query("SELECT * FROM GOT WHERE id='$thread_id'");
BUT i strongly suggest to
go for POST instead of GET
use mysql_real_escape to avoid SQL injection
I have looked through similar problems and solution but somehow only half way help me with my problem. I'm trying to make a form to checked more than one record from MySQL database and display the checked record to another page. Somehow I managed to do the page with check boxes but I don't know how to display the record checked. It can only display the first row of the record or all the records regardless which box are checked.
This is checkbox page
$columns = count($fieldarray);
//run the query
$result = mysql_query(
"SELECT * FROM request_item
ORDER BY request_item.IllNo DESC LIMIT 0, 6") or die(mysql_error());
$row = mysql_num_rows($result);
while($row=mysql_fetch_array($result))
{
{
$rows[] = $row['IllNo'];
}
foreach($rows as $value);
echo "";
echo " ";
echo $row['IllNo'];
echo "";
}
echo "";
?>
This is display record checked
$columns = count($fieldarray);
//run the query
$result = mysql_query(
"SELECT * FROM request_item
ORDER BY request_item.IllNo DESC LIMIT 0, 6") or die(mysql_error());
$row = mysql_num_rows($result);
while($row=mysql_fetch_array($result))
{
$rows[]=$row['IllNo'];
foreach($rows as $value);
if ($rows= 'checked') {
echo "";
echo $value;
}
Any help are welcome. Thank you.
There's actually a lot of problems with that script including syntax errors, calling the wrong variable name, form not opening where it should, invoking PHP after you already have, etc...
To get a good answer to you, you should share what make $row['IllNo'] should equal to indicate if it should be checked or not.
I reformatted it a bit and this may give you a good start.
<form NAME ="form1" METHOD ="POST" ACTION ="dari.php">
<table>
<?php
$columns = count($fieldarray);
//run the query
$result = mysql_query("SELECT * FROM request_item ORDER BY request_item.IllNo DESC LIMIT 0, 6") or die(mysql_error()) ;
$row = mysql_num_rows($result);
while($row=mysql_fetch_array($result)) {
echo "<tr><td>";
echo "<Input type = 'Checkbox' Name ='ch1' value ='ch1'";
// check checked if it is. this will be checked if $row['IllNo'] has a value
// if there were a condition to make it checked, you would put the condition
// before the ?
echo $row['IllNo'] ? ' checked' : '';
echo ' />';
echo $row['IllNo'];
echo "</td></tr>";
}
?>
</table>
<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Choose your books">
</FORM>