Hi I am trying to display specific entries in a database by appending the variable name to a URL like:
echo '<td><a class="index_table" href="includes/view.php?id=$row[id]>$row[Orderno]">
and then in my view.php I have:
<?php
include 'connect.php';
//Display the Data//
$id=$_GET['id'];
$result=mysql_query("select * from Products where ID=$id");
$row=mysql_fetch_object($result);
echo "<table>";
echo "
<tr bgcolor='#f1f1f1'><td><b>ID</b></td><td>$row->ID</td></tr>
However the specific ID is not being passed to the script, and the table in view.php is blank. When changing the where clause to 'where id = '1' the correct product displays. So I know that this is working.
Many Thanks
Basic PHP syntax: Strings quoted with ' do not interpolate variable values:
echo '<td><a class="index_table" href="includes/view.php?id=' . $row['id'] . '>' . $row['Orderno'] . '">';
^^^^^^^^^^^^^^^^^^
note that you're wide open to SQL injection attacks and are just begging to get your server pwn3d.
First problem:
You have to put the array string indexes into a paranthesis:
echo '<td><a class="index_table" href="includes/view.php?id='.$row['id'].'">'.$row['Orderno'].'</a></td>';
^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^
Second problem:
Your ID in the URL could easily be replaced with '; DELETE FROM table # thus allowing an attacker to perform a SQL injection! Always sanitize any user input (POST) or GET parameters that takes a part in SQL queries:
$id = mysql_real_escape_string($_GET['id']);
or for that case (when an integer is expected)
$id = (int) $_GET['id'];
Suggestion: do not use mysql_* functions but use PDO with (real!) prepared statements or at least mysqli_* functions with proper input sanitization.
Two big issues here. First, your link is not working correctly because you are using single-quotes in your echo, meaning the variables are not interpolated, so you must change to something like either of the following:
echo "<td><a class=\"index_table\" href=\"includes/view.php?id={$row['id']}>{$row['Orderno']}\">";
or
echo '<td><a class="index_table" href="includes/view.php?id=' . $row['id'] . '>' . $row['Orderno'] . '">';
WARNING - SECURITY BREACH
In your later code you are leaving yourself open to SQL Injection attack; some references to what this is can be found at OWASP and Wikipedia, and are very important to learn about. To protect yourself, you must escape data before sending it to a query. Here are some ways to do that:
$id = mysql_real_escape_string($_GET['id']);
$result=mysql_query("select * from Products where ID = '$id'");
or
$id = $_GET['id'];
if (!ctype_digit((string)$id)) {
die('Invalid ID: ' . htmlentities($id));
}
$result=mysql_query("select * from Products where ID = '$id'");
In the first example, I use mysql_real_escape_string to make the data safe for embedding in a query (note that I also added quotes around the variable); in the second, I did a data check to make sure it contained only digits (note that the length should also be checked, but this is a quick example), and if it contained something other than digits, we spit out an error message and don't run the query.
Change your query like, I added two ' between $id
$result=mysql_query("select * from Products where ID='$id'");
And see.
You're not actually including the value of the $id variable in the query. Take a look at this answer for options on how to do this:
How can I prevent SQL injection in PHP?
PDO
$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');
$stmt->execute(array(':name' => $name));
foreach ($stmt as $row) {
// do something with $row
}
mysqli
$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with $row
}
You shouldn't put the GET variable directly into the query like that, you should do some sanity checks like checking it's numeric etc. to avoid sql injection.
No doubt you will have answers saying the mysql_ functions are deprecated aswell but I don't think that's relevant to the question.
In your link you have
<td><a class="index_table" href="includes/view.php?id=$row[id]>$row[Orderno]">
you don't have the right syntax for the array elements, try
<td><a class="index_table" href="includes/view.php?id=' . $row['id'] . '>' . $row['Orderno'] . '">
It looks like a malformed URL in the tag, plus PHP doesn't parse variables in single quoted strings. I think you just need this:
echo "<td><a class='index_table' href='includes/view.php?id=$row[id]'>$row[Orderno]</a></td>";
You don't need to change the code in view.php but I would recommend filtering the _GET variable this way:
$id = (int)$_GET['id'];
Try
echo "<td><a class='index_table' href='includes/view.php?id=".$row['id'].">".$row['Orderno']."'>";
and
<?php
include 'connect.php';
//Display the Data//
$id=$_GET['id'];
if(is_int($id))
{
$result=mysql_query("select * from Products where ID=$id");
$row=mysql_fetch_object($result);
echo "<table>";
echo "<tr bgcolor='#f1f1f1'><td><b>ID</b></td><td>$row->ID</td></tr>";
}
else
{
echo "<h1>Nice try silly... You aint hackin me!</h1>";
}
I also noticed in your original code you were missing some ending quotes and semi-colons. That may have been all that was wrong. But this should clear up your security issue and should work for your application
Good luck.
Related
<?php $daerah_ejen1 = "$_GET[daerah_ejen]";
$kumpulan_ejen1 ="$_GET[kumpulan_ejen]";
echo $daerah_ejen1;
echo $kumpulan_ejen1;
echo $kumpulan_ejen;
$sql= "SELECT * FROM data_ejen WHERE daerah_ejen= '$daerah_ejen1' AND kumpulan_ejen='Ketua Kampung' ORDER BY nama_ejen";
$result = mysql_query($sql) or #error_die("Query failed : $sql " . mysql_error());
?>
my url
laporan_kk_detail.php?daerah_ejen=HULU+LANGAT&kumpulan_ejen=Ketua Kampung
for output daerah_ejen variable has display,
but for kumpulan_ejen/kumpulan_ejen1 is not display.
i dont know where the problem
your quotes accessing $_GET variable is invalid. try this
<?php
$daerah_ejen1 = $_GET["daerah_ejen"];
$kumpulan_ejen1 =$_GET["kumpulan_ejen"];
and you should read something about security, because you can pass malicous code to your script!
edit:// you can have a look on this thread https://stackoverflow.com/questions/19539692/sanitizing-user-input-php
you are converting get values in string using double quotes so remove and try
$daerah_ejen1 = $_GET['daerah_ejen'];
$kumpulan_ejen1 =$_GET['kumpulan_ejen'];
also use mysql_real_escape_string() for prevent sql injection.
The quotes go around the parameter name. This is because $_GET[] is an associative array and its values are referenced using a string key
$daerah_ejen1 = $_GET['daerah_ejen'];
$kumpulan_ejen1 =$_GET['kumpulan_ejen'];
Always sanitize your parameter values before using them in a query to protect yourself against SQL injection.
$daerah_ejen1 = mysqli::real_escape_string($daerah_ejen1)
You face 2 problem on your code :
1st is :
$daerah_ejen1 = "$_GET[daerah_ejen]";
$kumpulan_ejen1 ="$_GET[kumpulan_ejen]";
replace it by this :
$daerah_ejen1 = $_REQUEST['daerah_ejen'];
$kumpulan_ejen1 =$_REQUEST['kumpulan_ejen'];
2nd is :
$sql= "SELECT * FROM data_ejen WHERE daerah_ejen= '$daerah_ejen1' AND kumpulan_ejen='Ketua Kampung' ORDER BY nama_ejen";
replace it by this :
$sql= "SELECT * FROM data_ejen WHERE daerah_ejen= '".$daerah_ejen1. "' AND kumpulan_ejen='Ketua Kampung' ORDER BY nama_ejen";
If you need to put the $_GET['name'] in double quotes, wrap it in {} brackets.
e.g.
$kumpulan_ejen1 ="{$_GET['kumpulan_ejen']}";
Also, as dbh pointed out, you only have $kumpulan_ejen1, not kumpulan_ejen.
In my first page I have
I have a query that returns tournaments names in a table in this format
echo "<td><a href='tournament.php'>" . $info['tournament'] . "</a></td>";
$info['tournament'] has the tournament name which when clicked takes me to the page tournament.php where I have this code
$data = mysql_query("SELECT team1,score1,team2,score2 FROM table where tournament='';") or die(mysql_error());
what i want is to have the value clicked in the previous page that linked to this one, in tournament='HERE' so that the query retrieve the data for that tournament
First, create ID for the tournament if you haven't already (I mean in the table) - it's a good practice. Then, you would have a link like this:
echo "<td><a href='tournament.php?id=".$info['id']."'>" . $info['tournament'] . "</a></td>";
Then, about your query: mysql functions are deprecated from PHP 5.5, and you are strongly encouraged to use PDO statements or mysqli.
But for that lesson, you would use something like that (read about filtering - in this case intval():
$tournament_id = intval($_GET['id']);
if($tournament_id > 0)
$data = mysql_query("SELECT team1,score1,team2,score2 FROM table where id = ".$tournament_id.";") or die(mysql_error());
You can change the link to supply the tournament name (or, even better, an id):
echo "<td><a href='tournament.php?tournament=".$info['tournament']."'>" . $info['tournament'] . "</a></td>";
In tournament.php you can now access tournament via:
$tournamentName = $_GET['tournament'];//Remember to check if it exists
You can then use $tournamentName in your query. Please remember to escape $tournamentName since it may contain malicious values.
Also consider switching from the mysqli_* functions. These are now deprecated. Consider PDO or mysqli. When switching to these it's also a good idea to look into prepared statements.
change your code to pass tournament to next page using get method
echo "<td><a href='tournament.php?tournament=" . $info['tournament'] . "'>".$info['tournament'] . "</a></td>";
and get on second page using this code
$data = mysql_query("SELECT team1,score1,team2,score2 FROM table where tournament='" . $_GET['tournament'] . "';") or die(mysql_error());
hope you get points...
I have a submission script that I wrote in PHP. It is used by multiple surveys at our organization. The surveys are created by other users. When they submit to the script, PHP puts the data into the appropriate table in MySQL. The error that I run into sometimes is that the user(s) update the form. They add a field, or rename an input and the script doesn't account for it since it expects everything to be the same. So, I am trying to find a way to make it accomodate for when a new field is added. Here is what I have:
if( mysql_num_rows( mysql_query("SHOW TABLES LIKE '".$survey."'"))){
echo "table exists";
$sql = "SELECT * FROM " . $survey . ";";
$result = mysql_query($sql)
or die(mysql_error());
$i=0;
while($row = mysql_fetch_row($result));{
echo $row[0];
foreach($_POST as $k => $v){
$i++;
if($k != $row[$i]){
$query = "ALTER TABLE " . $survey . " ADD " . $k . " VARCHAR(100);";
mysql_query($query)
or die(mysql_error());
}
}
}
}
I am used to doing while loops in JS, so I don't know if using i works here (actually, I know it doesn't work... because it doesn't work...). What I am trying to say is that if a key doesn't match a current field name, then add it to the table. How can I return $row correctly?
When I submit to the script it says:
Duplicate column name 'V4'
I have echo $row[0] but it returns a 1. Which is the is the int used in the primary key for the for the first record.
You have a ; at the end of your while loop declaration that shouldn't be there. Not sure if that is causing the problem as you don't say what the above code does do. Update the question if the ; is not the issue.
Your while loop declaration should look like this: while($row = mysql_fetch_row($result)) {
Also, as Marc B so diplomatically put it in a comment to your question, you should be escaping any user input that goes directly into a query.
The easiest way to do this is to use $survey = mysql_real_escape_string($survey), before your first use of $survey, as a start or switch to PDO/MySQLi and use input binding (prepared statements). Here are the prepared statements docs for PDO. More can, and should, be done to protect yourself, but the above is a good start.
I have an existing recordset that retrieves all the information from a table in mysql called $rrows. What I am hoping to do is to use this existing recordset within a new mysql query.
For example I have the following line that retrieves the "product code" from one table:
<?php echo $rrows['productcode']; ?>
I am trying to then gather the respective images from a new table using this productcode by something similar to:
<img src="<?php
mysql_select_db("dbname", $con);
mysql_set_charset('utf8');
$result = mysql_query("SELECT * FROM furnimages WHERE productcode='$rrows['productcode']'");
while($row = mysql_fetch_array($result))
{
echo '' . $row['photo'] . '';
}
mysql_close($con);
?>">
Can this be done? Originally I was going to LINK tables together to get all the information, but this doesnt work as some of the product codes in the main do not have corresponding data in the 'furnimages' table.....
Thanks in advance!
JD
sprintf() is your best friend here.
$sql = <<<sql
SELECT * FROM furnimages
WHERE productcode=%d
sql;
$result = mysql_query(sprintf($sql, $rrows['productcode']));
So, %d is the placeholder in the string to swap in the second argument in the call to sprintf();
%d denotes an integer placeholder; if $rrows['productcode'] is a string, use %s.
This is better than simply quoting value of the variable as it adds a type constraint which reduces the risk of nasty sql injection.
It also makes it eminently more readable.
Check out the PHP Data Objects extension, though, because that really is the only way forward for this type of thing.
I am having trouble with an SQL query that I have inserted into a piece of PHP code to retrieve some data. The query itself works perfectly within SQL, but when I use it within my PHP script it says "Error in Query" then recites the entire SQL statement. If I copy and paste the SQL statement from the error message directly into MySQL it runs with no errors.
From my research I believe I am missing an apostrophe somewhere, so PHP may be confusing the clauses, but I am not experienced enough to know where to insert them.
The query is using a variable called $userid which is specified earlier in the PHP script.
$sql= <<<END
SELECT sum(final_price)
FROM (
SELECT Table_A.rated_user_id, Table_B.seller, Table_B.final_price
FROM Table_A
INNER JOIN Table_B ON Table_A.id=Table_B.id
) AS total_bought
WHERE seller != $userid
AND rated_user_id = $userid
UNION ALL
SELECT sum(final_price)
FROM (
SELECT Table_A.rated_user_id, Table_C.seller, Table_C.final_price
FROM Table_A
INNER JOIN Table_C ON Table_A.id=Table_C.id
) AS total_bought
WHERE seller != $userid
AND rated_user_id = $userid
END;
After this section the script then goes on to define the output and echo the necessary pieces as per usual. I'm happy with the last part of the code as it works elsewhere, but the problem I am having appears to be within the section above.
Can anyone spot the error?
Edited to add the following additional information:
All of the fields are numerical values, none are text. I have tried putting '$userid' but this only makes the error display the ' ' around this value within the error results. The issue remains the same. Adding parenthasis has also not helped. I had done a bit of trial and erorr before posting my question.
If it helps, the last part of the code bieng used is as follows:
$result = mysql_query($sql);
if (!$res) {
die('Error: ' . mysql_error() . ' in query ' . $sql);
}
$total_bought = 0;
while ($row = mysql_fetch_array($result)) {
$total_bought += $row[0];
}
$total_bought = number_format($total_bought, 0);
echo '<b>Your purchases: ' . $total_bought . '</b>';
echo "<b> gold</b>";
You're checking !$res, it should be !$result:
$result = mysql_query($sql);
if (!$result) {
die('Error: ' . mysql_error() . ' in query ' . $sql);
}
I suppose, you're echo()ing the query somewhere and copy-pasting it from the browser. Could it be that the $userid contains xml tags? They wouldn't be displayed in the browser, you would have to view the page source to spot them.
you should test with $userid quoted, and parentheses around the two statements.
I'm assuming that rated_user_id is a numeric field, but what type is seller? If it's a character field, then $userid would have to be quoted as streetpc suggests.
Another thing to check is that you have at least one space after the end of your lines for each line of the query. That has tripped me up before. Sometimes when going from your editor/IDE to the database tool those problems are silently taken care of.