How can we use PHP search function to search information from our database? Wherein, we will let the user for example key in the username and all of the information from that specified username will be shown.
Asked
Active
Viewed 90 times
1 Answers
2
You cannot search a database in php directly through a call. You have to write a search query to a database and then get back the result.
Refer to this video for more info: http://www.youtube.com/watch?v=yTudF1CAKY0
Your php code usually involves the following 3 phases:
- Connection to database: e.g
<?php $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass); ?>
- Execute a query in the database: e.g
$sth = $dbh->query ("SELECT name, category FROM animal");
- Display the output: e.g
while ($row = $sth->fetch ()) {
printf ("Name: %s, Category: %s\n", $row[0], $row[1]); $count++;}
More references: http://www.kitebird.com/articles/php-pdo.html
EDIT
Please try to avoid the following security risks:
- SQL Injection Attacks - How can I avoid SQL injection attacks?
- XSS (Cross site scripting attacks) - PHP Prevent xss
Refer here for a complete list of security threats you may be interested in. - OWASP - Top 10 risk
-
1Avoid XSS by escaping `$row[0]` and `$row[1]`. Otherwise a good answer to a very vague question +1 – knittl Feb 26 '12 at 10:38
-
@knittl that's true, left out here as it would complicate the point being made. – footy Feb 26 '12 at 11:03
-
While it would complicate things, I believe it's very important to at least mention it, and perhaps add a reference link. Direct copying from simplified examples can lead to security disasters. Also $knittl, I believe you mean SQL injection, rather than Cross-site scripting. – MichD Feb 26 '12 at 11:36
-
-
@Michd: he used PDO, so I the answer leads to the right direction (prepared statements). And no, I meant XSS: `printf("…", …)` usually outputs to in HTML context. – knittl Feb 26 '12 at 12:21