0

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.

marc_s
  • 704,970
  • 168
  • 1,303
  • 1,425
tantan
  • 35
  • 1
  • 3
  • are you referring to MySQL connector of PHP? See: http://www.php.net/manual/en/ref.mysql.php – Raptor Feb 26 '12 at 03:08

1 Answers1

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:

  1. Connection to database: e.g
<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
?>
  1. Execute a query in the database: e.g

$sth = $dbh->query ("SELECT name, category FROM animal");

  1. 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:

  1. SQL Injection Attacks - How can I avoid SQL injection attacks?
  2. 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

Community
  • 1
  • 1
footy
  • 5,603
  • 13
  • 46
  • 96
  • 1
    Avoid 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 and knittl , I have updated the answer – footy Feb 26 '12 at 11:50
  • @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