PHP form search for MySQL DB - php

I need some help getting a search function to work. I have previously coded something to work similar to this, where if I click on a hyperlink, I'm able to carry a variable forward and then assign this into an SQL script so it pulls only this one thing back from the DB. (Predefined variable, and not user input). I've tried modifying the script I've been using to allow for a form based text box to have user input which is then searched through a single database field, with a LIKE statement.
This is what I have, and it's not returning anything.
Input Form
<form class="formFormat" method="post" action="SearchResult.php">
<label class="lableInput2">Key Words</label>
<input type="text" class="textInput" name="JobDetails" />
<input type="image" src="img/blue/buttonsearch.jpg" value="search" class="buttonInput" alt="Submit Form" border="0" />
</form>
Returning Page
<?php
include('conn_mysql.inc');
include('corefuncs.php');
// create database connection
$conn = dbConnect('query');
// initialize flag
$deleted = false;
// get details of selected record
if ($_GET && !$_POST) {
// check that primary key is numeric
if (isset($_GET['JobDetails']) && is_numeric($_GET['JobDetails'])) {
$JobDetails = $_POST['JobDetails'];
}
else {
$JobDetails = NULL;
}
if ($JobDetails) {
$sql = "SELECT * FROM jobs WHERE JobDetails LIKE '%JobDetails%'";
$result = mysql_query($sql) or die (mysql_error());
$row = mysql_fetch_assoc($result);
}
}
?>
<p><h1><?php echo ($row['JobTitle'].'<span class="jobid"> #'.$row['IDJobs'].'</span>');?></h1></p>
<p><strong><?php echo ($row['Location']); ?></strong></p>
<p><strong>£<?php echo ($row['JobValue']); ?>.00</strong></p>
<p><strong>www.companyurl.com - BAD IDEA?</strong></p>
<p><strong>Open for Bidding</strong></p>
<br />
<p><span class="jobid">Job Posted: <?php echo ($row['JobPostDate']); ?></span></p>
<p><?php print ($row['JobDetails']); ?></p>
<p><span class="jobid">Job Deadline: <?php echo ($row['JobDeadline']); ?></span></p>
I know that I need to loop the output, so it displays more than one, but at the moment it simply returns the following error for every field (obv the line changes depending on what's trying to extract.
"( ! ) Notice: Undefined variable: row in
C:\wamp\www\ReEmployWork\SearchResult.php on line 54"
Can anyone assist? I'm a bit lost with this, and I believe I'm either going in the wrong direction or just missing something.

You missed $ before the variable name. Instead of:
$sql = "SELECT * FROM jobs WHERE JobDetails LIKE '%JobDetails%'";
write:
$sql = "SELECT * FROM jobs WHERE JobDetails LIKE '%$JobDetails%'";

You left your $ before JobDetails in you query.
Also remeber to use http://php.net/manual/en/function.mysql-real-escape-string.php
A suggestion:
$escaped_value = mysql_real_escape_string($JobDetails)
$sql = "SELECT * FROM jobs WHERE JobDetails LIKE '%$escaped_value%'";

For future readers. I scrapped the code I tried to modify and I took it from the beginning. There's enough information above for anyone to do this. Have a go, and you may end up with a result similar to what I coded.
$JobDetails = $_POST['JobDetails'];
$JobDetails = mysql_real_escape_string($JobDetails);
$sql = "SELECT * FROM `jobs` WHERE `JobDetails` LIKE '%{$JobDetails}%'";
$result = mysql_query($sql) or die (mysql_error());
?>
The above is what I coded and it runs like a dream. You make a lot more mistakes modifying code than you do, if you just code from scratch, so if you're learning dabble and play with code already wrote, but if you need something yourself which is unique then you're best starting from scratch.

Related

In PHP MySQL query returns EVERY row. In MySQL Workbench, it works correctly

I have a very simple PHP form:
<form action="listtenants.php" method="post">
Search for Tenant: <input name="term" type="text" value="" />
<input name="Submit" type="submit" />
</form>
At first I thought, the data was posting incorrectly; but after viewing the headers with LiveHTTP headers, it turns out it is posted correctly.
Here is my PHP script. Like I said, the query works correctly in MySQL workbench; however in the PHP script, every row is returned. Does anyone know why this could be? Even echoing the posted variable returns the expected string. Not sure what gives here.
<html>
<body>
<?php
$connect = mysql_connect("host","user","pass");
mysql_select_db("db", $connect);
$term = $_GET['term'];
$query = "SELECT itemid, first, last FROM tenants where CONCAT(first, last) LIKE '%$term%'";
$getUserid = mysql_query($query);
//$i = 0;
$records = mysql_num_rows($getUserid);
while($row_sections = mysql_fetch_array($getUserid))
{
echo "$row_sections[0] $row_sections[1] $row_sections[2]";
?>
<br><br>
<?php
}
?>
</body>
</html>
This is a terrible query and highly dangerous. BUT.. ..your issue is simple.
Your form submits via _POST, and your looking for variables using _GET.
$term = $_GET['term'];
will always be empty, so your query matches on '%%' - ie: everything!
Change it to:
$term = $_POST['term'];
..then go read about MySQL injections and follow the links in the comments to your post.

Query result into variable

I'm making a website. I want it so that I can put records into the database via my website. So first I need to select the id from which record I want to change. Then I want to put the values of the selected id into a variable. The I want to put the variable into a form value.
I'm trying to make something similar to phpmyadmin. If you click on the pencil you go to a form were everything is complete and you can just change the things you want to change and save it into the database.
wijzigen.php:
<form id="form1" name="form1" method="post" action="set_wijziging.php">
<h1>Selecteer het vuurwerkid van het product dat u wilt wijzigen</h1>
<p>Vuurwerkid <br>
<input type="text" name="vuurwerkid" id="vuurwerkid" />
<input type="submit" name="wijzigen" id="wijzigen" value="wijzigen"/>
</form>
and here is the part were I put what I typed in in the form into a variable.
<?php
$vuurwerkid=$_POST["vuurwerkid"];
?>
Then I'm trying to make a query wich only selects the things were vuurwerkid='$vuurwerkid'
So here I try to put the results of the query into a variable. But this doesn't seem to work.
set_wijziging.php:
<?php
include("connect.php");
$vuurwerkid=$_POST["vuurwerkid"];
$query = "SELECT * FROM vuurwerk_info WERE vuurwerkid='$vuurwerkid'";
$resultaat = MySQL_query($query);
while ($row = MySQL_fetch_array($resultaat))
{
$vuurwerkid="$row["vuurwerkid"]";
$naam=$row["naam"];
$prijs=$row["prijs"];
$soort=$row["soort"];
$cat_vuurwerk=$row["cat_vuurwerk"];
$aantal=$row["aantal"];
}
?>
I'm just started learning PHP
Your where spelling is wrong in your query
Try this
$query = "SELECT * FROM vuurwerk_info WHERE vuurwerkid='$vuurwerkid'";
I miss that last time Change this line as well
$vuurwerkid="$row["vuurwerkid"]";
To this
`$vuurwerkid=$row["vuurwerkid"];
//Remove the Double queite. As its variable not string`
although function name are case-incensitive. But change theese lines as well
chnage this
$resultaat = MySQL_query($query);
while ($row = MySQL_fetch_array($resultaat))
To this
$resultaat = mysql_query($query);
while ($row = mysql_fetch_array($resultaat))
Note I change nothing in the below line. I just used the small letter to right those function
Please learn MYSQLI_ OR PDO
As mysql function are depriciated.
You should change your $query to
$query = "SELECT * FROM vuurwerk_info WHERE vuurwerkid='$vuurwerkid'";
Also try to echo your query to see if it's correct.
Finally as others pointed out you should stop using mysql_* and switch to msqli or PDO.

Adding to a value in a table on the press of a button on a webpage?

I am very new to SQL and to say the least, I am struggling.
My table looks like this:
All I want to do is be able to increment any of these values by one upon the press of a button, like this:
This is how it looks on the website, but nothing is functional at all yet.
I have an understanding of HTML, CSS, and PHP, so if I were to know the correct way to do this with SQL, I should be able to implement it.
Thanks.
Ok, I see people suggesting AJAX ("elsewhere" as well as here), but you are unfamiliar with this. I'm going to suggest a completely non-Javascript solution, sticking with HTML, PHP, and MySQL, as you already know these. I would definitely recommend learning Javascript at some point though.
I've no idea of your level of understanding, so please let me know any bits of the following code you don't follow, and i'll explain in more detail.
<?php
/* Initialise the database connection */
$db = new mysqli("localhost", "username", "password", "database");
if ($db->connect_errno) {
exit("Failed to connect to the database");
}
/* First, check if a "name" field has been submitted via POST, and verify it
* matches one of your names. This second part is important, this
* will end up in an SQL query and you should NEVER allow any unchecked
* values to end up in an SQL query.
*/
$names = array("Anawhata","Karekare","Muriwai","Piha","Whatipu");
if(isset($_POST['name']) && in_array($_POST['name'], $names)) {
$name = $_POST['name'];
/* Add 1 to the counter of the person whose name was submitted via POST */
$result = $db->query("UPDATE your_table SET counter = counter+1 WHERE name = $name");
if(!$result) {
exit("Failed to update counter for $name.");
}
}
?>
<table>
<?php
/* Get the counters from the database and loop through them */
$result = $db->query("SELECT name, counter FROM your_table");
while($row = $result->fetch_assoc()) {
?>
<tr>
<td>
<p><?php echo $row['name'];?></p>
<form method="POST" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
<input type="hidden" name="name" value="<?php echo $row['name']; ?>" />
<input type="submit" name="submit" value="Add One" />
</form>
</td>
<td><?php echo $row['counter']; ?></td>
</tr>
<?php
} // End of "while" each database record
?>
</table>
One way is to use AJAX on sending the form to make calls to a php script that handles the mysql query and "adds one". You should put a hidden input with the name of the person you want to increment. That's if you don't want to refresh the page.
If you don't mind refreshing, make every button part of a form, and send to the same php file.
I recently came across a library, called meteor.js that is capable of doing all this. I have not yes tested it, though.

php select to get a variable and then apply if else on it

I have a car rental system I am working on. When a user rents a car, the system should first check if the number of available cars is greater than 0, if yes, then make the adjustment "AVAILABLE = AVAILABLE+1" (in the MySQL table which keeps track of cars), which means, rent the car to the user. Also, I am trying to record which car went to which user. So I have another database table called rentalrecords which takes in the values of the Username of the logged in user, and ID of the car rented. Now, the problem is, my 'IF-ELSE' part is not executing as desired.
<div id="stylized" class="myform">
<form id="form" name="form" method="POST" action="renting.php" >
<h1>Rent a Car</h1>
<label>Car ID
<span class="small">eg. Enter 1 for Mer1</span>
</label>
<input type="text" name="ID" id="ID" />
<input type="submit" style="margin:30px 100px;" name="submit" value="Check-Out">
<div class="spacer"></div>
</form>
</div>
Now,the action of this form, which is renting.php, is as follows:
<?php
session_start();
if(!session_is_registered(theUSERNAME)){
header("location:customer_login.php");
}
mysql_CONNECT("xx", "xx", "xx") OR DIE("Unable to connect");
mysql_SELECT_DB("xx") OR DIE("Unable to select database");
$ID = $_POST['ID'];
$result = mysql_query("SELECT AVAILABLE FROM car WHERE ID='$ID'");
if(mysql_fetch_array($result)>0)
{
$query="UPDATE car SET AVAILABLE=AVAILABLE-1 WHERE ID='$ID'";
mysql_query($query);
$query = "insert into rentalrecords (USERNAME,ID,RENTED_ON) values ('$_SESSION[theUSERNAME]','$_POST[ID]',CURDATE())";
$result = mysql_query($query);
header("location: list_Clogged.php");
}
else
{
echo "<script>alert('The car you chose is currently unavailable!'); location.href='rent.php';</script>";
}
?>
Even though I have available=0, it still is NOT executing the else part and no matter what, it always executes the IF part. The ID and AVAILABLE are the attributes of my MySQL table called 'car' and the in rental records table i just want to insert these values. I am aware that the script is vulnerable to injection at the moment, but first I want to get things working! Any immediate help would be much appreciated.
You're trying to count a resource...
if(mysql_fetch_array($result)>0)
You need to obtain the results and then count an item within those results:
$res = mysql_fetch_assoc($result);
if($res[0]['AVAILABLE'] > 0)
Note $res[0] means first row of the results. You can also use mysql_fetch_row to obtain a single result.
Keep in mind, mysql_ functions shouldn't be used at all. Look into switching to mysqli or PDO.
Also, you need to sanitize input. You're just blindly accepting $_POST['ID']
The mysql_fetch_array function doesn't do what you think it does; it returns an array, not a single value.

Form values populated with old variable

I am trying to create a page where users can edit information.
I can can populate the form with values from an array and update them, however, when it is saved and visited again with different array info it displays the previous form data. I have looked at clearing the cache and setting the array to NULL after the page has been submitted but neither of these have worked!
Here is what i have:
$id = ($_GET['id']);
function get_edit_event_details() {
global $connection;
$query = 'SELECT *
FROM events
WHERE id = "$id"';
$event_details = mysql_query($query, $connection);
confirm_query($event_details);
return $event_details;
echo $query;
}
$event_details = get_event_details();
$details = mysql_fetch_array($event_details);
and to populate the form values (I have also tried autocomplete="off" which has not worked either)
<input type="text" name="event_date" id="event_date" size="27" value="<?php echo $details["date"];?>" autocomplete="off" />
I am relatively new to PHP and have been able to solve every problem I have come across apart from this one!
I know that maybe this is not a real answer, but I'd like to point out some things:
Your ID should be casted to INT, as now you're vulnerable to injections.
So, it should be $id = intval($_GET['id']);
How is your ID passing to the function? it's outside, and not passed as a parameter, nor made global. I believe this could be the issue, as your query will always be without and ID to use as a condition. Try with:
get_edit_event_details($id){}
Personal taste maybe, but using 2 functions and and external call to the return value, just to fetch results it's a bit smelly. I'd rewrite the whole thing as:
function get_edit_event_details($_GET['id'])
{
global $connection;
$id = intval($_GET['id']);
$query = "SELECT * FROM events WHERE id = '$id'";
$result = mysql_query($query, $connection) or trigger_error('Query error: '.mysql_error());
if(mysql_num_rows($result) > 0)
{
return mysql_fetch_array($result);
}
else
{
return FALSE;
}
}
if($details = get_edit_event_details($_GET['id']) :?>
<input type="text" name="event_date" id="event_date" size="27" value="<?php echo $details["date"];?>" autocomplete="off" />
<?php endif;?>
Keep in mind that this is still not perfect code, I know, kinda smell mine too :). You might want to check if $_GET['id'] is set also, inside or outside the function.

Categories