Hi guys I am new in php I just started learning it I am making a simple e-commerce website using xampp local server I am facing this problem when i use get method for retrieving the specific id of a row:
if (isset($_GET['id'])) {
$id = mysqli_real_escape_string($_GET['id']);
$sql = "SELECT * FROM items WHERE id= '$id'" ;
$run = mysqli_query($conn, $sql) or die ('error');
while($row=mysqli_fetch_array($run, MYSQLI_ASSOC)){
$discounted_price = $row['item_price'] - $row['item_discount'];
echo "
<div class='col-md-6'>
<h3 class='pp-title'>$row[item_title]</h3>
<img src='$row[item_image]' class='img-responsive' >
<div class='bottom'>
<div class='pull-right cutted-price text-muted'><del>$ $row[item_price]</del></div>
<div class='clearfix'></div>
<div class='pull-right disscounted-price'>$$discounted_price</div>
</div>
<h4 class='pp-dsc-title'>Description</h4>
<div class='pp-dsc-detail'>$row[item_description]</div>
</div>
";
}
}else {
echo "The request is not working";
}
The URL I am trying to access this on is below:
http://localhost/ec/items.php?item_title%20=%20Beautiful-brown-Watch&id%20=%201
I am getting the else output "the request is not working" if i remove the if statement from above and simply write in the query id = '1' or '2' the data appear on web page but when i do for a specific id it doesn't work i use mysqli_real_escape_string for get rid of SQL injection if that is not proper way to get rid of SQL injection then guide me.
You are checking for the $_GET variable id yet you are passing in the parameter item_id according to your link.
In addition to this you also have extra spaces in your query string parameters which is causing the strange %20 you are seeing in your URL, so please strip these out.
To get this working, you either need to change your URL to:
http://localhost/ec/items.php?item_title=Beautiful-brown-Watch&id=1
Or update your code to:
if(isset($_GET['item_id'])) {
$id = mysqli_real_escape_string($_GET['item_id']);
You also need to check out parameterized queries as mysqli_real_escape_string() is not the way to keep yourself safe.
A great post on this can be found here How can I prevent SQL injection in PHP?
Your code expect a parameter called id while you pass one called item_id change your URL to
http://localhost/ec/items.php?item_title=Beautiful-brown-Watch&id=1
And it should work.
Also note that when creating URL you should not include any space.
Related
This question already has answers here:
Escape double quotes with variable inside HTML echo [duplicate]
(3 answers)
Closed 1 year ago.
First want to start off by saying that I am still a beginner developer but have gotten a long way in a short time and I am somewhat stumped. And yes I know my code might not be pretty in layout, but still learning, at least things are working.
I am creating something that is like a client portal for shows. A client signs up to do a show from an intake form. When they submit the form, it goes to Monday.com, creates a folder and sub folder in dropbox and then inserts everything into my Mysql database. I also then have another page (Assets) where they can upload files based on the show. Now if they have signed up for multiple shows, at the top of this page I have a dropdown box that grabs all the shows that is assigned to their used id. When they click on the show that they want to add files to and then click the "Choose Show For Asset Upload" button it goes back to the database to retrieve the dropbox path and the file request url and puts it into the code where those variables are assigned. So, everything is working great except when it comes to a show that has a single quote (apostrophe). I noticed this when I added a test show and everything went bonkers. I was able to figure everything out when it comes to making it correct in the code for Monday and Dropbox and even INSERTing it into the database. In the database column it has "Michael's" instead of "Michael\'s", so it's exactly how it should be in there. In the dropdown it actually shows "Michael's" but yet when I do an echo after clicking the button it shows "Michael" So that single quote is definitely the issue and this is where I don't know how to fix it, after much searching through the net.
In the dropdown it lists (Show Test, Did I Really Do It!!, Dudley, The Amazing MA, Lets See If This Works, Michael's).
Code is:
<div class="topdiv">
<h2 style="text-align: center;">Assets Upload</h2><br>
</div>
<?php
$userid = $_SESSION["userid"];
$sql = "SELECT * FROM intake WHERE userid = ?;";
$stmt = mysqli_stmt_init($con);
if(!mysqli_stmt_prepare($stmt, $sql)){
echo "There was an internal error!";
exit();
} else {
mysqli_stmt_bind_param($stmt, "s", $userid);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
}
?>
<form class="formcenter" action="assets.php" method="post">
<select name="show" id="show">
<?php
while ($rows = mysqli_fetch_assoc($result)) {
$show = $rows['showtitle'];
echo "<option value='$show'>$show</option>";
}
?>
</select>
<input type="submit" name="chooseShow" value="Choose Show For Asset Upload"><br><br>
</form>
<?php
if(isset($_POST["chooseShow"])) {
$showTitle = $_POST["show"]; //WHEN I DO AN ECHO OF THIS IT SHOWS "MICHAEL" NOT "MICHAEL'S"
$sql = "SELECT * FROM intake WHERE userid = ? and showtitle = ? ;";
$stmt = mysqli_stmt_init($con);
if(!mysqli_stmt_prepare($stmt, $sql)){
echo "There was an internal error!";
exit();
} else {
mysqli_stmt_bind_param($stmt, "ss", $userid, $showTitle);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$rows = mysqli_fetch_assoc($result);
$path = $rows['dbxPath'];
$requestURL = $rows['requestURL'];
echo $show; //THERE JUST TO SEE WHAT IT WAS OUTPUTTING
echo $showTitle; //THERE JUST TO SEE WHAT WAS OUTPUTTING
}
}
?>
When I do the two echos at the end of the code $show = "Michael's" and $showTitle = "Michael". So I do know that the correct way is coming through but just can't grab it to put in the last $sql variable to use as the $showTitle Granted, I am assuming the $show is showing "Michael's" because it's the last show in the loop. BUT when I tested $show instead of $showTitle in the mysqli_stmt_bind_param statement it actually worked, so I know it's possible. Just need to know how to get the full "Michael's" into my $showTitle variable.
Thank you for taking the time to look through this longwinded (trying to give you as much info as possible) question and appreciate any help and advice.
-Michael
Your problem is here:
echo "<option value='$show'>$show</option>";
The single quotes in the variable $show are interfering with the single quotes wrapping the value.
Change it to this:
echo '<option value="'.$show.'">'.$show."</option>";
This explicitly concatenates the parts of the string rather than interpolating it. It gives better control over what quotes are used and where.
Edit 3: I figured I should try to word, not only my issue but also my end goal better... so here it goes. I need data to be returned to the user by their input. What they put into the form, will return specific data from the database or nothing at all. The database I'm using is information on field reps. When the user enters into the form, they will be looking for specific information. The number they will be asked for will be the repID number. Now... the problem I am having is taking the number that is put into the form, and calling that specific data from the database. The user will not be able to see other data, not associated with other repID's.
Okay, I'm pretty sure I'm not supposed to just delete my entire initial post, but I'm still searching for an answer. Now, I would assume it should be relatively simple, however it has turned out to more taxing than I had originally thought. Perhaps I am not explaining my needs clear enough, I do tend to have that issue a lot.
Here it goes... How to Run sql Query with button click 2.0:
I have a database written in sql and stored on a server. The table I will be accessing is called dataRep and houses Rep Data. This data is user input via form submission. Upon coming to the website there is an option to "View Rep Information" by submitting the Rep's ID that was given. That Rep ID will be the auto increment repID from the table. Upon clicking the button, it opens a new window that should display the rep's data. It does not, however.
Here is the html the user will see:
<div class="pop_box">
<a class="rms-button" href="#popup1">Enter Rep Number Here</a> </div>
<div id="popup1" class="overlay">
<div class="popup">
<a class="close" href="#">×</a>
<div align="center"><br>
<br>
<p>Enter rep number in box below. Submission will open new window.</p>
<form method="get" action="/data/repPrepare.php" target="_blank" >
<input type="text" id="repSelect" name="repSelect" placeholder="Enter Rep Number Given Here" />
<button type="submit" class="newbutton">VIEW</button>
</form>
</div>
</div>
...changed the php a little, but now I get this error:
"Warning: mysqli_query() expects at least 2 parameters, 1 given on line 21
Unable to prepare statement: Query was empty"
<?php
$host = 'mhhost';
$user = 'myuser';
$pass = 'mypass';
$db = 'mydatabase';
$con = mysqli_connect($host,$user,$pass, $db);
//-------------------------------------------------------------------------
// 2) Query database for data
//--------------------------------------------------------------------------
$query = mysqli_query("SELECT * FROM dataRep WHERE repID = ?"); //query
$stmt = mysqli_prepare($con, $query)
or die("Unable to prepare statement: " . $con->error);
$stmt->bind_param("i", $_GET["repSelect"]);
$stmt->execute();
$array = mysqli_fetch_row($result); //fetch result
//-------------------------------------------------------------------------
// 3) echo result as json
//-------------------------------------------------------------------------
echo json_encode($array);
?>
I would like to apologize in advance if I'm totally messing up the procedure for the forum, its just I am truly stuck and have been dealing with this issue for two weeks. Once again, I would appreciate any assistance that can be provided. I just need the php to pull the data tied the repID that the user puts in the box (repSelect).
try like this. You have to print variables bind in bind_result().So
<?php
$stmt = $mysqli->prepare("SELECT repID, RepName, RepBio, RepCerts FROM dataRep WHERE repID = ?");
$stmt->bind_param('i', $_GET['repSelect']);
$stmt->execute();
$stmt->bind_result($repID, $repName,$repBio,$repCerts);
while($stmt->fetch()){
echo $repName;//now it prints RepName
};
$stmt->close();
?>
Sorry if my Title is crappy but I've looked everywhere and i just don't know how to do this.
OK. what i want to do is display information from a specific id from a table row.
first page
employees.php
<?php
require 'header.php';
require 'connect.php';
$sql1 = mysql_query("SELECT * FROM employees ORDER BY id ASC");
while($runrows = mysql_fetch_array($sql1)){
$employename = $runrows["employename"];
$minidescription = $runrows["minidescription"];
$bigdescription = $runrows["bigdescription"];
echo "
<!-- Employe Profile Start -->
<div class='ProfileWrap'>
<section class='Profile'>
<div class='HeadShot'>
<div class='Separator'></div>
<img width='90' height='136' alt='Employe Headshot' class='EmployeImage' src=img/headshots/".$runrows['images'] ." />
<div class='EmployeInfo'>
<legend class='EmployeName'>
<b>
Employe Name: $employename
</b>
</legend>
<div class='EmployeDes'>
<p>
Employe Descript $minidescription...
</p>
</div>
<a href='readmore.php?id=" .$id = $runrows["id"]. "' id='demo' alt='Read More'>
<div class='ReadMore'>
<b>
Read More
</b>
</div>
</a>
</div>
</div>
</section>
</div>
<!-- employe Profile End -->
";
} // close while loop
?>
<?php require 'footer.php'; ?>
second page
employe.php
<?php
require 'header.php';
require 'connect.php';
echo "<a href='index.php'>Back</a>";
$sql2 = mysql_query("SELECT * FROM employees WHERE id=$id");
while($runrows = mysql_fetch_array($sql2)){
$id = $runrows["id"];
$employename = $runrows["employename"];
$minidescription = $runrows["minidescription"];
$bigdescription = $runrows["bigdescription"];
echo "
<legend class='EmployeName'>
<b>
Employe Name: $employename
</b>
</legend>
<div class='EmployeDes'>
<p>
Employe Description: $bigdescription...
</p>
</div>
";
};
require 'footer.php';
?>
and you would click
[Read More]
then it would go to another page called readmore.php
"Click" [Read More] -> readmore.php?id=14 -> display specific info from that id from the database.
username
minidescription
->
click [Read More]
then it would show up like readmore.php?id=14 in the small address bar at the
bottom left
->
new page
->
largedescription
i want to be able to click on an item in a site that has a read more button and have it take me to another page where it displays the description info for that specific id
yes i realize I'm a complete newbie but I'm still learning and that was a crappy example of what i want to accomplish but i hope you understand what I'm trying to do none the less.
sorry if this already exists but I've looked everywhere and couldn't find what i was looking for. If someone has a link to share that can do what I've asked this question can just be deleted.
Thanks in Advance! hope someone can help me figure this out.
First, note #Matthew Johnson's answer about using Mysqli or PDO. Here are a few code specifics, though. When you generate the link to the page, you need this:
<a href='readmore.php?id=" . $runrows["id"] . "' id='demo' alt='Read More'>
Using $id = $runrows["id"] doesn't place the value into the url, it simply declares the value of the $id variable.
Then in your readmore.php file, the id can be capture from the URL using the $_GET array:
if (isset($_GET['id'])) {
$id = $_GET['id'];
}
The mysql_* functions are deprecated, and should no longer be used. Mysqli or PDO should be used, along with prepared statements. The code as you have it is susceptible to sql injection attacks. A simplified version of what you're trying to do would look something like this:
To Link:
//this gets all the name and mini, loops through and displays....
$stmt = $mysqli->prepare("SELECT id, employename, minidescription FROM employees");
$stmt->execute();
$stmt->bind_result($id, $employeename, $minidescription);
while($stmt->fetch()) {
echo "<p><a href='readmore.php?id=$id'>$employeename</a>: $minidescription</p>";
}
The Read More:
//make sure it's set, if so assign it...
$id = (isset($_GET['id']) ? $_GET['id'] : "";
//this gets the info using the id variable from the URL...
$stmt = $mysqli->prepare("SELECT employename, minidescription, bigdescription FROM employees WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($employeename, $minidescription, $bigdescription);
$stmt->fetch();
echo "$employeename: $bigdescription";
Using mysqli and prepared statements, as shown here, protects you against bobby tables and sql injection attacks. You can learn more about mysqli from the manual. Here's a tutorial with a quick run through of how prepared statements work.
Edit:
The code above still needs a database connection. The warning of an undefined variable is saying that the $mysqli variable hasn't been defined. The fatal error is due to the fact that the prepare statement failed. To create a connection, it would look similar to this:
define("HOST", "Host URL");
define("USER", "dbUser");
define("PASSWORD", "password");
define("DATABASE", "databaseName");
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
This would replace the code in your connect.php.
I wanted to expand my PHP skills so I read through a tutorial on tutorialzine. I understand the instructions presented in the tutorial. But when it comes to expanding on it I seem to be lacking a connection. My main goal was to simply delete a selected note when an a tag is clicked. However I don't know how to select the id assigned to the note to be able to pass it to my delete function.
Source: http://tutorialzine.com/2010/01/sticky-notes-ajax-php-jquery/
Thanks for the help.
<?php
error_reporting(E_ALL^E_NOTICE);
require 'connect.php';
mysql_query("DELETE FROM notes WHERE id>3 AND dt<SUBTIME(NOW(),'0 1:0:0')");
$query = mysql_query("SELECT * FROM notes ORDER BY id DESC");
$notes = '';
$left='';
$top='';
$zindex='';
while($row=mysql_fetch_assoc($query)){
list($left,$top,$zindex) = explode('x',$row['xyz']);
$notes.= '
<div class="note '.$row['color'].'" style="left:'.$left.'px;top:'.$top.'px;z-index:'.$zindex.'">
'.htmlspecialchars($row['text']).'
<div class="author">'.htmlspecialchars($row['name']).'</div>
<span class="data">'.$row['id'].'</span>
<a id="remove_note" href="javascript:;" onclick="deleteNote('<? echo $row['id']; ?>');"> </a>
</div>';
}
function deleteNote(id){
$sql="DELETE FROM notes WHERE id='$rows['id']'";
$result=mysql_query($sql) or die("Error when tryin to delete note.");
}
?>
Update:
I've been playing around with this and the answers that both Andrew and sachleen have provided. And ill plan to work on an AJAX alternative since you've mentioned the whole SQL Injection issue. But I am still having issues with passing the id to the remove.php file. I believe is has to do with how $notes is creating the information from the DB.
I say this because I get: Parse error: syntax error, unexpected T_STRING in /home/avonamyd/public_html/projects_php/sticky_notes/demo.php on line 24
And that is only when I include the code as is from sachleen. But when I update it to account for the single quotes I have the following code. The id is present and is passed to the remove.php file but I am still getting an error. This is when I use my code or what you've provided.
$notes.= '
<div class="note '.$row['color'].'" style="left:'.$left.'px;top:'.$top.'px;z-index:'.$zindex.'">
'.htmlspecialchars($row['text']).'
<div class="author">'.htmlspecialchars($row['name']).'</div>
<span class="data">'.$row['id'].'</span>
<a id="remove_note" target="_blank" href="remove.php?id='.$row['id'].'"> </a>
</div>';
Below is what I currently have in my remove.php file:
<?php
include 'connect.php';
$_GET['id'];
function deleteNote($id){
$sql="DELETE FROM notes WHERE id='$id'";
}
$result=mysql_query($sql) or die("Error when tryin to delete note.");
?>
Update
I've added in additional echo lines throughout the remove.php and this is what I am coming up with.
<?php
include 'connect.php';
$_GET['id'];
echo $id; --doesnt show
function deleteNote($id){
echo "hello"; --doesnt show
$sql="SELECT FROM notes WHERE id='$id'";
}
echo 'hello2'; --shows
$result=mysql_query($sql) or die("Error when tryin to delete note.");
?>
Update:
Thank you for everyone's help with this project I've finally gotten the concepts to click in my head after some tinkering around. I will post the functional code below for anyone else that stumbles upon this code. =D
Thx Everyone!
demo.php
error_reporting(E_ALL^E_NOTICE);
require 'connect.php';
mysql_query("DELETE FROM notes WHERE id>3 AND dt<SUBTIME(NOW(),'0 1:0:0')");
$query = mysql_query("SELECT * FROM notes ORDER BY id DESC");
$notes = '';
$left='';
$top='';
$zindex='';
while($row=mysql_fetch_assoc($query)){
list($left,$top,$zindex) = explode('x',$row['xyz']);
$id = $row['id'];
$notes.= '
<div class="note '.$row['color'].'" style="left:'.$left.'px;top:'.$top.'px;z-index:'.$zindex.'">
'.htmlspecialchars($row['text']).'
<div class="author">'.htmlspecialchars($row['name']).'</div>
<span class="data">'.$row['id'].'</span>
<a id="remove_note" target="_blank" href="remove.php?id='.$row['id'].'"> </a>
</div>';
}
remove.php
<?php
include 'connect.php';
$id = intval($_GET['id']);
$sql="DELETE FROM notes WHERE id=$id";
$result = mysql_query($sql) or die("Unable to delete database entry.");
?>
It looks like you are trying to mix JavaScript and PHP. You cannot call the deleteNote() function when your link is clicked because it is a PHP function. There are a couple of ways to go about calling the PHP script to delete the note:
Use something like the following:
<?php
// ...
$id_to_delete = $_GET['id'];
if( isset($id_to_delete) ) {
$sql="DELETE FROM notes WHERE id='$id_to_delete'";
$result=mysql_query($sql) or die("Error when tryin to delete note.");
}
$query = mysql_query("SELECT * FROM notes ORDER BY id DESC");
//...
while($row=mysql_fetch_assoc($query)){
//...
echo '<a id="remove_note" href="CURRENT_SCRIPT_URL?id=' . $id_to_delete . '">X</a>';
//...
}
?>
Or you could create a second script that deletes a row from the database based on the data that you pass to it and use ajax (I would recommend using jQuery for ajax functionality) to call that script with the id of the item to delete.
Remember that anyone could call your script with a GET parameter and delete a record from the database (or worse, perform an SQL injection attack), so make sure that you have some sort of safeguard in place unless you want all of your records wiped out!
You can't onclick a PHP function. You're mixing JavaScript with PHP. I would do this:
<a id="remove_note" href="remove.php?id=<?php echo $row['id']; ?>">Remove</a>
And then on remove.php get the ID using $_GET['id'] and pass that into the DELETE query.
you have 2 options.
1) make an <a href="another_php_script.php?delete=true"> (or similar), then run the delete script. (then header back to the same page you were on).
This is because you cannot run an onClick php function, you have to redirect to the other page.
2) You can use the onclick function to call an AJAX script, and execute the deleting PHP script from the page you're on - without redirecting.
Option 1 is the easy option, Option 2 is the better option to learn from.
Please could someone help im building my first website that pulls info from a MySQL table, so far ive successfully managed to connect to the database and pull the information i need.
my website is set up to display a single record from the table, which it is doing however i need some way of changing the URL for each record, so i can link pages to specific records. i have seen on websites like facebook everyones profile ends with a unique number. e.g. http://www.facebook.com/profile.php?id=793636552
Id like to base my ID on the primary key on my table e.g. location_id
ive included my php code so far,
<?php
require "connect.php";
$query = "select * from location limit 1";
$result = #mysql_query($query, $connection)
or die ("Unable to perform query<br>$query");
?>
<?php
while($row= mysql_fetch_array($result))
{
?>
<?php echo $row['image'] ?>
<?php
}
?>
Thanks
Use $_GET to retrieve things from the script's query (aka command line, in a way):
<?php
$id = (intval)$_GET['id']; // force this query parameter to be treated as an integer
$query = "SELECT * FROM location WHERE id={$id};";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) == 0) {
echo 'nothing found';
} else {
$row = mysql_fetch_assoc($result);
echo $row['image'];
}
There are many things to consider if this is your first foray into MsSQL development.
SQL Injection
Someone might INSERT / DELETE, etc things via using your id from your url (be careful!, clean your input)
Leaking data
Someone might request id = 1234924 and you expected id = 12134 (so some sensitive data could be shown, etc;).
Use a light framework
If you haven't looked before, I would suggest something like a framework (CodeIgniter, or CakePHP), mysql calls, connections, validations are all boilerplate code (always have to do them). Best to save time and get into making your app rather than re-inventing the wheel.
Once you have selected the record from the database, you can redirect the user to a different url using the header() function. Example:
header('Location: http://yoursite.com/page.php?id=123');
You would need to create a link to the same (or a new page) with the URL as you desire, and then logic to check for the parameter to pull a certain image...
if you're listing all of them, you could:
echo "" . $row['name'] . ""
This would make the link.. now when they click it, in samepage.php you would want to look for it:
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
//query the db and pull that image..
}
What you are looking for is the query string or get variables. You can access a get variable through php with $_GET['name']. For example:
http://www.facebook.com/profile.php?id=793636552
everything after the ? is the query string. The name of the variable is id, so to access it through your php you would use $_GET['id']. You can build onto these this an & in between the variables. For example:
http://www.facebook.com/profile.php?id=793636552&photo=12345
And here we have $_GET['id'] and $_GET['photo'].
variables can be pulled out of URL's very easily:
www.site.com/index.php?id=12345
we can access the number after id with $_GET['id']
echo $_GET['id'];
outputs:
12345
so if you had a list of records (or images, in your case), you can link to them even easier:
$query = mysql_query(...);
$numrows = mysql_num_rows($query);
for ($num=0;$num<=$numrows;$num++) {
$array = mysql_fetch_array($query);
echo "<a href=\"./index.php?id=". $row['id'] ."\" />Image #". $row['id'] ."</a>";
}
that will display all of your records like so:
Image #1 (links to: http://www.site.com/index.php?id=1)
Image #2 (links to: http://www.site.com/index.php?id=2)
Image #3 (links to: http://www.site.com/index.php?id=3)
...