Can anyone tell me how to pass the php values $value_aid and $value_tradeid to my sql query res3 please ?
<?php
//error_reporting(E_ALL);
///////////////////////Connect to the database and close the connection when finished///////////////////////////////
include ("dbconnect.php");
///////////////////////////////// Gather and Display area_id //////////////////////////////
$res=mysql_query("SELECT area_id FROM pc_test WHERE postcodes = '".$_POST['postcode']."'");
while ($row = mysql_fetch_array($res))
{
// This works !!
//echo("$row[area_id]");
$value_aid="$row[area_id]";
echo("$value_aid");
}
////////////////// Gather and Display postcodes relating to area_id ////////////////////////
$res3=mysql_query("SELECT trade_id FROM trade WHERE trade_type = '".$_POST['trade_type']."'");
while ($row3 = mysql_fetch_array($res3))
{
// And this works !!
echo("\n$row3[trade_id]");
$value_tradeid="$row3[trade_id]";
}
/**************************************** Gather the query information ********************************************/
//************!!!!!!!!!!!!!!!! This part does not work as the variable values are not being passed !!!!!!!!!!!**********//
$res2=mysql_query("SELECT first_name, last_name, phone_mobile, postcode, trade_type FROM customer WHERE area_id = '$value_aid' && trade_id = '$value_tradeid'");
/**************************************** DISPLAY QUERY RESULTS HERE *********************************************/
while ($row2 = mysql_fetch_array($res2))
{
echo("<TABLE align='center' border = '1' bgcolor = 'A7E3F6'><TH><strong>SEARCH RESULTS<strong></TH>");
echo("<TR><TD><strong>Name :<strong>\n$row2[first_name]\n$row2[last_name]</TD></TR>");
echo("<TR><TD><strong>Phone :<strong>\n$row2[phone_mobile]</TD></TR>");
echo("<TR><TD><strong>Postcode :<strong>\n$row2[postcode]</TD></TR>");
echo("<TR><TD><strong>Trade Type :<strong>\n$row2[trade_type]</TD></TR></TABLE>");
}
/*********************** If no matching records in my table...DISPLAY MESSAGE HERE ******************************/
if (mysql_num_rows($res2) == 0) {
echo ("<strong><br><br>No one is advertising for this area just yet, sorry.<br>We will have tradesmen advertising here very soon.</strong>");
}
//include ("db_close.php");
?>
first of all, dont pass variables you get from the user (_POST, _GET, ...) directly into Database queries without escaping them (e.g. mysql_real_escape_string($_POST['name']) this leads to massive security problems (SQL Injection)
to assign a variable with the value of a nother variable you simply use:
$value_tradeid = $row['trade_id'];
Variables doesnt need to be capsuled as strings, but array keys should !
On the queries which dont work, why you dont escape the strings, like you have done in the others obove.
$res2=mysql_query("SELECT first_name, last_name, phone_mobile, postcode, trade_type FROM customer WHERE area_id = '".$value_aid."' && trade_id = '".$value_tradeid."'");
you should also read about PDO and Prepared Statements.
Related
I am teaching myself php and MySQL, and right now I have a problem with MySQL.
I want to compare the phone number that the user put in with the phone number in MYSQL, and if it is in MYSQL to not register it again.
My code:
<?php
require_once 'connection/connection.php';
// Variables from HTML to php
$worker_Name = $_POST['workerNameFromHtml']; // worker Name
$worker_City = $_POST['workerCityFromHtml']; // workerCity
$worker_career = $_POST['workerCareerFromHtml']; // worker career
$worker_PhoneNumber = $_POST['workerPhonNumberFromHtml']; // worker Phone Number
$worker_SecondPhoneNumber = $_POST['workerSecondPhoneNumberFromHtml']; // worker Second Phone Number
$submt=$_POST['submitFromHtml'];
if($submt){
$qry = ( "SELECT workrPhoneNumber FROM workersTable WHERE workrPhoneNumber = '$worker_PhoneNumber'") or die(mysql_error());
$result = $connect->query($qry);
$num = $result->num_rows;
if ($num == 1) {
$here = "INSERT INTO workersTable VALUES('','$worker_Name','$worker_City','$worker_career','$worker_PhoneNumber','$worker_SecondPhoneNumber')";
$query = $connect->query($here);
print "Successfully added!";
}
else {print "This number has already been entered Thank you for your cooperation!";}}
$connect->close();
So far I have not found a solution to this problem.
your biggest problem here is that you are trying to include variables inside of a string.
"SELECT workrPhoneNumber FROM workersTable WHERE workrPhoneNumber = '$worker_PhoneNumber'"
If you want to do it this way, you need to concatenate your variables with your string.
"SELECT workrPhoneNumber FROM workersTable WHERE workrPhoneNumber = '".$worker_PhoneNumber."'"
Keep in mind if you do this you will want to sanitize your variables first to prevent SQL injections. Also, when you INSERT variables, you will actually want to use a prepared statement like this:
"INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...)"
where the 1st set of values are the names of your columns in the database and the second set are your PHP variables you are putting into it.
I'm building a simple bug tracking tool.
You can create new projects, when you create a project you have to fill in a form, that form posts to project.class.php (which is this code)
$name = $_POST['name'];
$descr = $_POST['description'];
$leader = $_POST['leader'];
$email = $_POST['email'];
$sql="INSERT INTO projects (name, description, leader, email, registration_date)
VALUES ('$name', '$descr', '$leader', '$email', NOW())";
$result = mysql_real_escape_string($sql);
$result = mysql_query($sql);
if($result){
header('Location: ../projectpage.php?id='.mysql_insert_id());
}
else {
echo "There is something wrong. Try again later.";
}
mysql_close();
(It's not yet sql injection prove, far from complete...)
Eventually you get redirected to the unique project page, which is linked to the id that is stored in the MySQL db. I want to show the name of that project on the page, but it always shows the name of the first project in the database.
(here I select the data from the MySQL db.)
$query = 'SELECT CONCAT(name)
AS name FROM projects';
$result = mysql_real_escape_string($query);
$result = mysql_query ($query);
(here I show the name of the project on my page, but it's always the name of the first project in the MySQL db)
<?php
if ($row = mysql_fetch_array ($result))
echo '<h5>' . $row['name'] . '</h5>';
?>
How can I show the name of the right project? The one that is linked with the id?
Do I have the use WHERE .... ?
Yes, You have to use the WHERE to specify which project You want to get. I'm also not sure why are You using CONCAT function when You want to get only one project.
Other important thing is that You have to use mysql_real_escape_string() function on parameters before You put them in the query string. And use apropriate functions for specific type of data You receive.
So Your statement for getting the project should look like this:
SELECT name FROM projects WHERE id = ' . intval($_GET['id'])
Also when before You use the mysql_fetch_assoc() function, check if there are any records in the result with
if(mysql_num_rows($result) > 0)
{
$project = mysql_fetch_assoc($result);
/* $project['name'] */
}
try this
// first get the id, if from the url use $_GET['id']
$id = "2";
$query = "SELECT `name` FROM `projects` WHERE `id`='".intval($id). "'";
$result = mysql_query(mysql_real_escape_string($query));
use mysql_fetch_row, here you'll not have to loop through each record, just returns single row
// if you want to fetch single record from db
// then use mysql_fetch_row()
$row = mysql_fetch_row($result);
if($row) {
echo '<h5>'.$row[0].'</h5>';
}
$row[0] indicates the first field mentioned in your select query, here its name
The might be of assistance:
Your are currently assing a query string parameter projectpage.php?id=
When you access the page the sql must pick up and filter on the query string parameter like this:
$query = 'SELECT CONCAT(name) AS name FROM projects WHERE projectid ='. $_GET["id"];
$result = mysql_real_escape_string($query);
$result = mysql_query ($query);
Also maybe move mysql_insert_id() to right after assigning the result just to be safe.
$result = mysql_query($sql);
$insertId = mysql_insert_id();
Then when you assign it to the querystring just use the parameter and also the
header('Location: ../projectpage.php?id='.$insertId);
I am using a variable in my php code named $user_id. This variable takes a value after executing a short script of code. I also have a table named users in my database and this table holds user_id and email. If want to select email from my database, when the user_id from my table is equal to my variable named $user_id. Can I do this? This is my query:
<?php
//code ...
$user_id=$_GET['user']; //$user_id gets a value here
//now I want to select email from table users, where user_id is equal to variable $user_id
mysql_query(" SELECT `email` FROM `users` WHERE `user_id`='$user_id' ");
?>
Yes, it will work. I'd though advise you to use pdo or mysqli instead of mysql_* functions. They have been deprecated.
If for some reasons you can not switch to either of them; you should filter/sanitize your query.
Also, if user_id is a numeric field, you wouldn't be needing to enclose $user_id in quotes.
Your code has the basics, it just needs handling and I would add a couple of checks.
if(isset($_GET["user"]) && $_GET["user"] != "") //check there is a value for the user ID
{
if(is_int($_GET["user"]))
{
$user_id=$_GET["user"]);
$email="";
$q=mysql_query("SELECT email FROM users WHERE user_id={$user_id}") or die(mysql_error());
if(mysql_num_rows($q) > 0)
{
while($user=mysql_fetch_assoc($q))
{
$email=$user["email"];
}
}
else
{
echo "no users found";
}
}
else
{
echo "Not a valid user ID, please enter numeric value";
}
}
else
{
echo "No UserID";
}
hjpotter92 recommends that you use mysqli or pdo for questioning your database, which I would agree with although while learning keep with mysql as there are more resources available for learning, then when confident move onto newer technologies.
Please note: I have based this on the experience I feel the user has got with PHP and MySQL not on the most modern or best practices.
The code should be:
$email = '';
$res = mysqli_query(" SELECT `email` FROM `users` WHERE `user_id`='$user_id' ");
while ($temp = mysqli_fetch_assoc($res)) {
$email = $temp['email'];
}
So I've been trying to replicate a second order SQL Injection. Here's an example template of two php based sites that I've prepared. Let's just call it a voter registration form. A user can register and then you can check if you're a registered voter or not.
insert.php
<?php
$db_selected = mysql_select_db('canada',$conn);
if (!db_selected)
die("can't use mysql: ". mysql_error());
$sql_statement = "INSERT into canada (UserID,FirstName,LastName,Age,State,Town)
values ('".mysql_real_escape_string($_REQUEST["UserID"])."',
'".mysql_real_escape_string($_REQUEST["FirstName"])."',
'".mysql_real_escape_string($_REQUEST["LastName"])."',
".intval($_REQUEST["Age"]).",
'".mysql_real_escape_string($_REQUEST["State"])."',
'".mysql_real_escape_string($_REQUEST["Town"])."')";
echo "You ran the sql query=".$sql_statement."<br/>";
$qry = mysql_query($sql_statement,$conn) || die (mysql_error());
mysql_close($conn);
Echo "Data inserted successfully";
}
?>
select.php
<?php
$db_selected = mysql_select_db('canada', $conn);
if(!db_selected)
die('Can\'t use mysql:' . mysql_error());
$sql = "SELECT * FROM canada WHERE UserID='".addslashes($_POST["UserID"])."'";
echo "You ran the sql query=".$sql."<br/>";
$result = mysql_query($sql,$conn);
$row=mysql_fetch_row($result);
$sql1 = "SELECT * FROM canada WHERE FirstName = '".$row[1]."'";
echo "The web application ran the sql query internally=" .$sql1. "<br/>";
$result1 = mysql_query($sql1, $conn);
$row1 = mysql_fetch_row($result1);
mysql_close($conn);
echo "<br><b><center>Database Output</center></b><br><br>";
echo "<br>$row1[1] $row1[2] , you are a voter! <br>";
echo "<b>VoterID: $row[0]</b><br>First Name: $row[1]<br>Last Name: $row[2]
<br>Age: $row[3]<br>Town: $row[4]<br>State: $row[5]<br><hr><br>";
}
?>
So I purposely made this vulnerable to show how second order SQL Injection works, a user can type in a code into the first name section (where I am currently stuck, I've tried many different ways but it seems that I can't get it to do anything).
Then when a person wants to activate the code that he has inserted in the first name section, all he needs to do is just type in the userID and the code will be inserted.
For example:
I will type into the insert.php page as:
userid = 17
firstname = (I need to inject something here)
lastname = ..
age = ..
town = ..
state = ..
Then when I check for my details, and type in 17, the SQL script injected will be activated.
Can I get few examples on what sort of vulnerabilities I can show through this?
What is there to demonstrate?
Second order SQL injection is nothing more than SQL injection, but the unsafe code isn't the first line.
So, to demonstrate:
1) Create a SQL injection string that would do something unwanted when executed without escaping.
2) Store that string safely in your DB (with escaping).
3) Let some other piece of your code FETCH that string, and use it elsewhere without escaping.
EDIT: Added some examplecode:
A table:
CREATE TABLE tblUsers (
userId serial PRIMARY KEY,
firstName TEXT
)
Suppose you have some SAFE code like this, receiving firstname from a form:
$firstname = someEscapeFunction($_POST["firstname"]);
$SQL = "INSERT INTO tblUsers (firstname) VALUES ('{$firstname }');";
someConnection->execute($SQL);
So far, so good, assuming that someEscapeFunction() does a fine job. It isn't possible to inject SQL.
If I would send as a value for firstname the following line, you wouldn't mind:
bla'); DELETE FROM tblUsers; //
Now, suppose somebody on the same system wants to transport firstName from tblUsers to tblWhatever, and does that like this:
$userid = 42;
$SQL = "SELECT firstname FROM tblUsers WHERE (userId={$userid})";
$RS = con->fetchAll($SQL);
$firstName = $RS[0]["firstName"];
And then inserts it into tblWhatever without escaping:
$SQL = "INSERT INTO tblWhatever (firstName) VALUES ('{$firstName}');";
Now, if firstname contains some deletecommand it will still be executed.
Using a first name of:
' OR 1 OR '
This will produce a where clause in the second SQL of
WHERE FirstName = '' OR 1 OR ''
Therefore the result will be the first record in the table.
By adding a LIMIT clause, you can extract all rows from the table with:
' OR 1 ORDER BY UserID ASC LIMIT 0, 1 --
Obviously it will only extract 1 row at a time, so you would need to repeat that and increment the 0 in the LIMIT. This example uses a comment -- to terminate the remaining SQL which would otherwise cause the query to fail because it would add a single quote after your LIMIT.
The above is a simple example, a more complex attack would be to use a UNION SELECT which would give you access to the entire DB through the use of information_schema.
Also you are using addslashes() in one of your queries. That is not as secure as mysql_real_escape_string() and in turn: escaping quotes with either is not as secure as using prepared statements or parameterised queries for example in PDO or MySQLi.
I've been doing a lot of research but I guess I still didn't find the answers. This is a seat reservation and I'm not so good in php and mysql. So here's my code:
reservation.php code:
<?php
mysql_connect("localhost","root","") or die (mysql_error());
mysql_select_db('seat_reservation') or die (mysql_error());
$insert = mysql_query("INSERT INTO reservation (chair_status, room_id, chair_number) VALUES (0, 400, 05)");
?>
</td>
<div id="popupContact">
<a id="popupContactClose">x</a>
<center><form method = "POST" action="reserve.php">
<?php
$query = mysql_query("SELECT chair_status FROM reservation WHERE room_id = '400' AND chair_number = '05'");
while($row = mysql_fetch_array($query)) {
$_SESSION['roomno'] = $row['room_id'];
$_SESSION['chairnum'] = $row['chair_number'];
}
?>
reserve.php code:
<?php
$name = $_POST['student_name'];
$stud_id = $_POST['stud_id'];
$room_id = $_SESSION['roomno'];
$chair_num = $_SESSION['chairnum'];
mysql_connect("localhost", "root", "") or die (mysql_error());
mysql_select_db('seat_reservation') or die (mysql_error());
$query = mysql_query("SELECT chair_status FROM reservation WHERE room_id = '$room_id' AND chair_number = '$chair_num'");
if($query == 0)
{
$insert = mysql_query("UPDATE reservation SET chair_status = 1, student_name = '$name', stud_id = '$stud_id' WHERE room_id = '$room_id' AND chair_number = '$chair_num'");
}
else
die ("Sorry, seat taken! <br />Redirecting...<meta http-equiv='refresh' content=2;reservation.php>");
?>
my problem is that, when I reserve a seat, it tells me that the seat is taken even if the chair_status field is 0. When I checked the DB, it successfully inserted with chair_status of 0. I don't know which part is wrong. I really need your help, thank you!
In reservation.php, you SELECT only chair_status but then try to access $row['room_id'] and $row['chair_number']: neither are in the resultset. However, both are already known since they were fixed in the WHERE clause of the query, therefore one could use those values without resorting to the MySQL query.
Even if you wanted to use such a query to set the $_SESSION variables, it is daft to loop over the resultset overridding those variables with each result. Better to LIMIT the query and use only one resulting record.
However, you probably wanted to output form elements rather than set $_SESSION variables in order that the user can then choose which of the available seats they wish to reserve? In which case, you probably meant to include chair_status = 0 in your filter criteria.
The return value of the mysql_query function is a resource identifier; comparing this against 0 in reserve.php is probably not what you had intended. Perhaps you wanted mysql_num_rows instead?
Please stop writing new code with the ancient MySQL extension: it is no longer maintained and the community has begun the deprecation process. Instead you should use either the improved MySQLi extension or the PDO abstraction layer.
Please avoid putting variables (and especially those which come from your user) into your SQL, which makes you vulnerable to SQL injection. You should instead use prepared statements, with which your variables can be passed to MySQL as parameters that do not get evaluated for SQL. Read about Bobby Tables for more information.
You probably mean if (mysql_num_rows($query) == 0) {. The way it is your are checking if there is an error with the query, not the number of rows returned. Check the docs for more information.
Also, this might be optional, but use braces to enclose your else statement. And it might be better to use mysqli instead of mysql_... functions as mentioned in your comments. Or just escape the user input before adding it to the query string.
use mysql_num_rows for checking if records exist..
$query = mysql_query("SELECT chair_status FROM reservation WHERE room_id = '$room_id' AND chair_number = '$chair_num'");
$rows = mysql_num_rows($query);
if($rows == 0)
{
$insert = mysql_query("UPDATE reservation SET chair_status = 1, student_name = '$name', stud_id = '$stud_id' WHERE room_id = '$room_id' AND chair_number = '$chair_num'");
}