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>
Related
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>
I have dropdown menu with 3 values.
and here is my table (table name is Sms)
What I want to do? Example : If I choose 2,49 and press submit, then I get sonum value.
This is my form
<div class="col_12" style="margin-top:100px;">
<div class="col_6">
<label for="asukoht">Vali Hind</label>
<form class="vertical" method="GET">
<select name="hind">
<option value="1">-- Vali --</option>
<?php
// Tegin dropdown menüü, kust saab valida komponendi, mille alla see pilt läheb
$andmed = mysql_query("SELECT * FROM Sms");
// Dropdown menüü
while($rida = mysql_fetch_array($andmed)){
echo '<option value="'.$rida['id'] . '">'.utf8_encode($rida['hind'] ). '</option>';
}
?>
<input type="submit" name="add" id="add">
</form>
I tried something like this
if(mysql_query("DESCRIBE `Sms`")) {
$sql = "SELECT sonum FROM `Sms`";
echo $sql;
}
I think it should be pretty easy, but I'm looking for a solution and I didnt found it.
Thank you for helping !
You need to work on SQL and Loop.
Based on your code:
if(mysql_query("DESCRIBE `Sms`")) {
$sql = "SELECT sonum FROM `Sms`";
echo $sql;
}
First we do change the query including $_GET parameter.
So this:
$sql = "SELECT sonum FROM `Sms`";
Will become:
$sql = "SELECT sonum FROM `Sms` WHERE id = ".$_GET['hind'];
It will be better if you check that the var exist and is setted with something like:
if(isset($_GET['hind']) && is_numeric(trim($_GET['hind']){//Code here}
But it is off-topic.
Now let's change echo $sql; with a loop, we need to loop and fetch the data.
while($result = mysql_fetch_array($sql)){
echo '<option value="'.$result ['id'] . '">'.utf8_encode($result ['hind'] ). '</option>';
}
I've only changed what i know, you know your system ^_^
You should do:
$sql = "SELECT sonum FROM Sms WHERE id = ".$_GET['hind'];
Then do :
echo mysql_query($sql);
$sql = "SELECT sonum FROM Sms WHERE id = ".$_GET['hind'];
while($rida = mysql_fetch_array($sql)){
echo '<option value="'.$rida['id'] . '">'.utf8_encode($rida['hind'] ). '</option>';
}
Do not use MYSQL queries...try MySQLi or PDO with prepared statement.
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);
}
}
?>
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.
hello im using this code to do search
<form action="arama.php" method="get">
<input type="text" name="lol">
<select name='kategori'>
<option value="tum">Tum kategoriler</option>
<?
while ($kat = mysql_fetch_array($kategori_isim)) {
echo "
<option value=".$kat[kategori_isim].">".$kat[kategori_isim]."</option>";
}
?>
</select>
<input type="submit" value="ara">
</form>
<?
$lol = mysql_real_escape_string($_GET['lol']);
$kategori = mysql_real_escape_string($_GET['kategori']);
if ($kategori == "tum") {
$ara = mysql_query("select * from dosyalar where baslik like '%$lol%'");
}
else {
$ara = mysql_query("select * from dosyalar where baslik like '%$lol%' order by kategori = '%$kategori%'");
}
?>
search by term works but not listing by kategori.. what can i do?
I'm not sure I understand the question (I can't really figure out what those fields mean), but I think that your second query should be more like:
$ara = mysql_query("SELECT * FROM dosyalar WHERE kategori LIKE '%$kategori%'");
ORDER BY only specifies how to sort the results, you can only use a column name, not a check as in your code.
Extending my answer: the ORDER BY kategori = '%$kategori%' isn't a syntax error but I don't think it does anything useful. The check kategori = '%$kategori%' will always be false (unless you have a value with percent signs both at start and at end) so the ORDER BY clause will be useless and you will just do the same select you're doing in the other branch of the if block.
Specifying ORDER BY kategori = '$kategori' will return 0 for all the records where kategori is not equal to $kategori, 1 for the ones where it matches. This will basically sort all the matching rows at the end of your query.
Maybe the query failed. In that case mysql_query() returns FALSE and mysql_error() returns a description of the error.
Try
<form action="arama.php" method="get">
<input type="text" name="lol" />
<select name='kategori'>
<option value="tum">Tum kategoriler</option>
<?php
while ( false!==($kat=mysql_fetch_array($kategori_isim)) ) {
$htmlIsim = htmlspecialchars($kat['kategori_isim']);
echo ' <option value="', $htmlIsim, '">', $htmlIsim, "</option>\n";
}
?>
</select>
<input type="submit" value="ara" />
</form>
<?php
$lol = isset($_GET['lol']) ? mysql_real_escape_string($_GET['lol']) : '';
$kategori = isset($_GET['kategori']) ? mysql_real_escape_string($_GET['kategori']) : '';
$query = "select * from dosyalar where baslik like '%$lol%'";
if ( 'tum'!==$kategori ) {
$query .= "order by kategori = '%$kategori%'";
}
$ara = mysql_query($query) or die( htmlspecialchars(mysql_error().': '.$query) );
echo '<pre>Debug: ', mysql_num_rows($ara) , ' records in the result set for ', htmlspecialchars($query), "</pre>\n";
?>