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...
Related
I have a query which is not inserting if i use the where clause, without the where clause it inserts data. this is weird and I have never seen it happen before in WAMP
$key=substr(md5(rand(0, 1000000)), 0, 5);
$key1="INSERT INTO login(key_id) VALUES('$key')
WHERE (email_id = '" . mysql_real_escape_string($_POST['email_id']) . "')"
if(mysql_query($key1))
{
$message = 'User Added!.';
echo "<SCRIPT>
alert('$message');
location='forgotpassword.php';
</SCRIPT>";
}
If I echo $_POST['email_id'] it does return valid result
INSERT and WHERE do not mix.
when INSERTing, you are creating a new record.
WHERE is used with SELECTing DELETEing or UPDATEing, when you have to specify a filter which rows you want to SELECT, DELETE or UPDATE.
if you want to INSERT a row, do not use WHERE.
if you want to change a row, use
$key1="UPDATE login SET key_id = '$key' WHERE
(email_id = '" . mysql_real_escape_string($_POST['email_id']) . "')";
Insert is only used on creating new record and where clause is only used if want to set any condition it is used with like select,update,delete.
Try this it will help:-
$key1="update login set key_id ='$key' WHERE
(email_id = '" . mysql_real_escape_string($_POST['email_id']) . "')";
I know #Franz-Gleichmann is already explained very well, whats wrong in your code.
You need to use UPDATE for updating data modified code:
$key1 = "UPDATE login SET key_id = '$key' WHERE
(email_id = '" . mysql_real_escape_string($_POST['email_id']) . "')";
Now i am adding two more points:
Please use mysqli_* or PDO, because mysql_* is deprecated and not available in PHP 7.
You missed the termination semi colon on the same line, i hope this is typo error.
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.
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.
Hey, I am wondering how to extract the data from a table in a database onto a table in a page (users.php),
For example:
I want to be able to get all of the usernames and all the id's from my database onto a table.
So if I have in my database:
1 - Fred
2 - Frank
3 - Margret
It will see that I have them user's and id's in the database and print them onto a table.
Any help would be great,
Thanks.
Connect to your database. Host is the location, like localhost if its on your computer, or on the same server as your code. User and Password are self explanatory.
mysql_connect("host", "user", "pass");
The name of the database you want to access.
mysql_select_db("database");
The actual mysql query.
$result = mysql_query('SELECT `User_Name`, `User_ID` FROM TABLE');
Sort it into an array
while($temp = mysql_fetch_array($result)
{
$id = $temp['User_ID'];
$array[$id]['User_ID'] = $id;
$array[$id]['User_Name'] = $temp['User_Name'];
}
Turn the array into a table. (You could skip the last step and go right to this one.
$html ='<table><tr><td>User ID</td><td>User Name</td></tr>';
foreach($array as $id => $info)
{
$html .= '<tr><td>'.$info['User_ID'].'</td><td>'.$info['User_Name'].'</td></tr>';
}
echo $html . '</table>';
Or, the formatting you wanted
$html ='User Id - User Name';
foreach($array as $id => $info)
{
$html .= $info['User_ID'].' - '.$info['User_Name'].'<br>';
}
echo $html;
(For this answer, I will use the mysqli extension -- you could also want to use PDO ;; note that the mysql extension is old and should not be used for new applications)
You first have to connect to your database, using mysqli_connect (And you should test if the connection worked, with mysqli_connect_errno and/or mysqli_connect_error).
Then, you'll have to specifiy with which database you want to work, with mysqli_select_db.
Now, you can send an SQL query that will select all data from your users, with mysqli_query (And you can check for errors with mysqli_error and/or mysqli_errno).
That SQL query will most likely look like something like this :
select id, name
from your_user_table
order by name
And, now, you can fetch the data, using something like mysqli_fetch_assoc -- or some other function that works the same way, but can fetch data in some other form.
Once you have fetched your data, you can use them -- for instance, for display.
Read the pages of the manual I linked to : many of them include examples, that will allow you to learn more, especially about the way those functions should be used ;-)
For instance, there is a complete example on the page of mysqli_fetch_assoc, that does exactly what you want -- with countries insteand of users, but the idea is quite the same ^^
You can do something like the following (using the built-in PHP MySQL functions):
// assuming here you have already connected to the database
$query = "SELECT id,username FROM users";
$result = mysql_query($query, $db);
while ($row = mysql_fetch_array($result))
{
print $row["id"] . " - " . $row["username"] . "\n";
}
which will give you (for example):
1 - Fred
2 - Frank
3 - Margret
Where I've put the print statement, you can do whatever you feel like there eg put it into a table using standard HTML etc.