I have this code which permits me to pass a variable to another page, but the problem is i cannot seem to get that variable using the link. We have tried before, this same method and has worked.. could you please check it?
Thanks..
The link:
$sql="SELECT * FROM pianificazione";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
?>
<?php echo $row['job'] ?>
<?php echo '</br><br />'; }
?>
The page after the link:
include('menu.php');
$id=$_GET['job_id'];
$sql="SELECT * FROM attivita WHERE job_id='$id'";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
?>
<?php echo $row['attivita_da_promuovere'] ?>-<?php echo $row['attivita_tip_merc'] ?>-<?php echo $row['attivita_da_svolgere'] ?>-<?php echo $row['attivita_tip_personale'] ?>
You should be using:
$id = $_GET['id'];
You're also open to SQL injections... Either parse it as an INT:
$id = (int) $_GET['id'];
... or use prepared statements with PDO (instead of the default mysql functions that you're using, which are no longer recommended).
You're passing it as:
lista_attivita.php?&id=<?php echo $row['job_id'] ; ?>
And then looking for it as:
$id=$_GET['job_id'];
You should use:
$id=$_GET['id'];
In the URL that you're passing to the "page after link" you're setting "?id=xxx" as the parameter however in your script, your looking for "job_id".
Change the parameter to ?job_id= in your first script.
Two things.
1) FUNCTIONALITY
$id=$_GET['job_id'];
should be
$id=$_GET['id'];
since your link passes the variable id, not job_id:
lista_attivita.php?&**id**=<?php echo $row['job_id']
2) SECURITY
Never, NEVER insert user-input data directly into a SQL query. You are asking for headaches or worse. The $id on your receiving page should be validated and escaped prior to doing any lookup. If you expect a number, do something like this on the receiving page:
if (!is_numeric($_GET['id']))
{
// throw error
}
It's not a bad idea to query your DB for valid codes, put those in an array, then check that array to see if the passed value is found. This prevents user entered data from reaching your DB.
Something like this:
$q = "SELECT DISTINCT(id) FROM my_table WHERE display=1 ORDER BY id ASC";
$res = mysqli_query($dbx,$q);
while (list($_id) = mysqli_fetch_array)
{
$arr_valid_id[] = $_id;
}
Then,
if (in_array($_GET[id],$arr_valid_id[])
{
// do stuff
} else {
// throw error
}
Related
I am passing the following variables from a query through a link:
<a href="middle.php?name=<?php echo $name; ?>&id=<?php echo $id1; ?>&rowid=<?php echo $rowid; ?>&record=<?php echo $record; ?>">
The variables are being passed to this page:
session_start();
//$id = ($_GET['id']);
if (isset($_GET["record"])) {
$_SESSION["record"] = $_GET["record"];
}
if (isset($_GET["id"])) {
$_SESSION["id"] = $_GET["id"];
}
if (isset($_GET["rowid"])) {
$_SESSION["rowid"] = $_GET["rowid"];
}
if (isset($_GET["name"])) {
$_SESSION["name"] = $_GET["name"];
}
if (isset($_GET["store"])) {
$_SESSION["store"] = $_GET["store"];
}
and then users are redirected to this page where Im trying to use the assign the session variables to variables in the page like this:
session_start();
$id = $_SESSION[id];
$rowid = $_SESSION[rowid];
$name = $_SESSION[name];
$record = $_SESSION[record];
The variables arent accessible as I need them to be on this page. Am I missing quotes? What is the best way to use the session variables again?
FYI they're mainly being used in other queries like this:
"SELECT * FROM mgap_orders WHERE mgap_ska_id = '" . $_SESSION['id'] . "' AND mgap_status = 0 GROUP BY mgap_ska_report_category LIMIT 5";
Am I missing quotes?
Yes. You say you're accessing them like this:
$id = $_SESSION[id];
That should be this:
$id = $_SESSION['id'];
But even more to the point, why do you need to use session here at all? The way you describe the situation is:
User makes a request with query string values in the link.
In the response you forward the user to another page (presumably using the location header?).
On the last page the values need to be present.
If they're query string values, keep them as query string values in the redirect. So where you may have something like this:
header('Location: somePage.php');
you can include the values:
header('Location: somePage.php?name=' . $name');
and so on for the remainder of the values, just like you do when building the original link for the page which performs the redirect.
Also, while you don't show your data access, you do show your query which appears to be vulnerable to SQL Injection attacks. Ultimately the values you're using are coming from user input (query string) so you shouldn't directly concatenate them into SQL queries.
if(isset($_SESSION['admin'])) {
echo "<li><b>Admin</b></li>";
}
<?php
session_name('MYSESSION');
session_set_cookie_params(0, '/~cgreenheld/');
session_start();
$conn = blah blah
$query2 = 'Select Type from User WHERE Username = "'.$_SESSION['user'].'" AND Type =\'Admin\'';
$result2 = $conn->query($query2);
if($result2->num_rows==1) {
$_SESSION['admin'] = $result2;
}
?>
Hi, I'm trying to set this session variable but it doesn't seem to be setting, and i'm wondering if anyone can help. If session['admin'] isset it should echo the admin button.
But i'm not quite sure why? (I do have session start and everything on everypage, it's not a problem with that or any of the "You don't have php tags" I have checked the mysql query, and it does return something from my table. Any ideas please?
Your session_start(); should be at the top of the page before anything to do with the session variables.
From the docs:
When session_start() is called or when a session auto starts, PHP will call the open and read session save handlers.
Edit from comments:
<?php
session_name('MYSESSION');
session_set_cookie_params(0, '/~cgreenheld/');
session_start();
// Moved to start after answer was accepted for better readability
// You had the <?php after this if statement? Was that by mistake?
if(isset($_SESSION['admin']))
{
echo "<li><b>Admin</b></li>";
}
// If you have already started the session in a file above, why do it again here?
$conn = blah blah;
$query2 = 'Select Type from User WHERE Username = "'.$_SESSION['user'].'" AND Type =\'Admin\'';
// Could you echo out the above statement for me, just to
// make sure there aren't any problems with your sessions at this point?
$result2 = $conn->query($query2);
if($result2->num_rows==1)
{
$_SESSION['admin'] = $result2;
// It seems you are trying to assign the database connection object to it here.
// perhaps try simply doing this:
$_SESSION['admin'] = true;
}
?>
Edit 2 from further comments:
You have to actually fetch the fetch the data like this - snipped from this tutorial which might help you out some more:
$query = "SELECT name, subject, message FROM contact";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo "Name :{$row['name']} <br>" .
"Subject : {$row['subject']} <br>" .
"Message : {$row['message']} <br><br>";
}
But having said that, while we are talking about it, you would be better off moving away from the old mysql_* functions and move to PDO which is much better.
Move session_start(); to the top of the page. You are trying to retrieve sessions, where it's not loaded.
EDIT: Try echoing $_SESSION['admin'], if it even contains something. Also try debugging your if($result2->num_rows==1) code by adding echo('its working'); or die('its working'); inside it, to check if $result2 contains exactly 1 row, since currently it seems $result2 contains either more than 1 row or no rows at all.
I have a little test project set up so that when you click a wolves's name, it takes them to a page that I want to use to personalize information concerning whichever wolf they clicked on. The page is called wolf.php. I'm trying to using passing variable the $_GET method to assign the URL the wolves id, i.e www.testsite.com/wolf.php?id=1 but the page then displays nothing even though I do not get an error.
Here's the home page (home.php)
<?php
$username = $_SESSION['username'];
$result = #mysql_query("SELECT * FROM wolves WHERE owner = '$username'");
while($wolf = mysql_fetch_array($result))
{
echo "<a href= wolf.php?id=$wolf[id]>$wolf[name]</a>";
};
?>
Clicking this link takes me to www.testsite.com/wolf.php?id=1 (or whatever the id was). On wolf.php I have this:
<?php
$id = $_GET['id'];
$result = #mysql_query("SELECT name FROM wolves WHERE id = '$id'") or die("Error: no
such wolf exists");
echo .$result['name'].
;
?>
I'm not sure where I went wrong but this doesn't seem to be working. No information regarding the id of the wolf shows up. Thanks for help in advance.
Turn on error reporting with error_reporting(E_ALL); ini_set('display_errors', 1); in development so you see the fatal syntax errors in your code. It is also recommended to remove # error suppression operator from your mysql_*() calls.
You have syntax problems on the last line. Unexpected . concatenation operators:
// Wrong:
// Parse error: syntax error, unexpected '.'
echo .$result['name'].
;
// Should be:
echo $result['name'];
Next, you have not fetched a row from your query:
// mysql_query() won't error if there are no rows found. Instead you have to check mysql_num_rows()
$result = mysql_query("SELECT name FROM wolves WHERE id = '$id'") or die("Query error: " . mysql_error());
// Zero rows found, echo error message.
if (mysql_num_rows($result) < 1) {
echo "No such wolf.";
}
else {
// Row found, fetch and display.
$row = mysql_fetch_assoc($result);
echo $row['name'];
}
Note that this script is wide open to SQL injection. At a minimum, call mysql_real_escape_string() on your query input variables.
$id = mysql_real_escape_string($_GET['id']);
Ultimately, think about using PDO or MySQLi instead of the old mysql_*() functions, as they support prepared statements for greater security over manually escaping variables. The mysql_*() functions are planned for deprecation.
Firstly need fetch a result row.
Variant 1 - associative array (values are avialable as field names)
$result = mysql_fetch_assoc($result);
echo $result['name'];
Variant 2 - enumerated array (by index, started from zero)
$result = mysql_fetch_row($result);
echo $result[0];
<?php
$username = $_SESSION['username'];
$result = #mysql_query("SELECT * FROM wolves WHERE owner = '$username'");
You forgot the session_start(); at the begining. $username is "" and the sql maybe is returning 0 records.
In your second snippet you can't treat $result like it's an array; it's a resource identifier. To get an array, do:
$row = mysql_fetch_assoc($result);
echo $row['name'];
Also read about SQL injection vulnerability.
I'm having a little problem with passing a parameter for a query to another page.
I want to make the name of the restaurant a link that would pass the name of the product to process a query on the next page.
echo "<p class='p2'><a class='link' href='restaurant.php?name=". $row['name'] ."'><strong>". $row['name'] ."</strong></a>
on the restaurant page
<?php
require ("db.php");
$name = $_GET['name'];
$query = "SELECT * FROM restaurant WHERE name =\"$name\"";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
?>
but nothing is displayed.
Any idea what I'm doing wrong?
First, a note: you should pass an ID rather than the name, since certain characters aren't great in URLs.
Second, try using urlencode() on the name.
echo "<p class='p2'><a class='link' href='restaurant.php?name=". urlencode($row['name']) ."'><strong>". $row['name'] ."</strong></a>
Of course it won't display anything, because you don't have any print functions (echo, print, var_dump, ...) in your file.
Anyways, you probably thought that your query doesn't work. If so, try to echo your $row['name']. If everything's OK, check if your variable is set, but it probably isn't because you get null.
To fix that issue, use isset() or empty().
Example:
if(!empty($_GET['name'])) $name = $_GET['name'];
else die('Variable name is empty');
Try also to add ini_set('display_errors', true) to the top of your pages to see if there's any errors.
Note that your code is very insecure and vulnerable. Use mysql_real_escape_string() before executing queries.
Example:
$name = mysql_real_escape_string($_GET['name']);
There are not really and direct answers on this, so I thought i'd give it a go.
$myid = $_POST['id'];
//Select the post from the database according to the id.
$query = mysql_query("SELECT * FROM repairs WHERE id = " .$myid . " AND name = '' AND email = '' AND address1 = '' AND postcode = '';") or die(header('Location: 404.php'));
The above code is supposed to set the variable $myid as the posted content of id, the variable is then used in an SQL WHERE clause to fetch data from a database according to the submitted id. Forgetting the potential SQL injects (I will fix them later) why exactly does this not work?
Okay here is the full code from my test of it:
<?php
//This includes the variables, adjusted within the 'config.php file' and the functions from the 'functions.php' - the config variables are adjusted prior to anything else.
require('configs/config.php');
require('configs/functions.php');
//Check to see if the form has been submited, if it has we continue with the script.
if(isset($_POST['confirmation']) and $_POST['confirmation']=='true')
{
//Slashes are removed, depending on configuration.
if(get_magic_quotes_gpc())
{
$_POST['model'] = stripslashes($_POST['model']);
$_POST['problem'] = stripslashes($_POST['problem']);
$_POST['info'] = stripslashes($_POST['info']);
}
//Create the future ID of the post - obviously this will create and give the id of the post, it is generated in numerical order.
$maxid = mysql_fetch_array(mysql_query('select max(id) as id from repairs'));
$id = intval($maxid['id'])+1;
//Here the variables are protected using PHP and the input fields are also limited, where applicable.
$model = mysql_escape_string(substr($_POST['model'],0,9));
$problem = mysql_escape_string(substr($_POST['problem'],0,255));
$info = mysql_escape_string(substr($_POST['info'],0,6000));
//The post information is submitted into the database, the admin is then forwarded to the page for the new post. Else a warning is displayed and the admin is forwarded back to the new post page.
if(mysql_query("insert into repairs (id, model, problem, info) values ('$_POST[id]', '$_POST[model]', '$_POST[version]', '$_POST[info]')"))
{
?>
<?php
$myid = $_POST['id'];
//Select the post from the database according to the id.
$query = mysql_query("SELECT * FROM repairs WHERE id=" .$myid . " AND name = '' AND email = '' AND address1 = '' AND postcode = '';") or die(header('Location: 404.php'));
//This re-directs to an error page the user preventing them from viewing the page if there are no rows with data equal to the query.
if( mysql_num_rows($query) < 1 )
{
header('Location: 404.php');
exit;
}
//Assign variable names to each column in the database.
while($row = mysql_fetch_array($query))
{
$model = $row['model'];
$problem = $row['problem'];
}
//Select the post from the database according to the id.
$query2 = mysql_query('SELECT * FROM devices WHERE version = "'.$model.'" AND issue = "'.$problem.'";') or die(header('Location: 404.php'));
//This re-directs to an error page the user preventing them from viewing the page if there are no rows with data equal to the query.
if( mysql_num_rows($query2) < 1 )
{
header('Location: 404.php');
exit;
}
//Assign variable names to each column in the database.
while($row2 = mysql_fetch_array($query2))
{
$price = $row2['price'];
$device = $row2['device'];
$image = $row2['image'];
}
?>
<?php echo $id; ?>
<?php echo $model; ?>
<?php echo $problem; ?>
<?php echo $price; ?>
<?php echo $device; ?>
<?php echo $image; ?>
<?
}
else
{
echo '<meta http-equiv="refresh" content="2; URL=iphone.php"><div id="confirms" style="text-align:center;">Oops! An error occurred while submitting the post! Try again…</div></br>';
}
}
?>
What data type is id in your table? You maybe need to surround it in single quotes.
$query = msql_query("SELECT * FROM repairs WHERE id = '$myid' AND...")
Edit: Also you do not need to use concatenation with a double-quoted string.
Check the value of $myid and the entire dynamically created SQL string to make sure it contains what you think it contains.
It's likely that your problem arises from the use of empty-string comparisons for columns that probably contain NULL values. Try name IS NULL and so on for all the empty strings.
The only reason $myid would be empty, is if it's not being sent by the browser. Make sure your form action is set to POST. You can verify there are values in $_POST with the following:
print_r($_POST);
And, echo out your query to make sure it's what you expect it to be. Try running it manually via PHPMyAdmin or MySQL Workbench.
Using $something = mysql_real_escape_string($POST['something']);
Does not only prevent SQL-injection, it also prevents syntax errors due to people entering data like:
name = O'Reilly <<-- query will bomb with an error
memo = Chairman said: "welcome"
etc.
So in order to have a valid and working application it really is indispensible.
The argument of "I'll fix it later" has a few logical flaws:
It is slower to fix stuff later, you will spend more time overall because you need to revisit old code.
You will get unneeded bug reports in testing due to the functional errors mentioned above.
I'll do it later thingies tend to never happen.
Security is not optional, it is essential.
What happens if you get fulled off the project and someone else has to take over, (s)he will not know about your outstanding issues.
If you do something, finish it, don't leave al sorts of issues outstanding.
If I were your boss and did a code review on that code, you would be fired on the spot.