Replaced $HTTP_GET_VARS with $_GET, but not working - php

I have the following code, which is not working for me. I used to have $HTTP_GET_VARS instead of $_GET, but then updated to PHP 5, and now things are broken. Any thoughts on what I'm doing wrong here?
<?php
$_GET['SubCat'];
$_GET['Location'];
$db = mysql_connect("localhost", "xxxx", "xxxx");
mysql_select_db("outdoors",$db);
if ($Location) {
$result = mysql_query("SELECT ID, Longitude, URL, SiteName, Description FROM hunting WHERE SubCategory = '$SubCat' AND Location = '$Location' AND Status <> 'HIDDEN' ORDER BY SiteName",$db);
} else {
$result = mysql_query("SELECT ID, Longitude, URL, SiteName, Description FROM hunting WHERE SubCategory = '$SubCat' AND Status <> 'HIDDEN' ORDER BY SiteName",$db);
<More unrelated stuff after this>
The variable will be passed through a link like this :
hunting.php?SubCat=Hunting+Locations

For your first question:
You must store it in any variable such like this
$SubCat = $_GET['SubCat'];
$Location = $_GET['Location'];
Or refer to it directly.
For your second question:
Any idea on an easy way to change those two lines on several dozen files at one on my server?
Use a global search function to cover your entire directory. You find it in any of the popular editors. The search for $_GET['SubCat']; and replace it by $SubCat = $_GET['SubCat'];. Just make sure it is an unique name.
On a side note:
You donot use any type checking or input escaping and directly put it in your sql statement. IT IS VERY DANGEROUS. Please use PDO or at least an escaping function before you pass it to avoid SQL injection attacks

Related

Adding a secondary WHERE statement to PDO/MySql statement

I have a PDO/MySQL database connection. My database holds content for various landing pages. To view these landing pages I enter *localhost/landing_page_wireframe.php* and append with ?lps=X (where X represents the Thread_Segment) to display the particular page in the browser. I am now getting to second iterations of these pages and need to add a secondary classifier to follow "Thread_Segment" to distinguish which version I am trying to pull up. Here is a snippet of my current working query.
<?php
$result = "SELECT * FROM landing_page WHERE Thread_Segment = :lps";
$stmt = $connection->prepare($result);
$stmt->bindParam(':lps', $_GET['lps']);
$stmt->execute();
$thread = "";
$threadSegment = "";
$version = "";
$categoryAssociation = "";
while($row = $stmt->fetch()) {
$thread = $row["Thread"];
$threadSegment = $row["Thread_Segment"];
$version = $row["Version"];
$categoryAssociation = $row["Category_Association"];
}
?>
So I need to now change this to add in the secondary classifier to distinguish between versions. I would imagine my query would change to something like this:
$result = "SELECT * FROM landing_page WHERE Thread_Segment = :lps AND Version = :vrsn";
if this is correct so far, then where I am beginning to get lost is in the following PHP code.
$stmt = $connection->prepare($result);
$stmt->bindParam(':lps', $_GET['lps']);
$stmt->execute();
I imagine I need to include some secondary iteration of this in my php to talk to the secondary classifier, but not totally sure how to go about this, and then I would imagine my url appendage would go from ?lps=X to something like this ?lps=X&vrsn=Y (Y representing the version).
I should state that I am somewhat new to PHP/MySql so the answer here may be simple, or may not even be possible. Perhaps I am not even going about this the correct way. Thought you all might be able to shed some insight, or direction for me to curve my research on the matter to. Thanks and apologies for any improper terminology, as I am definitely new to these technologies.
The URL change is as you describe. Just add another bindParam call to use that parameter:
$stmt = $connection->prepare($result);
$stmt->bindParam(':lps', $_GET['lps']);
$stmt->bindParam(':vrsn', $_GET['vrsn']);
$stmt->execute();
Adding another bindParam() should work here.
$stmt = $connection->prepare($result);
$stmt->bindParam(':lps', $_GET['lps']);
$stmt->bindParam(':vrsn', $_GET['vrsn']);
$stmt->execute();
You can access it via ?lps=X&vrsn=Y but just as a warning, the query will fail if those $_GET params are not requested. I recommend defaulting it to something prior to sending it through the query:
$stmt = $connection->prepare($result);
$lps = isset($_GET['lps']) ? $_GET['lps'] : 'default lps value';
$vrsn = isset($_GET['vrsn ']) ? $_GET['vrsn '] : 'default vrsn value';
$stmt->bindParam(':lps', $lps);
$stmt->bindParam(':vrsn', $vrsn);
$stmt->execute();

SQL Table not updating in PHP

I'm trying to create an update function in PHP but the records don't seem to be changing as per the update. I've created a JSON object to hold the values being passed over to this file and according to the Firebug Lite console I've running these values are outputted just fine so it's prob something wrong with the sql side. Can anyone spot a problem? I'd appreciate the help!
<?php
$var1 = $_REQUEST['action']; // We dont need action for this tutorial, but in a complex code you need a way to determine ajax action nature
$jsonObject = json_decode($_REQUEST['outputJSON']); // Decode JSON object into readable PHP object
$name = $jsonObject->{'name'}; // Get name from object
$desc = $jsonObject->{'desc'}; // Get desc from object
$did = $jsonObject->{'did'};// Get id object
mysql_connect("localhost","root",""); // Conect to mysql, first parameter is location, second is mysql username and a third one is a mysql password
#mysql_select_db("findadeal") or die( "Unable to select database"); // Connect to database called test
$query = "UPDATE deal SET dname = {'$name'}, desc={'$desc'} WHERE dealid = {'$did'}";
$add = mysql_query($query);
$num = mysql_num_rows($add);
if($num != 0) {
echo "true";
} else {
echo "false";
}
?>
I believe you are misusing the curly braces. The single quote should go on the outside of them.:
"UPDATE deal SET dname = {'$name'}, desc={'$desc'} WHERE dealid = {'$did'}"
Becomes
"UPDATE deal SET dname = '{$name}', desc='{$desc}' WHERE dealid = '{$did}'"
On a side note, using any mysql_* functions isn't really good security-wise. I would recommend looking into php's mysqli or pdo extensions.
You need to escape reserved words in MySQL like desc with backticks
UPDATE deal
SET dname = {'$name'}, `desc`= {'$desc'} ....
^----^--------------------------here
you need to use mysql_affected_rows() after update not mysql_num_rows

"insert into $schoolname ('cat','...) The $_POST " if statement " is not passing values into $schoolname table

I'm having problems getting $schoolname to read in the "insert into" mysqlcommand.
I'm just creating a small thing for a fan club that spans a few schools. So i created a different database table for each school. Each school has a unique id, and the table name corresponds to that. The code is below. Please help. Well, the problem area is the insert portion.
"insert into $schoolname ('cat','...)
For some reason $schoolname is not catching with the $_POST if statement
the mysql command " insert into .... " passes values if i specify a hard coded table name, but it does not pass values if i specify the variable ($schoolname) in place of the table name. I need to specify the variable because there a number of schools with each having their own tables.
<?php
require_once('include.php');
include('imageupload.php');
$schoolid='';
if(isset($_GET['schoolid']) && isset($_GET['schoolid']) != '')
{
$schoolid .= 'and id ='.$_GET['schoolid'];
}
$sqlschoolid = "select * from schools where status = 'Active' ".$schoolid;
$resschoolid = $obj->sql_query($sqlschoolid);
$school = $resschoolid[0];
$schoolname = $school['parameter'];
$schoolid2 = $school['id'];
if($_POST)
{
(isset($_POST['pr']) && $_POST['pr'] != "") ? $price=mysql_real_escape_string($_POST['pr']) : $pr="" ;
$sqlclass = "insert into $schoolname(`category`,`type`,`price`,`title`,`description`,`weburl`,`image`,`email`,`phone`,`address`,`city`,`state`,`zip`,`postdate`,`sponser`,`status`)
values('".$_POST['subcategory']."','".$_POST['type']."','".$pr."','".mysql_real_escape_string($_POST['title'])."','".mysql_real_escape_string($_POST['description'])."','".mysql_real_escape_string($_POST['weburl'])."','".$imagename."','".mysql_real_escape_string($_POST['email'])."','".mysql_real_escape_string($_POST['phone'])."','".mysql_real_escape_string($_POST['address'])."','".mysql_real_escape_string($_POST['city'])."','".mysql_real_escape_string($_POST['state'])."','".mysql_real_escape_string($_POST['zip'])."','".date('Y-m-d H:i:s')."','0','Active')";
}
?>
Since you haven't specified what problem you're seeing, this is only a guess:
if(isset($_GET['schoolid']) && isset($_GET['schoolid']) != '')
Shouldn't that be
if(isset($_GET['schoolid']) && $_GET['schoolid'] != '')
As a side note, consider what happens if the user entered the following in schoolid:
0; delete from schools
This is known as SQL Injection, and you should be using "bind variables" instead of building the query by concatenating strings.
The problem seems to be the below query:
$sqlschoolid = "select * from schools where status = 'Active' ".$schoolid;
What is $schoolid variable at the end? I see what is $schoolid variable and I assume that the variable isn't set correctly.
From what I understand is that the above query might be throwing an error and therefore $schoolname isn't populated at all. Can you please try to print how that query looks like?
EDIT 1 Reading the past discussions, it is clear that $schoolname variable is empty, i.e. has no value. It is not the scope issue because from your code $schoolname is in the global scope and is therefore available inside the $_POST IF check. So let us try to debug the code to analyse options:
Can you put an echo $sqlschoolid; just after where you have written the query? This will confirm that the query format is correct
Assuming that the query is good, let us now check if the query is returning the right data? I'm not sure what DB class are you using, so I can't say what does $obj->sql_query() returns? Perhaps the MySQL resultset. Anyways, can you put var_dump($resschoolid) right after where it is initialized? And another var_dump($school) below?
This is how I would like you to put the debug statements:
$sqlschoolid = "select * from schools where status = 'Active' ".$schoolid;
echo $sqlschoolid;
$resschoolid = $obj->sql_query($sqlschoolid);
var_dump($resschoolid);
$school = $resschoolid[0];
var_dump($school);
$schoolname = $school['parameter'];
$schoolid2 = $school['id'];
I hope the above will give more insight into the problem. Let me know if you've any questions.

SQL full text search with PHP and PDO

I'm trying to write a simple, full text search with PHP and PDO. I'm not quite sure what the best method is to search a DB via SQL and PDO. I found this this script, but it's old MySQL extension. I wrote this function witch should count the search matches, but the SQL is not working. The incoming search string look like this: 23+more+people
function checkSearchResult ($searchterm) {
//globals
global $lang; global $dbh_pdo; global $db_prefix;
$searchterm = trim($searchterm);
$searchterm = explode('+', $searchterm);
foreach ($searchterm as $value) {
$sql = "SELECT COUNT(*), MATCH (article_title_".$lang.", article_text_".$lang.") AGINST (':queryString') AS score FROM ".$db_prefix."_base WHERE MATCH (article_title_".$lang.", article_text_".$lang.") AGAINST ('+:queryString')";
$sth = $dbh_pdo->prepare($sql);
$sql_data = array('queryString' => $value);
$sth->execute($sql_data);
echo $sth->queryString;
$row = $sth->fetchColumn();
if ($row < 1) {
$sql = "SELECT * FROM article_title_".$lang." LIKE :queryString OR aricle_text_".$lang." LIKE :queryString";
$sth = $dbh_pdo->prepare($sql);
$sql_data = array('queryString' => $value);
$sth->execute($sql_data);
$row = $sth->fetchColumn();
}
}
//$row stays empty - no idea what is wrong
if ($row > 1) {
return true;
}
else {
return false;
}
}
When you prepare the $sql_data array, you need to prefix the parameter name with a colon:
array('queryString' => $value);
should be:
array(':queryString' => $value);
In your first SELECT, you have AGINST instead of AGAINST.
Your second SELECT appears to be missing a table name after FROM, and a WHERE clause. The LIKE parameters are also not correctly formatted. It should be something like:
sql = "SELECT * FROM ".$db_prefix."_base WHERE article_title_".$lang." LIKE '%:queryString%' OR aricle_text_".$lang." LIKE '%:queryString%'";
Update 1 >>
For both SELECT statements, you need unique identifiers for each parameter, and the LIKE wildcards should be placed in the value, not the statement. So your second statement should look like this:
sql = "SELECT * FROM ".$db_prefix."_base WHERE article_title_".$lang." LIKE :queryString OR aricle_text_".$lang." LIKE :queryString2";
Note queryString1 and queryString2, without quotes or % wildcards. You then need to update your array too:
$sql_data = array(':queryString1' => "%$value%", ':queryString2' => "%$value%");
See the Parameters section of PDOStatement->execute for details on using multiple parameters with the same value. Because of this, I tend to use question marks as placeholders, instead of named parameters. I find it simpler and neater, but it's a matter of choice. For example:
sql = "SELECT * FROM ".$db_prefix."_base WHERE article_title_".$lang." LIKE ? OR aricle_text_".$lang." LIKE ?";
$sql_data = array("%$value%", "%$value%");
<< End of Update 1
I'm not sure what the second SELECT is for, as I would have thought that if the first SELECT didn't find the query value, the second wouldn't find it either. But I've not done much with MySQL full text searches, so I might be missing something.
Anyway, you really need to check the SQL, and any errors, carefully. You can get error information by printing the results of PDOStatement->errorCode:
$sth->execute($sql_data);
$arr = $sth->errorInfo();
print_r($arr);
Update 2 >>
Another point worth mentioning: make sure that when you interpolate variables into your SQL statement, that you only use trusted data. That is, don't allow user supplied data to be used for table or column names. It's great that you are using prepared statements, but these only protect parameters, not SQL keywords, table names and column names. So:
"SELECT * FROM ".$db_prefix."_base"
...is using a variable as part of the table name. Make very sure that this variable contains trusted data. If it comes from user input, check it against a whitelist first.
<< End of Update 1
You should read the MySQL Full-Text Search Functions, and the String Comparison Functions. You need to learn how to construct basic SQL statements, or else writing even a simple search engine will prove extremely difficult.
There are plenty of PDO examples on the PHP site too. You could start with the documentation for PDOStatement->execute, which contains some examples of how to use the function.
If you have access to the MySQL CLI, or even PHPMyAdmin, you can try out your SQL without all the PHP confusing things. If you are going to be doing any database development work as part of your PHP application, you will find being able to test SQL independently of PHP a great help.

mysql_query arguments in PHP

I'm currently building my first database in MySQL with an interface written in PHP and am using the 'learn-by-doing' approach. The figure below illustrates my database. Table names are at the top, and the attribute names are as they appear in the real database. I am attempting to query the values of each of these attributes using the code seen below the table. I think there is something wrong with my mysql_query() function since I am able to observe the expected behaviour when my form is successfully submitted, but no search results are returned. Can anyone see where I'm going wrong here?
<form name = "search" action = "<?=$PHP_SELF?>" method = "get">
Search for <input type = "text" name = "find" /> in
<select name = "field">
<option value = "Title">Title</option>
<option value = "Description">Description</option>
<option value = "City">Location</option>
<option value = "Company_name">Employer</option>
</select>
<input type = "submit" name = "search" value = "Search" />
</form>
$query = "SELECT Title, Descrition, Company_name, City, Date_posted, Application_deadline
FROM job, employer, address
WHERE Title = $find
OR Company_name = $find
OR Date_posted = $find
OR Application_deadline = $find
AND job.employer_id_job = employer.employer_id
AND job.address_id_job = address.address_id";
There seems to be at least four problems:
You don't have quotes around $find, i.e. WHERE Title = '$find'.
You don't seem to be using mysql_real_escape_string (or did you just omit that code in your question for brevity?)
You spelled Description incorrectly.
AND has higher precedence than OR so you probably want parentheses in your expression:
WHERE (Title = '$find'
OR Company_name = '$find'
OR Date_posted = '$find'
OR Application_deadline = '$find')
AND job.employer_id_job = employer.employer_id
AND job.address_id_job = address.address_id"
I suspect that one or more of these are the reason why it's not working. However to be sure you should post more of your code and your table structure.
Another point is that you are using the old ANSI-89 join syntax. I would recommend using the newer syntax added in SQL-92 (FROM a JOIN b ON ...). This would have prevented you from making the fourth error, as well as having numerous other advantages over the older syntax.
Also try using mysql_error to find out what the exact error message is. And please include the message in your question.
If you like to learn by doing then learn by doing it in PDO and bind the parameters. This is the safe and correct way to do it these days.
Use single quotes for values in where clause.
Try this one:
$fields= array('Title','Company_name', 'Date_posted','Application_deadline');
if(!in_array($_GET['field'],$fields)) die(); // do some error handling here
$query = "SELECT Title, Descrition, Company_name, City, Date_posted, Application_deadline
FROM job, employer, address
WHERE
$field = '".mysql_real_escape_string($_GET['find']) ."'
AND job.employer_id_job = employer.employer_id
AND job.address_id_job = address.address_id";
If single quotes isn't your only problem (it is certainly part of it), check the return of mysql_error().
Check the code samples here:
http://www.php.net/manual/en/function.mysql-query.php
I would suggest also using ezSQL to do all your query handling, it's easy to drop into your code and makes all the processing easy, just include the db info in a config file, include the classes for ezSQL in the config file, setup a global call to the class like
$db = new ez_SQL();
then in your referencin php files, just do this
global $db;
$results = $db->query("SELECT statment", ARRAY_A);
you can get ezsql from: http://justinvincent.com/ezsql

Categories