Display MYSQL Data From a Menu - php

I have a MYSQL database with a number of fields such as property, bedrooms, size etc
I have two dropdown list with data that is contained within the database
When submitting the options I want a new page to open displaying the results. I am getting the error message mysql_fetch_assoc(): supplied argument is not a valid MySQL and have no idea how to fix this! help much appreciated...I know about SQL injections and looking to rectify this after I get this section working first
HTML
<form method="get" action="submit.php">
Number: <select name="property">
<option value="Aviemore House">Aviemore House</option>
<option value="Dalfaber House">Dalfaber House</option>
</select>
<br>
Name: <select name="bedrooms">
<option value="2">2</option>
<option value="3">3</option></select>
<br>
<input type="submit" value="submit" />
</form>
PHP
<?php
require 'defaults.php';
require 'database.php';
$property = $_GET['property'] ;
$bedrooms = $_GET['bedrooms'] ;
$query = "select FROM properties where property = '$property' & bedrooms = '$bedrooms'";
while ($row = mysql_fetch_assoc($result))
{
$r[] = $row;
}
?>

You forgot to execute your query!
<?php
require 'defaults.php';
require 'database.php';
$property = $_GET['property'] ;
$bedrooms = $_GET['bedrooms'] ;
$query = "select FROM properties where property = '$property' & bedrooms = '$bedrooms'";
$result = mysql_query($query); // <-- You forgot this
while ($row = mysql_fetch_assoc($result))
{
$r[] = $row;
}
?>

Try this instead:
$query = "SELECT * FROM `properties` WHERE property = '{$property}' AND bedrooms = '{$bedrooms}'";
$row=mysql_query($query);
Your sql is malformatted and need to execute the query.

Related

Use mysql query result in more than one place in code

