I am writing a database search function for games. I come from a Python background so PHP is very new to me, but I am fluent in HTML/CSS, so I figured it was time to write some PHP. Anyways, my Code should query the database for either the Name of the game, or the System based on the search query. I am using LIKE to accomplish this.
<?php
if(isset($_POST['submit'])){
if(isset($_GET['go'])){
if(preg_match("^/[A-Za-z]+/^", $_POST['query'])){
$query=$_POST['query'];
}
}
$db=mysql_connect ("localhost", "********", "*****") or die ('I cannot connect to the database because: ' . mysql_error());
$mydb=mysql_select_db("*******");
$sql="SELECT ID, Name, System FROM Games WHERE Name LIKE '%" . $query . "%' OR System LIKE '%" . $query ."%'";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result)){
$Name=$row['Name'];
$System=$row['System'];
$ID=$row['ID'];
echo "<ul>\n";
echo "<li>" . "<a href=\"search.php?id=$ID\">" .$Name . " " . $System . "</a></li>\n";
echo "</ul>";
}
}
else{
echo "<p>Please enter a search query</p>";
}
?>
And here is my very simple HTML for it
<!DOCTYPE html>
<HTML>
<head>
<link rel="stylesheet" type="text/css" href="assets/style.css">
</head>
<body>
<h1>Search for Games</h1>
<p>You can search by genre, name, or just browse.</p>
<form method="post" action="search.php?go" id="searchform">
<input type="text" name="query">
<input type="submit" name="submit" value="Search">
</form>
</body>
</HTML>
Lastly, here is the website I am running it on so you can see what it does/returns. [removed website due to vulnerabilities]
There are only 3 database entries right now and it doesn't matter if I type in "starfox" or "zelda" I always get all 3 entries returned back to me. What am I doing wrong?
EDIT: I cleaned up my code with mysqli, is this more complete? It works like I want to, but is it safe from SQL Injection?
<?php
if(isset($_POST['submit'])){
if(isset($_GET['go'])){
$query=$_POST['query'];
}
$db=new mysqli ("localhost", "****", "*****", "******") or die ('I cannot connect to the database because: ' . mysql_error());
$sql="SELECT ID, Name, System FROM Games WHERE Name LIKE '%" . $query . "%' OR System LIKE '%" . $query ."%'";
$result = $db->query($sql);
while($row=$result->fetch_assoc()){
$Name=$row['Name'];
$System=$row['System'];
$ID=$row['ID'];
echo "<ul>\n";
echo "<li>" . "<a href=\"search.php?id=$ID\">" .$Name . " " . $System . "</a></li>\n";
echo "</ul>";
}
}
else{
echo "<p>Please enter a search query</p>";
}
?>