SELECT by example:
<form action ="Tutorial.php" method="GET">
<form action ="Tutorial.php" method="GET">
Choose a food type:
<select
name="uh">
<option
value="u">Unhealthy</option>
<option
value="h">Healthy</option>
</select><br><br>
<input type="submit"
value="Submit">
</form>
<?php
$mysql_host='localhost';
$mysql_user='root';
$mysql_pass='';
$mysql_db='a_database';
if(isset($_GET['uh'])
&& !empty($_GET['uh'])){
$uh=strtolower($_GET['uh']);
if($uh=='u' || $uh=='h') {
$query="SELECT `food`,
`calories` FROM `food` WHERE `healthy_unhealthy`='".$uh."' ORDER BY
`id` DESC";
if(@mysql_connect($mysql_host,
$mysql_user, $mysql_pass)){
if(@mysql_select_db($mysql_db)){
if($query_run=mysql_query($query)){
while($query_row = mysql_fetch_assoc($query_run)){
$food = $query_row['food'];
$calories=$query_row['calories'];
echo $food.' has
'.$calories.' calories.<br>';
}
} else {
echo 'Query failed';
}
}
}
} else {
echo 'Must be u, or h.';
}
}
?>
LIKE with a Search Engine Example:
LIKE with a Search Engine Example:
<form action ="Tutorial.php" method="POST">
Name: <input type="text" name="search_name"><input type="submit" value="Search">
</form>
<?php
require 'connect.inc.php';
if(isset($_POST['search_name'])){
$search_name = $_POST['search_name'];
if(!empty($search_name)){
$query = "SELECT name FROM names WHERE name LIKE '%".mysqli_real_escape_string($mysql_conn,$search_name)."%'";
$query_run = mysqli_query($mysql_conn,$query);
if(mysqli_num_rows($query_run) == NULL){
echo 'No result found';
}else{
echo 'Result found: <br>';
while($query_row = mysqli_fetch_assoc($query_run)){
echo $query_row['name'].'<br>';
}
}
}
}
?>
connect.inc.php
<?php
$host = 'localhost';
$name = 'root';
$password = '';
$database = 'a_database'; //your database name
if(@mysqli_connect($host, $name, $password)) {
$mysql_conn = @mysqli_connect($host, $name, $password);
if(@mysqli_select_db($mysql_conn, $database)) {
} else {
die('Could not find database.');
}
} else {
die('Could not connect.');
}
?>
<form action ="Tutorial.php" method="POST">
Name: <input type="text" name="search_name"><input type="submit" value="Search">
</form>
<?php
require 'connect.inc.php';
if(isset($_POST['search_name'])){
$search_name = $_POST['search_name'];
if(!empty($search_name)){
$query = "SELECT name FROM names WHERE name LIKE '%".mysqli_real_escape_string($mysql_conn,$search_name)."%'";
$query_run = mysqli_query($mysql_conn,$query);
if(mysqli_num_rows($query_run) == NULL){
echo 'No result found';
}else{
echo 'Result found: <br>';
while($query_row = mysqli_fetch_assoc($query_run)){
echo $query_row['name'].'<br>';
}
}
}
}
?>
connect.inc.php<?php
$host = 'localhost';
$name = 'root';
$password = '';
$database = 'a_database'; //your database name
if(@mysqli_connect($host, $name, $password)) {
$mysql_conn = @mysqli_connect($host, $name, $password);
if(@mysqli_select_db($mysql_conn, $database)) {
} else {
die('Could not find database.');
}
} else {
die('Could not connect.');
}
?>
No comments:
Post a Comment