Okay this is abit hard to explain but I currently have a website where I'm using PHP and MySQL to pull tables into the web pages and display them. I've been able to make a search function to look for specific values in the table. I'll show you my code.
<!DOCTYPE php>
<html>
<head>
<link rel="stylesheet" href="style.php" media="screen">
</head>
<body>
<a id="TableButton" href="/Test.php">Items Table</a>
<a id="Clear" href="index.php">Clear Search</a>
<center>
<form method="GET" id="SearchPerson">
<select name="Drop" id="Select">
<option value="FirstName">First Name</option>
<option value="Surname">Surname</option>
<option value="MobileNumber">Mobile Number</option>
<option value="Code">Code</option>
<option value="TeamGroup">Team Group</option>
<option value="Home">Home</option>
</select>
<input type="text" name="Box">
<input type="submit" value="Search">
</form>
</center>
<?php
$host = "localhost";
$user = "root";
$pass = "password";
$db = "Database";
$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
mysql_select_db($db) or die ("Unable to select database!");
if($_REQUEST['Drop']=='MobileNumber') {
$MobileNumber = $_REQUEST['Box'];
$query = "SELECT * From Person WHERE MobileNumber = $MobileNumber";
}
elseif($_REQUEST['Drop']=='Code') {
$Code = $_REQUEST['Box'];
$query = "SELECT * From Person WHERE Code = '$Code'";
}
elseif($_REQUEST['Drop']=='TeamGroup') {
$TeamGroup = $_REQUEST['Box'];
$query = "SELECT * From Person WHERE TeamGroup = '$TeamGroup'";
}
elseif($_GET['Drop']=='FirstName') {
$FirstName = $_REQUEST['Box'];
$query = "SELECT * From Person WHERE FirstName = '$FirstName'";
}
elseif($_GET['Drop']=='Surname') {
$Surname = $_REQUEST['Box'];
$query = "SELECT * From Person WHERE Surname = '$Surname'";
}
elseif($_REQUEST['Drop']=='Home') {
$Home = $_REQUEST['Box'];
$query = "SELECT * From Person WHERE Home = '$Home'";
}
else{
$query = "SELECT * FROM Person";
}
print "<center id=Title>Person Table</center>";
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
if (mysql_num_rows($result) > 0) {
$row = mysql_fetch_assoc($result);
print '<center><table><tr>';
foreach($row as $name => $value) {
print "<th>$name</th>";
}
print '</tr>';
while($row) {
print '<tr>';
foreach($row as $key=>$value) {
if($key=='MobileNumber'){print "<td><a href='/Test.php?MobileNumber=$value'>$value</a></td>";}
elseif($key=='TeamGroup'){print "<td><a href='/Test.php?TeamGroup=$value'>$value</a></td>";}
elseif($key=='Group'){print "<td><a href='/Test.php?Home=$value'>$value</a></td>";}
else{print "<td>$value</td>";}
}
print '</tr>';
$row = mysql_fetch_assoc($result);
}
print '</table></center>';
}
else {
echo "No People found!";
}
mysql_free_result($result);
mysql_close($connection);
?>
</body>
</html>
Problem is even though I've got the search working it only works if I have the full values whereas i want it so say that i put part of someone mobile number in then itll display the mobile numbers that have those parts of the value in it. For example say that a few people had a mobile number starting with 0783 and I type that into the search box I want it to show up all people with 0783 in their mobile number.
What you are looking for is "SELECT * FROM Person WHERE MobileNumber LIKE '%".$_POST['MobileNumber']."%'", which will look for any string that contains the string you want, but may also be longer on either side. For example, "foo" will return the rows with values "foobar", "barfoo", "barfoobar" and of course "foo", but not "fo".
The % is a wildcard here, which means that you can also do something like "SELECT * FROM Person WHERE MobileNumber LIKE '".$_POST['MobileNumber']."%'" if you specifically want to return rows with values starting with your string ("foobar", but not "barfoo" in our example above).
Please also note the " and '.
Also:
Don't use mysql_query. It's depreciated and will be removed in future versions of PHP. Use PDO or mysqli instead.
Your code is definitely not safe. At least use prepared statements to prevent injection. I would advise against using addslashes as it is very prone to resulting in double escapes if you are not paying attention, and as far as you may also want to go the magic_quotes, be aware it is not portable and may cause you trouble if you rely solely on this. Use mysql_real_escape_string instead, as it is very mysql-oriented and specific.
Related
The function of this web application is to: select a customer from the dropdown list (the dropdown list values are auto popup from the database), it will print the selected customer name and its postcode on the result page.
When I choose the customer name from the dropdown list and click the submit button, the result page only prints the $customerv value (the 1st echo), but the $result value (2nd echo) was not printed. The customer name is unique in the database.
index.php:
<?php
require_once('config.php');
?>
<!DOCTYPE HTML>
<html>
<form action="result.php" method="post">
Customer:<br>
<select Customer id="customer" name="Customer">
<option value="">--- Select Customer ---</option>
<?php
$sql = "SELECT b.BPName from BP b where b.BPCode like 'C%' Order by b.BPName";
$customer = mysqli_query($conn, $sql);
while ($cat = mysqli_fetch_array(
$customer,
MYSQLI_ASSOC
)) :;
?>
<option value="<?php echo $cat['BPName']; ?>">
<?php echo $cat['BPName']; ?>
</option>
<?php
endwhile;
?>
</select>
<input type="submit" value="Submit">
</form>
</html>
config.php:
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$databse = "xxx";
$conn = new mysqli($servername, $username, $password, $databse);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
result.php:
<table>
<?php
require_once('config.php');
$customerv = $_POST['Customer'];
echo $customerv;
$sql = "SELECT shiptozipcode FROM BP WHERE BPName ='$customerv'";
$result = $conn->query($sql);
echo $result;
?>
</table>
The query result itself isn't something that's "printable" to the page. It's not just a single value, it's a complex object. You need to fetch the record(s) from the result. For example:
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
echo $row["shiptozipcode"];
}
If you're sure there will be only one row (it's still a good idea to add some error checking anyway) then you don't need the loop:
$result = $conn->query($sql);
$row = $result->fetch_assoc();
echo $row["shiptozipcode"];
But either way, you need to extract the data from the result set. (You could also use fetch_object() instead of fetch_assoc() if you prefer object syntax over array syntax.)
As an aside, be aware that your query is wide open to SQL injection. Now would be a good time to learn how to correct that.
I've recently finished the PHP course on codeacadamy and I'm currently building my first PHP site. This is my first time coding anything so please forgive the fact that my code might be very unorganized and crude. The site is for a scavenger hunt, and the idea is to have a dedicated page for each item of the hunt. I have two tables in my db that the pages access to check data. I've created a template page, which will basically be called in by each dedicated page. My code is all working as intended. I do, however, get a warning that the $game and $question variables have not been used. I understand why I am getting this warning, and that the solution will probably be to convert the majority of my code in scavenger_template.php into a function and do something like
scavenger_function($game, $question); on my individual pages.
My question is, if I leave the code the way it is, will this potentially cause problems in the long run? Is it better/good practice to functionize as much of the code as possible? If you have any tips for good practices or being efficient in coding, it would be greatly appreciated. Codeacademy doesn't really go into much detail about how to actually go about building something.
Thank you!
(game1.php)~(game00.php) dedicated pages
<?php
$game = 1;
$question = "What is 1+1?";
include 'scavenger_template.php';
?>
(scavenger_template.php)
<?php
session_start();
$username = $_SESSION["username"];
$empty_message = "";
$submission_message = "";
$submission_confirm = "";
$row2 = "";
include ('../db_connection.php');
include ('../addPoints.php');
$conn = OpenCon();
/* define game number for each page. game1 in users correlates to id=1 in games. */
/* declaring variables required to check if game has been submitted */
$sql = "SELECT game$game FROM `users` WHERE username = '$username'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result);
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$user_answer = trim(strtolower(($_POST["answer"])));
/*check to see if something is inputed */
if ($user_answer != "") {
/* check if submission is already made. if row = 0, then game hasn't been played */
if ($row[0] === "0") {
/* declaring variables required to check answers in games table */
$sql2 = "SELECT answer FROM `games` WHERE id = '$game'";
$result2 = mysqli_query($conn, $sql2);
$row2 = mysqli_fetch_array($result2);
/* check submitted answer against game table */
if ($user_answer === $row2[0]) {
$sql_value = "SELECT value FROM `games` WHERE id = '$game'";
$result_value = mysqli_query($conn, $sql_value);
$row3 = mysqli_fetch_array($result_value);
addPoints($row3[0], $username, $conn);
$sql3 = "UPDATE users SET game$game='1' WHERE username = '$username'";
mysqli_query($conn,$sql3);
$submission_confirm = "Your answer is correct!";
} else {
$submission_confirm = "Your answer is incorrect.";
$sql3 = "UPDATE users SET game$game='1' WHERE username = '$username'";
mysqli_query($conn,$sql3);
}
} else {
$submission_message = "Your team has already made a submission for this item.";
}
} else {
$empty_message = "Please input an answer.";
}
}
?>
<html>
<head>
</head>
<div align="center">
<form method="post">
<label><?= $question ?></label><br>
<input type="text" id="answer" name="answer"><br><br>
<input type="submit" name="submit" value="Submit Answer"><br>
</form>
<?= $submission_message?>
<?= $empty_message?>
<?= $submission_confirm?>
<br><br>
<form action="../home.php">
<input type="submit" value="Go to home" />
</form>
</div>
</html>
I have a column vehicle_name and I would like 2 dropdown lists of my 2 other columns namely, vehicle_type and vehicle_color.
When these 2 dropdown values are selected and submitted, I would like their intersection to print out the values from vehicle_name. So far my code only generates a dropdown list for vehicle_type, I would need another dropdown for vehicle_colour. Which on submissions populates the intersected values for the vehicle_name. How can I achieve this?
<!DOCTYPE html>
<html>
<body>
<?php
echo "<br>";
echo "<br>";
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";
$db = new mysqli($servername, $username, $password, $dbname);
if (!$db) {
exit('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
?>
<br>
<div class="label">Select vehicle type:</div>
<select name="payment_method">
<option value = "">---Select---</option>
<?php
$queryusers = "SELECT DISTINCT vehicle_type FROM orders";
$db = mysqli_query($db, $queryusers);
while ($d=mysqli_fetch_assoc($db)) {
echo "<option value='{".$d['vehicle_type']."}'>".$d['vehicle_type']."</option>";
}
?>
</select>
<br>
<div class="label_for_time">Select color:</div>
<select name="vehicle_color">
<option value = "">---Select---</option>
<?php
$query_for_color = "SELECT DISTINCT vehicle_color FROM orders";
$db = mysqli_query($db, $query_for_date);
while ($a=mysqli_fetch_assoc($db)) {
echo "<option value='{".$a['vehicle_color']."}'>".$a['vehicle_color']."</option>";
}
?>
</select>
<br>
<br>
<button class="go-btn" type="submit">Go</button>
</body>
</html>
As I don't see any AJAX / client-side code in your above example I assume that this is a pure backend-side filtering you are performing. Your code is currently missing parts of the required elements we would need but let's try to figure this out together:
1. Form around your inputs
Add a <form method="POST" target="path-to-your-script.php"> where "path-to-your-script.php" has to be changed to your PHP file name or rewritten URL path. This has to be around the <select> boxes.
You may also use PHP_SELF to set this automatically, this should work in most cases. I used html_entities($var) to avoid any code injections via manipulated URL.
<form name="test" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
2. Check for POST'ed variable 'vehicle_type'
In your form, check if a search for available colors has been performed:
<?php
$query_for_color = "SELECT DISTINCT vehicle_color FROM orders";
// check if the form variable 'vehicle_type' is available; if so, filter entries.
if (isset($_POST['vehicle_type'])) {
$vType= filter_var($_POST['vehicle_type'], FILTER_SANITIZE_STRING);
$query_for_colors .= ' WHERE vehicle_type = \''.$vType.'\'';
}
$db = mysqli_query($db, $query_for_date);
while ($a=mysqli_fetch_assoc($db)) {
echo "<option value='{".$a['vehicle_color']."}'>".$a['vehicle_color']."</option>";
}
?>
Edit:
As pointed out by one user in the comment, filter_var($var, FILTER_SANITIZE_STRING) won't be enough to avoid potential SQL injections. This was just a recommendation and was not part of the question at all. If you have to work with user data, do more than using filter_var(), instead use either prepared statements or properly escape the user data. There are many tutorials like this one out there that will guide you to safe queries.
i want to retrieve data in database by using search engine i create.
it pass the search keywords from testseach.php to searchTitle.php.
here is my code for test seach.php
>!DOCTYPE html>
<html>
<head><title></title>
</head>
<body>
<form action="searchTitle.php" method="GET" class="formright">
<input type="text" name="keywords" placeholder="Search">
<input type="submit" value="search">
</form>
</body>
</html>
here is my searchtitle.php which pass the keywords from testsearch.
<? php
require_once 'database_conn.php'
//collect search title
if(isset($_GET['keywords'])){
$searchq = $_GET['keywords'];
$searchq = preg_replace("#[^a-z]#i" , "", $searchq);
$query = mysql_query("SELECT eventTitle FROM te_events where eventTitle LIKE '%searchq%'") or die("could not search!");
$count = mysqli_num_rows($query);
if($count==0){
echo "<p>There was no search result!</p>\n";
}
else{
while ($row = mysql_fetch_assoc($query)){
$title = $row['eventTitle'];
$id = $row['eventID'];
echo "<p>$title</p>\n";
}
}
}
?>
however, it shows this error
There was no search result! \n"; } else{ while ($row =
mysql_fetch_assoc($query)){ $title = $row['eventTitle']; $id =
$row['eventID']; echo " $title
\n"; } } } ?>
i pretty sure that my database connection is working and i don't see any typo in my code.
can anyone tell me what's is my problem?
There are some mistake
1)$query = mysql_query("SELECT * FROM countries",$connection) or die("could not search!");
In mysql_query you add connection variable
please refer syntax as per php documentation
2) You use $count = mysqli_num_rows($query); for get number of raw but you use mysql_num_rows instead of mysqli_num_rows
OR
Please check php version and that compatible with mysql or mysqli
please check it also because that may cause that type of issue also
this answer may be help you.
I just started learning php and mysql and i might already be way ahead of myself. The thing i would like to create is a webpage where ppl can sign up for an event, so far so good, the form to submit their first name, last name, age and email adress is working and its actually sending te information to the database.
Next thing i want to create is a page where i can display all the database records submitted (except for the email adress). This is also working, but I wanted to play around with dynamic urls.
When i visit my page http://www.example.com/ppl.php?id=1 i get the information of the first database record displayed but i also wanted to see if i could get this to work with names instead of ids so i tried to edit my code and use http://www.example.com/ppl.php?name=john this does only return an error and however there are a few people called john in the database no records are displayed.
So i would like to know if what i want is actually possible and how do i get this to work with my current code.
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "event";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$id = $_GET['id'];
$firstname = 'firstname';
$lastname = 'lastname';
$age = 'age';
$sql = "SELECT * FROM people WHERE id = $id";
$result = $conn->query($sql);
echo "<table id='display' width='600' align='center'>";
echo"<tr><td> Firstname</td> <td> Lastname</td> <td> Age</td>";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo"<tr><td width='33%'> $row[$firstname]</td> <td width='33%'> $row[$lastname]</td> <td width='33%'> $row[$age] cm</td></tr>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Try to change the query:
$sql = "SELECT * FROM people WHERE id = $id";
To:
$name = $_GET['name'];
$sql = "SELECT * FROM people WHERE name LIKE '%$name%'";
Then echo for each one John you find.
Also consider using CSS like this.
<style>
#display {
width: 600px;
}
#display td {
width: 33%;
}
</style>
You should be looking for two separate $_GET keys: id OR name.
<?php
if (isset($_GET['id'])) {
// logic to get row by ID
} elseif (isset($_GET['name'])) {
// logic to get row by Name
} else {
// logic if no $_GET keys are set
}
I would recommend not using the name field for a find because it's not a primary key in your database - it may not be unique. Your query may return multiple results depending on what data is being stored.
Edit: To answer the question of where to place this in the code sample above, consider placing it where the query string is declared.
<?php
if (isset($_GET['id'])) {
$id = $_GET['id'];
$sql = "SELECT * FROM people WHERE id = $id";
} elseif (isset($_GET['name'])) {
$name = $_GET['name'];
$sql = "SELECT * FROM people WHERE name = '$name'";
}
From there you can keep the same query execution logic. But as I stated, I'd advise against using the name field as a key because it may not be unique.