I have a database with vehicle information in it (make, model, year, branch, etc)
I need to create a search form to search this database. The search form consists of 4 selection boxes and two text boxes.
Please find the code below trying to query the database:
<?php
$dbName = "F:/Domains/autodeal/autodeal.co.za/wwwroot/newsite/db/savvyautoweb.mdb";
// Throws an error if the database cannot be found
if (!file_exists($dbName)) {
die("Could not find database file.");
}
// Connects to the database
// Assumes there is no username or password
$conn = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$dbName", '', '');
if (isset($_REQUEST['submit'])) {
$searchMake = addslashes($_POST['makeSelection']);
$searchModel = addslashes($_POST['modelSelection']);
$searchBranch = addslashes($_POST['branchSelection']);
$searchYear = addslashes($_POST['yearSelection']);
$minPrice = addslashes($_POST['minPriceSelection']);
$maxPrice = addslashes($_POST['maxPriceSelection']);
$sql = "SELECT Id, Make, Model, Year, Price, SpecialPrice, Branch, StockNO FROM Vehicle WHERE Price >= '$minPrice' AND Price <= '$maxPrice' AND Make LIKE '$searchMake' AND Model LIKE '$searchModel' AND Branch LIKE '$searchBranch' AND Year LIKE '$searchYear'";
$rs = odbc_exec($conn, $sql);
} else {
$sql = "SELECT Id, Make, Model, Year, Price, SpecialPrice, Branch, StockNO FROM Vehicle ORDER BY Make";
$rs = odbc_exec($conn, $sql);
}
echo "\t" . "<tr>\n";
echo "\t" . "<th>Make</th><th>Model</th><th>Year</th><th>Price</th><th>Special Price</th><th>Location</th><th>Stock Number</th>" . "\n";
while (odbc_fetch_row($rs)) {
$id = odbc_result($rs, Id);
$make = odbc_result($rs, Make);
$model = odbc_result($rs, Model);
$year = odbc_result($rs, Year);
$price = odbc_result($rs, Price);
$specialPrice = odbc_result($rs, SpecialPrice);
$branch = odbc_result($rs, Branch);
$stockNo = odbc_result($rs, StockNO);
echo "\t" . "<tr>\n";
echo "\t\t" . "<td>" . $make . "</td><td><a href=/newsite/selected-vehicles?Id=$id>" . $model . "</a></td><td>" . $year . "</td><td>" . $price . "</td><td>" . $specialPrice . "</td><td>" . $branch . "</td><td>" . $stockNo . "</td>\n";
echo "\t" . "</tr>\n";
}
odbc_free_result($rs);
odbc_close($conn);
// This message is displayed if the query has an error in it
if (!$rs) {
exit("There is an error in the SQL!");
}
?>
When I run this script, "there is an error in the SQL" message appears.
Any help would be greatly appreciated.
Thannk you
The sql query which you are making depending upon the user inputs should be modified as there is huge chances it will fail as user may or may not enter all the text boxes. Basically, you you create dynamic query with if else conditions
$sql = "SELECT Id, Make, Model, Year, Price, SpecialPrice, Branch, StockNO FROM Vehicle WHERE 1 = 1;
if ($minPrice > -1 )
{
$sql .= $sql " and Price >= $minPrice ";
}
Similarly for others and in comparison operators > < you shouldn't add single quotes with price.
Try to print your query and check how is it formed-
Related
I'm trying to compare products and I'm already finished. I just have a problem that my product features are not under the right product names because I need to fill the gaps between with empty <td></td>.
Here is my code from the function that fills the values.
function datatable($id)
{
$conn = connection();
$productPost = $_POST["product"];
$sqlSpecTitle = "Select title as title from product where uid = '$id'";
$resultTitle = mysqli_query($conn, sqlSpecTitle) or die("database error:" . mysqli_error($conn));
foreach ($productPost as $product)
{
$sqlSpecValue = "Select productname, title, value from text join product on uid = uid join feature on uid = uid where productname = '$product" and uid = '$id';
$resultValue = mysqli_query($conn, $sqlSpecValue or die("database error:" . mysqli_error($conn));
if(mysqli_num_row($resultValue) > 0
{
while($row = mysqli_fetch_assoc($resultTitle))
{
echo "<td>" . $row['title'] . "<td>";
}
while ($row = mysqli_fetch_assoc($resultValue))
{
if($row['value'] == null)
{
echo "<td>" . "empty" . "<td>";
}
else
{
echo "<td> . $row['value'] . "</td>";
}
}
}
}
}
The productnames are getting filled in another function that is as much the same.
function headerTable()
{
$conn = connection();
$productPost = $_POST["product"];
foreach ($productPost as $product) {
$sqlSpecValue = "SELECT productname, title, value from text
join product on uid = uid
join feature on uid = uid
where productname = '$product';
$resultValue = mysqli_query($conn, $sqlSpecValue) or die("database error:" . mysqli_error($conn));
$row = mysqli_fetch_assoc($resultValue);
echo "<td id='product'>" . $row['productname'] . "</td>";
}
}
You make a "join" over between your tables, so you only get data if you have something in "text" table.
Just switch to "right join" and it should work.
I am trying the approach of 'adding a log just before the php query'; in effort to achieve the ability to print a 'time stamp' when my mySQL database has been updated.
my queries look like this.
require_once('include/connect.php');
$q = $_GET['q'];
//echo $q;
//$plan=substr($q,0,4);
//$spec=substr($q,4);
list($plan, $ptype, $spec) = explode('_', $q);
//echo $plan . ", " . $spec;
//$query="SELECT vphp.tbl_provider_types.`TYPE` from coolDB.tbl_provider_types where vphp.tbl_provider_types.".$q." = 'Y';";
$query= "SELECT tbl_sourcespecheader.specID, coolDB.tbl_sourcespecheader.Specialty_Header from vphp.tbl_provider_types left join coolDB.tbl_sourcespecheader on coolDB.tbl_provider_types.ID = coolDB.tbl_sourcespecheader.TypeID where coolDB.tbl_provider_types.ID = " . $spec . " and coolDB.tbl_sourcespecheader." . $plan . " = 'Y';";
$result = mysqli_query($connection, $query);
//Populate result in HTML which will be returned via AJAX
echo "<h4>Please select from these " . $ptype . " specialties:</h4>";
echo "<select id='type' multiple='' name='specialty'><option selected="selected" value="nospec"></option>";
while($row = mysqli_fetch_array($result))
{
echo "<option value='" . $row['specID'] . "'><a href='#' id='" . $row['specID'] . "' onclick='getSelected(this.id);return false' style='text-decoration: none'>" . $row['Specialty_Header'] . "</a></option>";
}
echo "</select>";
//Close database connection
mysqli_close($connection);
Better use triggers. You need to create log table to be able to insert all data you needed. Below is the example.
DELIMITER $$
CREATE TRIGGER before_employee_update
BEFORE UPDATE ON employees
FOR EACH ROW
BEGIN
INSERT INTO employees_audit
SET action = 'update',
employeeNumber = OLD.employeeNumber,
lastname = OLD.lastname,
changedat = NOW();
END$$
DELIMITER ;
If you are using phpMyadmin. Go to that and find the trigger menu. There you can create triggers.
How to show the average of a column in mysql?
Below is my code which i have tried so far :
<?php
if (isset($_GET["age"]));
$age = ($_GET["age"]);
include($_SERVER["DOCUMENT_ROOT"] . "/includes/config.php");
// Input
$sql = "SELECT AVG(column_name) FROM table_name";
// Check age
if ($age > 99 or $age < 5) {
echo ("We only store data of people between the age of 5 and 99.");
if (!mysqli_query($conn, $sql)) {
die('Error: ' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)));
}
}
else {
echo ("We got it!");
}
// Close connection
((is_null($___mysqli_res = mysqli_close($conn))) ? false : $___mysqli_res);
die();
?>
But how to exactly define a variable to the result of the AVG with a maximum of 2 decimals?
I want to used and show it into another file (so I will include this one).
What I have right now
<?php
if (isset($_GET["age"]));
$age = ($_GET["age"]);
include($_SERVER["DOCUMENT_ROOT"] . "/3/includes/config.php");
include($_SERVER["DOCUMENT_ROOT"] . "/3/includes/opendb.php");
// My own created code
$sql = $conn->query("SELECT ROUND(AVG(price AS FLOAT), 2) FROM data WHERE age= '$age'");
$data = $sql->mysqli_fetch_assoc();
$avg_data = $data['price'];
echo $avg_data;
// This below is from an other post but don't know how it works and if it is good.
$ratings = $conn->query("SELECT AVG(price) avg_rating FROM data form_id = '" . $age . "'");
$data2 = $ratings->mysqli_fetch_assoc();
$avg_rating = $data2['avg_rating'];
echo $avg_rating;
die();
?>
Use Like This For Getting Average witth two decimal points.
$sql = "SELECT ROUND(AVG(column_name AS FLOAT), 2) FROM table_name";
How I fixed it:
<?php
if (isset($_GET["age"])) {
$age = ($_GET["age"]);
include($_SERVER["DOCUMENT_ROOT"] . "/3/includes/config.php");
$con=mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT AVG(price) FROM data WHERE age= '$age'") or die("Error: " . mysqli_error($con));
while($row = mysqli_fetch_array($result)) {
echo $row['AVG(price)'];
echo number_format($row['AVG(price)'], 2);
}
die();
}
else {
echo 'Something went wrong, try again.';
}
?>
$sql = 'SELECT *, ROUND(AVG(column_name), 2) AS avg_value FROM table_name';
avg_value will store the rounded + average value and add * if need to get all the column.
I have an advanced search query which queries a database. The search works fine and prints the desired results when a user searches something that is IN the database.
I've set up a condition when if a user searches something and that something couldn't be found in the database, it displays a message that the record could not be found.
But it's not displaying the message I need it to. Instead, if it can't find the record, it prints an empty table with headings. This table is only supposed to be printed if something is found.
No if I swop the condition from >= -1 to just == -1 it displays the message I need it to when something couldn't be found even if that something is in the database.
I hope this makes sense.
Please see my code below.
<table class="table table-bordered table-striped" style="width: 100%;">
<?php
$dbName = "F:/Domains/autodeal/autodeal.co.za/wwwroot/newsite/db/savvyautoweb.mdb";
// Throws an error if the database cannot be found
if (!file_exists($dbName)) {
die("Could not find database file.");
}
// Connects to the database
// Assumes there is no username or password
$conn = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$dbName", '', '');
$searchMake = addslashes($_POST['makeSelection']);
$searchModel = addslashes($_POST['modelSelection']);
$searchBranch = addslashes($_POST['branchSelection']);
$searchYear = addslashes($_POST['yearSelection']);
$minPrice = addslashes($_POST['minPriceSelection']);
$maxPrice = addslashes($_POST['maxPriceSelection']);
$sql = "SELECT Id, Make, Model, Year, Price, SpecialPrice, Branch, StockNO FROM Vehicle ";
if ($searchMake || $searchModel || $searchBranch || $searchYear || $minPrice || $maxPrice) {
$sql .= "WHERE ";
}
$combine = '';
if ($minPrice) {
$sql .="{$combine}Price BETWEEN $minPrice "; $combine = 'BETWEEN ';
}
if ($maxPrice) {
$sql .="AND $maxPrice "; $combine = 'AND ';
}
if ($searchMake) {
$sql .="{$combine}Make LIKE '%$searchMake%' "; $combine = 'AND ';
}
if ($searchModel) {
$sql .="{$combine}Model LIKE '%$searchModel%' "; $combine = 'AND ';
}
if ($searchBranch) {
$sql .="{$combine}Branch LIKE '%$searchBranch%' "; $combine = 'AND ';
}
if ($searchYear) {
$sql .="{$combine}Year LIKE '%$searchYear%' "; $combine = 'AND ';
}
$rs = odbc_exec($conn, $sql);
if (odbc_num_rows($rs) >= -1) {
echo "\t" . "<tr>\n";
echo "\t" . "<th>Make</th><th>Model</th><th>Year</th><th>Price</th><th>Special Price</th><th>Location</th><th>Stock Number</th>" . "\n";
while (odbc_fetch_row($rs)) {
$id = odbc_result($rs, Id);
$make = odbc_result($rs, Make);
$model = odbc_result($rs, Model);
$year = odbc_result($rs, Year);
$price = odbc_result($rs, Price);
$specialPrice = odbc_result($rs, SpecialPrice);
$branch = odbc_result($rs, Branch);
$stockNo = odbc_result($rs, StockNO);
echo "\t" . "<tr>\n";
echo "\t\t" . "<td><a href=/newsite/selected-vehicles?Id=$id>" . $make . "</td><td><a href=/newsite/selected-vehicles?Id=$id>" . $model . "</a></td><td>" . $year . "</td><td>" . $price . "</td><td>" . $specialPrice . "</td><td>" . $branch . "</td><td>" . $stockNo . "</td>\n";
echo "\t" . "</tr>\n";
}
} else {
echo "We don’t have the vehicle you are looking for right now, but send us your vehicle requirements and we will be sure to find you one!";
}
odbc_free_result($rs);
odbc_close($conn);
// This message is displayed if the query has an error in it
if (!$rs) {
exit("There is an error in the SQL!");
}
?>
</table>
As a general rule, odbc_num_rows() is not a reliable way to determine the number of rows returned by a SELECT query. As mentioned in the "Notes" section of the PHP documentation:
Note:
Using odbc_num_rows() to determine the number of rows available after a SELECT will return -1 with many drivers.
That is indeed the case with the Access ODBC driver.
Instead of using odbc_num_rows() you could check the result of the first odbc_fetch_row() to see if it is TRUE and, if so, proceed with dumping the data to the HTML table. If the first call to odbc_fetch_row() returns FALSE then no rows were retrieved and you can display your message.
I am trying to use AES_DECRYPT in MySQL to decrypt a successfully encrypted SSN. In the output I get the word "Array" instead of the actual data from that field. My PHP and MySQL knowledge is a bit rusty, so I'm sure it's something silly I overlooked. Any help would be appreciated.
OUTPUT:
verify_name other_names ssn dob
: test : test : Array : test
CODE:
$key="88b871WZ3SntWK67rN3l2J1SvMqsOjyk";
$SQLstring = "SELECT * FROM applications";
$QueryResult = #mysql_query($SQLstring, $conn) or die("Query Problem - "
. mysql_error($conn) . " - Error Number - "
. mysql_errno($conn));
echo "verify_name other_names ssn dob";
$num_result = mysql_num_rows($QueryResult);
for ($i = 0; $i < $num_result; $i++)
{
$row = mysql_fetch_array($QueryResult);
$SQLstring2 = "SELECT AES_DECRYPT(ssn,'$key') FROM applications WHERE name='" . $row["name"] . "'";
$QueryResult2 = #mysql_query($SQLstring2, $conn) or die("Query Problem - "
. mysql_error($conn) . " - Error Number - "
. mysql_errno($conn));
$num_result2 = mysql_num_rows($QueryResult2);
for ($j = 0; $j < $num_result; $j++){
$ssndecrypt = mysql_fetch_array($QueryResult2);
echo $ssndecrypt[0];
}
echo $row["verify_name"];
echo $row["other_names"];
echo $ssndecrypt;
echo $row["dob"];
It's because you're fetching the result as an array.
$ssndecrypt = mysql_fetch_array($QueryResult2);
...
echo $ssndecrypt;
It's echoing Array because you never reassign the $ssndecrypt variable.
The core of the problem, however, seems to be that you're needlessly complicating your queries. There's no reason to query the table twice when you can just do:
SELECT verify_name,
other_names,
dob,
AES_DECRYPT(ssn,'$key') AS ssn
FROM applications
This simplifies the code quite a bit:
$stmt = "SELECT verify_name, other_names, dob, AES_DECRYPT(ssn,'$key') AS ssn FROM applications";
$result = #mysql_query($stmt, $conn) or die("Query Problem - " . mysql_error($conn) . " - Error Number - " . mysql_errno($conn));
echo "verify_name other_names ssn dob";
while ($row = mysql_fetch_assoc($result))
{
echo $row["verify_name"];
echo $row["other_names"];
echo $row["ssn"];
echo $row["dob"];
}
Ideally, though, you should be using PDO instead of the mysql_* functions:
try {
$dbh = new PDO('mysql:host=localhost;dbname=mydb', $user, $pass);
foreach($dbh->query("SELECT verify_name, other_names, dob, AES_DECRYPT(ssn,'$key') AS ssn FROM applications") as $row) {
echo $row["verify_name"];
echo $row["other_names"];
echo $row["ssn"];
echo $row["dob"];
}
$dbh = null;
} catch (PDOException $e) { die("ERROR: " . $e->getMessage()); }