I'm using the following query to pull records from a database:
$query = "SELECT password, salt, 'jobseeker' as type
FROM ip_jobseekers
WHERE ipJ_username = '$username'
UNION
SELECT password, salt, 'company' as type
FROM ip_companies
WHERE ipC_username = '$username';";
$result = mysql_query($query);
//No Such User
if (mysql_num_rows($result) < 1) {
header('Location: login.php?login=fail'); exit;}
to create a new session:
//login successful
else {$_SESSION['user'] = $username;}
I want to include the type of user in the session so that I can specify what content is displated to the user. Is it possible to make use of the "'company' as type" and "'jobseeker' as type" parts of that query to do this? I've make a few attempts at doing it but I've had no success.
Any help would be greatly appreciated.
Thanks.
Kai.
There is absolutely no difference between "regular" and aliased fields. You can use the latter as well as any other.
to find any error in your query you can run the query like below
$result = mysql_query($query) or trigger_error(mysql_error()." ".$query);
for testing you can use above and you ca redirect to custom error page in production environment.
My personal suggestion is to use PDO. make use of Object oriented Programs to run your code faster and to have standard structure.
First of all, you're using the mysql_ set of functions, which are highly dangerous, and you should move over all your code from ASAP.
Next, you should NOT be stringing up queries like this, because your application will grow into this behemoth of SQL everywhere (in the HTML, in the Views, EVERYWHERE), you should probably be using some kind of class/object system where you wrap around the SQL.
And, you should know about the SQL AND clause (I feel horrible linking w3schools, but, that's all I can find right now).
Related
I am adding some server-side form validations (using php) in case one of the users of my site has javascript turned off. On one form, there are 10 separate input fields that can be changed. Could someone please tell me which protocol will use less system resources? In the first, I write some mySQL variables to check the user's current settings, and compare these with the posted settings. If all 10 posted values are identical to the current values, don't UPDATE database, else UPDATE the database:
$login_id = $_SESSION['login_id'];
$sql1 = mysql_fetch_assoc(mysql_query("SELECT value1 FROM login WHERE login_id =
'$login_id'"));
$sql1a = $sql1['value1'];
// Eight More, then
$sql10 = mysql_fetch_assoc(mysql_query("SELECT value10 FROM login WHERE login_id =
'$login_id'"));
$sql10a = $sql10['value10'];
$Value1 = $_POST['Value1'];
// Eight More, then
$Value10 = $_POST['Value10'];
//Other validations then the following
if (($sql1a == $Value1)&&($sql2a == $Value2)&&.......($sql10a == $Value10)) {
echo "<script>
alert ('You haven't made any changes to your profile');
location = 'currentpage.php';
</script>";
}
else {
$sqlUpdate = mysql_query("UPDATE login SET value1 = '$Value1',....value10 = '$Value10'
WHERE login_id = '$login_id'");
echo "<script>
alert ('Your profile has been updated!');
location = 'currentpage.php';
</script>";
}//End php
OR is it less expensive to just use the user-posted values (keep the $_POST variables) and avoid checking with the comparison line: (($sql1a == $Value1)&&($sql2a == $Value2)&&.......($sql10a == $Value10)) and just go right to
//Other validations then the following
$sqlUpdate = mysql_query("UPDATE login SET value1 = '$Value1',....value10 = '$Value10'
WHERE login_id = '$login_id'");
echo "<script>
alert ('Your profile has been updated!');
location = 'currentpage.php';
</script>";
Thanks for any input on this!
If I understand correctly, your question is whether it's OK for performance to check the profile for modifications. For me, after I've checked your code, this is about much more than just performance...
Let's start with the performance: AFAIK MySQL queries are slower than basic PHP comparisions, that's true - but on this scale, I really don't think it matters much. We're talking about two very basic queries which won't handle a lot of data.
Let's think about what the end user will see (UX): in the second scenario, the user will not have the most exact feedback telling him/her that no modification has been done. On a profile modification screen, I suppose that might not be intentional, so I would tell that we haven't modified anything. (Also, performing an unnecessary UPDATE query is not the most elegant.)
#aehiilrs is right, please pay attention to that comment. This style of MySQL usage is particularly bad for security - if you keep going with this, you will create a lot of security holes in your PHP code. And those are really easy to discover and exploit, so please, have a good look on the alternatives, starting with PDO as mentioned. Any good PHP book out there will show you the way. You can also have a look at a great Q/A here on StackOverflow: How can I prevent SQL injection in PHP?
I wonder whether it's a good idea to try to update the user interface like you did - I would strongly prefer loading another PHP without any <script> magic in the output. In the result PHP, you can always display something like a CSS-styled statusbar for displaying info like that.
I have a basic query in Joomla! and I really, really can't figure out why it doesn't return anything:
$database =& JFactory::getDBO();
$query = "SELECT * FROM my_table";
$database->setQuery($query);
$result = $database->loadObjectList();
var_dump($result);
die();
Query is very, very basic, I know.
It returns $result as null. Thing is, I run this query in a separate .php scrip file (localhost/myscript.php). All other queries in the rest of my website seem to run just fine (including some in other script files like this one).
I've run this query in a terminal and returns what I want. Please, I need some idea :)
If your trying this in a separate php file (localhost/myscipt.php) as you say, you need the proper classes. See this post. The last answer has some details.
However this is not recommended. You should be using module or plugin development all within the framework.
Alternatively, you could use Jumi which allows you to write any code you want and include it as part of a module. Makes life a lot easier.
I think your query is missing a table prefix, you can echo the prefix using $database->getPrefix();
also try changing
$query = "SELECT * FROM my_table";
to
$query = "SELECT * FROM `#__my_table`";
NOTE: Joomla uses a placeholder for the prefix, the “#__” will be replaced with the correct prefix.
need some enlightment here, and this is my first post here.
I would like to call and use my previously created mysql view using php... is it possible?
or in another words,
i'm wondering....can we OR how do we call mysql view, that we already created using php? to reduce long query coding
standard generic codes as follow :
$sql= " SELECT shipping.tarrif1, city.city_name
FROM shipping JOIN city
ON shipping.id_city = city.id_city";
$db->QueryArray($sql);
while ($row = $db->Row()) {
echo $row->city_name. " - " . $row->tarrif1 . "<br />\n";
}
now for the MYSQL VIEWS :
$sql= " CREATE VIEW shipsumarry AS SELECT shipping.tarrif1, city.city_name
FROM shipping JOIN city
ON shipping.id_city = city.id_city";
Pure MYSQL command :
query: SELECT * FROM shipsummary
IN PHP :
$sql = i'm badly stuck here...please help
How do we access it using php.
thanks before
Addition 1:
ok... let me rewrite the example :
$sql1= " CREATE VIEW shipsumarry AS SELECT shipping.tarrif1, city.city_name
FROM shipping JOIN city
ON shipping.id_city = city.id_city";
$sql2= "SELECT * FROM shipsummary";
$db->QueryArray($sql2);
$sql2 can not see shipsummary VIEW, coz it's already in a different var
how to utilise and then execute $sql1 ? & $sql2?
The process is the same in PHP - a MySQL view is seen by the client (PHP) as a regular table, so querying it as
mysql_query("SELECT * FROM shipsummary");
// Or for whatever framework you're using:
$db->QueryArray("SELECT * FROM shipsummary");
should work correctly. If it does not work correctly, the MySQL user with which you are accessing the view may have broken permissions. (Seems unlikely though).
UPDATE
After you edited your question, I can see the problem quite clearly.
$sql1= " CREATE VIEW shipsumarry AS SELECT shipping.tarrif1, city.city_name
FROM shipping JOIN city
ON shipping.id_city = city.id_city";
$sql2= "SELECT * FROM shipsummary";
// Here, you need to execute $sql1 before $sql2 is useful.
$db->QueryArray($sql1);
// Now execute $sql2
$db->QueryArray($sql2);
We don't know what database class or framework you are using, but if there is a comparable method to QueryArray() that doesn't return a result set, but just executes a statement, use it to create the view instead.
Now, all that being said...
Unless the definition of the view must change every time this code executes, and unless you have a reason to then DROP VIEW shipsummary at the end of this script's execution each time, it makes far, far, far, far .... more sense to simply create the view in the database, where it will stay forever, rather than to keep re-creating it with PHP. Views, once created, stay created.
Don't think of them as a temporary query time/code saver. Create the views you will need ONCE in your database (using PHPMyAdmin or mysql CLI, or however you created your tables), and access them with PHP.
Why not just send that
SELECT * FROM shipsummary
To mysql query, it should work, unless i'm not understanding your question...
I have the website written in PHP (Kohana) and MySQL. I want to create the installer which would run all the environment tests and, what is the most important (and the most misterious) for me, will deploy the database. What is more, I would like to choose the prefix of the tables in the database and specify the username and password for the admin. Would you please give my some hints how to do it? Or some link to some tutorial? I was trying to google that but when I searched for terms like "PHP website installer" I have found only how to install PHP.
The most important for me is the process of deploying database with user-defined tables prefix. How should I store the database structure in the file. Should I name the tables using some keyword for the prefix, for example:
%%prefix%%_tableName
or
__prefix__tableName
And what then? Change all the keywords using regular expresions? Is it correct way or is it any better?
A simple way would be to store the SQL queries in PHP files and have PHP inject the prefix into the SQL and return the string.
Like, if you had a PHP file like this for each of your CREATE TABLE queries:
<?php
/** get_myTable.php **/
return <<<SQL
CREATE TABLE `{$prefix}myTable` ( ... )
SQL;
?>
You could do this in your main code:
<?php
$prefix = 'dbprefix_';
$create_queries = array();
$create_queries[] = include('get_myTable.php');
$create_queries[] = include('get_otherTable.php');
foreach($create_queries as $_query) {
mysql_query($_query) or trigger_error(mysql_error(), E_USER_WARNING);
}
?>
Wordpress has its famous '5-minute install'. It's a great benchmark for simplicity, usability, and power and it does most, if not all, of the things you outlined in your question.
If I build my pages like this do I have to check if news_id is numeric in news.php too? Or is this safe?
index.php:
if (ctype_digit($_GET['news_id'])) include('news.php');
news.php:
$query = mysql_query("SELECT * FROM news WHERE news_id = $_GET[news_id]");
$row = mysql_fetch_assoc($query);
if (!mysql_num_rows($query)) exit('The news you're trying to read do not exist.');
The other answers are absolutely correct, you should never allow any user input directly into your database, or any other sensitive area.
You should validate/sanitize all input from $_GET, $_POST etc... You can use PHP’s built in filter functions or use those built into a framework such as Cake PHP or Symphony, which both make handling user data a lot easier.
jonstjohn has a good point you are leaving yourself open sql injection this way, and other forms of attack based around feeding malicious code into you application.
Worth reading Jeff Atwood’s 25 most dangerous programming mistakes for a bit of background on these issues, and others besides.
Short answer: Yes, you should.
Someone might (and will) request news.php, bypassing index.php.
You really should escape your data and sanitize it before sending it into MySQL. No guarantee someone won't try to send something malicious in through the post data.
$news_id = (int)$_GET[news_id];
$query = mysql_query("SELECT * FROM news WHERE news_id = " .
mysql_real_escape_string($news_id));
$row = mysql_fetch_assoc($query);
if (!mysql_num_rows($query)) exit('The news you're trying to read do not exist.');
It's not safe;
Don't check, convert it to integer using intval();
Never, ever put GPC variables in SQL without escaping or casting;