I'm building a system that tracks contact lenses. I'm storing the contact lens info in a database as sometimes prices/availabilities change and i access this info from multiple points in the program. I'm trying to interface with this list using a dropdown by doing "SELECT * FROM contacts" as a query. my code looks like this :
$contact_list = mysqli_query($link, "SELECT brand FROM contacts ORDER BY brand");
Then I echo that list out in a while loop using PHP to populate the options in the dropdown.
My question is this: I have these dropdowns for each eye on the same form. So it's "Brand Right Eye"....other miscellaneous info about the right eye....then "Brand Left Eye". But ONLY the right eye is populating with the brand info because it appears first in the code. What i'm having to do is copy/paste the exact same query and do
$contact_list2 = mysqli_query($link, "SELECT brand FROM contacts ORDER BY brand");
then later if I need the dropdown again, I need to do $contact_list3..and so on. Why can i not generate a drop down using the same variable? Why does it stop responding to calling the variable after the first execution of it and is there any work around that I can implement that would allow me to not have to copy/paste the same query with a different variable association each time?
just for refernce, my php while code is this:
<select class="form-control" name = "brandOS">
<option value="0">Please Select</option>
<?php
while($row = mysqli_fetch_array($contact_list))
{
?>
<option value = "<?php echo($row['brand'])?>" name = "brandOS">
<?php echo($row['brand']) ?>
</option>
<?php
}
?>
</select>
I have this loop copy/pasted for right eye and left eye. But it only works on which ever drop down appears first in the code.
A possible solution will be more efficient in term of performance could be :
<?php
$left_eye = '<option value="0">Please Select</option>';
$rigth_eye = '<option value="0">Please Select</option>';
while($row = mysqli_fetch_array($contact_list))
{
//logic for left eye
$left_eye .= <<<HTML
<option value ="{$row['brand']}" name = "brandOS">
{$row['brand']}
</option>
HTML;
//logic for rigth eye
$rigth_eye .= <<<HTML
<option value ="{$row['brand']}" name = "brandOS">
{$row['brand']}
</option>
HTML;
}
?>
<select class="form-control" name = "brandOS">
<?php echo $left_eye ; ?>
</select>
<select class="form-control" name = "brandOS">
<?php echo $rigth_eye ; ?>
</select>
With this solution you get your result in the same while loop. If the left and right select are the same you can use the same variable.
Store the brands in an array, then you can just loop through the array.
<?php
$contact_list = mysqli_query($link, "SELECT brand FROM contacts ORDER BY brand");
$brands = array();
while($row = mysqli_fetch_array($contact_list))
{
array_push($brands, $row['brand']);
}
?>
<select class="form-control" name = "brandOS">
<option value="0">Please Select</option>
<?php
foreach($brands as $brand){
?>
<option value = "<?php echo($brand[0])?>" name = "brandOS">
<?php echo($brand[0]) ?>
</option>
<?php
}
?>
</select>
You can use a PHP array, like the SESSION one, to store values and use them across your site. Be sure you call "session_start()" method on each page you use that array, though.
//Initialize sessions
session_start();
...
//Right after getting result from query
$_SESSION['contact_list'] = $contact_list;
To use it, just be sure to call the method I told you above, and call the variable with the same syntax:
<?php
while($row = mysqli_fetch_array($_SESSION['contact_list'])) { ?>
Hope this helps.

UPDATE an imploded multiple selection into database

I have a problem while updating a to database, It happens to add the new value beside the old value into the database for example
Current Database Tags: tag1,tag2
Form GET Tags: [tag1][tag2]
Form Edited Tags: [tag1][tag2][tag3][tag4]
Updated Database Tags: tag1,tag2,tag1,tag2,tag3,tag4
GET
$query = "SELECT * FROM data WHERE id = $id";
$edit = mysqli_query($dbc, $query);
while($row = mysqli_fetch_assoc($edit)){$tags = $row['tags'];}
POST
$tags = implode(",",$_POST['tags'];
$query = "UPDATE data SET tags= '$tags' WHERE id = $id";
<form method="post" action="">
<select id="tags" name="tags[]" multiple="multiple">
<?php foreach ($tags as $tag) {echo "<option value'$tag' selected>$tag</option>";} ?>
<option>tag1</option>
<option>tag2</option>
<option>tag3</option>
<option>tag4</option>
</select>
<button type="submit" name="update">Submit</button>
</form>
There are few issues with your code, such as:
$tags is not an array. See the below statement in your while() loop,
$tags = $row['tags'];
So you can't use it in foreach loop like that. Use explode() function to split the string and get the tags in an array, like this:
$tags = explode(",",$row['tags']);
And then use this $tags array in your form, which is explained below.
Syntax error here,
$tags = implode(",",$_POST['tags'];
^ missing closing )
Even you get the tags as an array(as pointed above), you don't have to use that foreach loop either, it will unnecessarily append additional/redundant tags in your <select> element. better use in_array() function to check the tag value is present in $tags array or not and make it selected accordingly
value attribute is missing from <option> tags.
Place the SELECT operation below the UPDATE operation, otherwise you'll get old tag values from the SELECT operation even if you update the tags using the form.
So your code should be like this:
if(isset($_POST['update'])){
$tags = implode(",",$_POST['tags']);
$query = "UPDATE data SET tags= '$tags' WHERE id = $id";
mysqli_query($dbc, $query);
}
$query = "SELECT * FROM data WHERE id = $id";
$edit = mysqli_query($dbc, $query);
while($row = mysqli_fetch_assoc($edit)){
$tags = explode(",",$row['tags']);
}
<form method="post" action="index.php">
<select id="tags" name="tags[]" multiple="multiple">
<option value="tag1"<?php if(in_array('tag1', $tags)){ echo ' selected="selected"'; } ?>>tag1</option>
<option value="tag2"<?php if(in_array('tag2', $tags)){ echo ' selected="selected"'; } ?>>tag2</option>
<option value="tag3"<?php if(in_array('tag3', $tags)){ echo ' selected="selected"'; } ?>>tag3</option>
<option value="tag4"<?php if(in_array('tag4', $tags)){ echo ' selected="selected"'; } ?>>tag4</option>
</select>
<button type="submit" name="update">Submit</button>
</form>

Drop down box used to delete records sqlite

I am currently struggling with creating a drop down box that when populated will delete whichever record is currently highlighted.
I have been able to create a form that allows me to add new records to the database, but since then have really struggled to get the correct records to show on the drop down box as I only have a vague understanding of PHP.
<?php
$db=sqlite_open("/wwwroot/Work/bookDB.db");
if (isset($_POST['submit']))
{
$Author = $_POST['Author'];
$Title = $_POST['Title'];
$Synopsis = $_POST['Synopsis'];
$ISBN = $_POST['ISBN'];
$Publisher = $_POST['Publisher'];
sqlite_query ($db, "INSERT INTO Books (Author, Title, Synopsis, ISBN, Publisher)
VALUES ('$Author', '$Title', '$Synopsis', '$ISBN', '$Publisher')");
header("Location: /Work/Book/Book.php");
}
else
{
}
?>
this is my submit query that may give some understanding of how the database is set up, I am looking to have a drop down box that will be populated by a list of the authors. So far I have tried using $row to no avail, and I don't seem to be able to use $column either, like I have stated earlier my PHP skills are awful so any help would really be appreciated.
html:
<form name = "delete form" action="Delete.php" method="POST">
<div class = "book">
<select name = "Title">
<option value = ""> Select </option>
</div>
php:
<form action = "<?php echo $_SERVER['PHP_SELF'];?>" method="get">
<select name = 'rowno' onchange = "javascript:document.forms[0].submit();">
<option> Select a Book </option>
<?php
$db = sqlite_open("/wwwroot/work/bookDB.db");
$query = sqlite_query($db,"SELECT ID, Title from Books");
$result = sqlite_fetch_all($query, SQLITE_BOTH);
$rowno = 0;
foreach($result as $entry)
{
echo "<option value = $rowno >$entry[ID] $entry[Title]</option>";
$rowno++;
}
?>
</select>
</form>
</div>

white spaces in $_POST

I have a HTML dropdown list populated by PHP as following:
<form name="selectOccupation" method="post" action="specific_occupation.php">
<div align="centre">
<select name="occupation_dropdown" id="occupation_dropdown">
<?php
include "connection.php";
$sql = mysql_query("SELECT DISTINCT Occupation from patient_info");
while ($row = mysql_fetch_array($sql)) {
echo "<option value=".$row['Occupation'].">".$row['Occupation']."</option>";
}
?>
</select>
</div>
<br>
<br>
<input type="submit" name="submit" value="Proceed"/>
</form>
In the specific_occupation.php file, I have this code:
<?php
include "connection.php";
$selectedoccupation = $_POST['occupation_dropdown'];
echo $selectedoccupation;
$myquery = "SELECT patient_info.Name, test_info.DateOfTest FROM `patient_info`,`test_info` WHERE patient_info.PatientID = test_info.PatientID AND patient_info.Occupation = '$selectedoccupation' ";
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
$tempdata = json_encode($data);
?>
This works fine if an occupation without any white space between them like "carpenter" is selected from the dropdown menu but doesn't work for "sales person". How can the $_POST be used for occupations with white spaces??
Thanks in advance !!
You're building your HTML wrong. You've got it as:
<option value=Sales Person>
^^^^^---what will get sent as the value
^^^^^^---some wonky unknown/non-standard attribute
This is incorrect. HTML now requires that ALL attributes be quoted:
<option value="Sales Person">
and even when the quotes weren't required, you still had to have the quotes to handle "spaced" data like this.
PHP post replace some characters such as - with whitespaces.
You can try urlencode($var) in your PHP script.

Select multiple (PHP and MySQL)

I have a form with a select multiple like this:
<select name="states[]" size="5" multiple>
<option value="2">state 1</option>
<option value="3">state 2</option>
<option value="4">state 3</option>
<option value="5">state 4</option>
<option value="6">state 5</option>
</select>
I want to have the possibility to choose more than one state, and then make the query to my database and show the description of each state chosen.
So this is what I have to make the query using PHP and MySQL:
$state = $_POST['states'];
$data = mysql_query("SELECT * from states WHERE id_state = '$state'",$db);
while($row = mysql_fetch_array($data)){
$result=$row['description'];
}
echo $result;
I have that code and it doesn't show anything.
How can I fix this problem?
Try this
$state = $_POST['states']; // return Array
$count_states = count( $state );
if( $count_states > 0) {
$states = implode( ',', $state);
$data = mysql_query("SELECT * from states WHERE id_state IN ($states)",$db);
while($row = mysql_fetch_array($data)){
echo $row['description'];
}
}
This would require a simple foreach to go through the array and get results based on each value as such,
foreach($_POST['states'] as $state) {
$data = mysql_query("SELECT * from states WHERE id_state = '$state'",$db);
$row = mysql_fetch_array($data);
echo $row['description'];
}
Also since you're not protecting your query in some sort and are using mySQL which has been deprecated as of PHP 5.5.0, I suggest you looking into PDO or mySQLi Prepared statements
$_POST['states'] holds an Array with all the ID's of the selected states.
Off course you can query your database for every posted state_id, but way nicer (and faster) would it be to make a query which looks like this and uses only one query:
SELECT description FROM states WHERE id_state=1 OR id_state=2 etc etc
This also might be a good point to start using a database abstraction layer like PDO.
As the number of posted states is variable, we need to make the statement also variable:
// The [connection setup][2] by PDO is done in $conn, with some proper exception handlers
// e.g. $conn = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
// Fill an array with count() number of elements with value 'id_state=?'
$place_holders = array_fill(0, count($_POST['state']), 'id_state= ?');
//implode the array
$place_holders = implode(' OR ', $place_holders);
// prepare the query
$st = $conn->prepare("SELECT description FROM state WHERE $place_holders");
// execute to above prepared query with the $_POSTED states
$st->execute($_POST['state']);
// traverse the result
foreach($st->fetchAll() AS $r){
// do some magic
}
You could build the string by iterating through the array:
$state = "";
foreach($_POST['states'] AS $s)
{
// Sanitize $s here
$state .= "`id_state` = " . $s . " OR";
}
if($state)
{
$state = substr($state, 0, -3);
$data = mysql_query("SELECT * from states WHERE $state",$db);
while($row = mysql_fetch_array($data)){
echo $row['description'];
}
}
Of course, you should use something like MySQLi or PDO to handle database interaction. They will have ways to sanitize input easily so you can avoid obvious SQL injection.
Tamil has a pretty good IN select method as well. This is just one option.
Example (pages for edit):
//On select_multiple.php (Form):
<?php
//Conn
include('incl_config.php');
//Multiple data to bring
$sql = " select COD_DXS,VALOR_DXS from hc_dxsindromico where ESTADO_DXS='1' ";
$result=#mysql_query($sql);
?>
//In the form select:
<select multiple="multiple" size="7" name="dxsindromico[]"> //look yes or yes brackets []
<option value="" selected="selected">Choose one or more options</option>
<?php
while($row=mysql_fetch_array($result)){
?>
<option value="<?php echo $row['COD_DXS']; ?>" style="color:#F00;"><?php echo $row['VALOR_DXS'];?></option>
<?php } ?>
</select>
//////////// On grabar_mtr.php ///////////////
<?php
include('incl_config.php');
/*Multiple selection form in HTML5, PHP and Bootstraps
Created by: www.nycsoluciones.com
Version: 1.1*/
//we use a foreach to traverse the array (values of our select and save them in the table dxsindromico_data)
if(isset($_POST['dxsindromico'])){
foreach( $_POST['dxsindromico'] as $insertar ) {
//echo $insertar;
$sqli="insert into dxsindromico_data(DXSINDROMICO_HC) values('$insertar')";
//echo $sqli;
//exit;
$resulti=mysql_query($sqli);
}
} else{
foreach( $_POST['dxsindromico'] as $insertar ) {
//echo $insertar;
$sqli="insert into dxsindromico_data(DXSINDROMICO_HC) values('$insertar')";
$resulti=mysql_query($sqli);
}
}
?>

Categories