I was trying to get selected value selected from database, but it does not work for some reason. I do not know what do I need to change, I am using function to store articles in database, and I am using the same function to get article that is selected in database. Function artikli:
function article() {
$link = new mysqli("localhost", "xxx", "xxx", "xxx");
$link->set_charset("utf8");
$sql=mysqli_query($link, "SELECT * FROM `artikli` ORDER BY `Id` ASC ");
echo '<option value="">Select article: </option>';
while($record=mysqli_fetch_array($sql)){
echo '<option value= "' .$record['Id']. '">' . $record['ArtCode'] ."-|-". $record['ArtName'] . ' </option>';
}
}
In insert form this function works and insert an article. Now, in edit form, I want to get an article that is inserted. First I retrieve article from another table and I get value.
$article = $r['ArtPalArticle'];
I get for ex. value 18. All values are integers.
$article = 18;
<div class="col-xs-12">
<label>Article</label>
<select class="form-control" name="article" value = "<?php echo $article; selected?>">
<option value=<?php echo $article?> selected></option>
<?php article(); ?>
</select>
</div>
Could anyone give me hint, do I need to change function or I missed the code below function. It would be better for me to keep function same and change code below in select section
You need to compare the id
with inserted id
in the function. You can try this -
function article($articleId = null) {
$link = new mysqli("localhost", "xxx", "xxx", "xxx");
$link->set_charset("utf8");
$sql=mysqli_query($link, "SELECT * FROM `artikli` ORDER BY `Id` ASC ");
echo '<option value="">Select article: </option>';
while($record=mysqli_fetch_array($sql)){
echo '<option value= "' .$record['Id']. '" ' . ((!empty($articleId) && $articleId == $record['Id']) ? 'selected' : '' ) . '>' . $record['ArtCode'] ."-|-". $record['ArtName'] . ' </option>';
}
}
And HTML
<div class="col-xs-12">
<label>Article</label>
<select class="form-control" name="article">
<?php
if(!empty($article)) { // at the time of edit
article($article);
} else {
article();
}
?>
</select>
</div>
<?php
function article( $article_id='' )
{
$link = new mysqli("localhost", "xxx", "xxx", "xxx");
$link->set_charset("utf8");
$sql=mysqli_query($link, "SELECT * FROM `artikli` ORDER BY `Id` ASC ");
echo '<option value="">Select article: </option>';
while($record=mysqli_fetch_array($sql))
{
if( !empty($article_id) )
{
if( $record['Id'] == $article_id )
echo '<option value= "' .$record['Id']. '" selected>' . $record['ArtCode'] ."-|-". $record['ArtName'] . ' </option>';
else
echo '<option value= "' .$record['Id']. '">' . $record['ArtCode'] ."-|-". $record['ArtName'] . ' </option>';
}
else
{
echo '<option value= "' .$record['Id']. '">' . $record['ArtCode'] ."-|-". $record['ArtName'] . ' </option>';
}
}
}
?>
<div class="col-xs-12">
<label>Article</label>
<select class="form-control" name="article" id="article">
<?php article( $article ); ?>
</select>
</div>