use a foreach to output data from a database - php

I've a very simple database, a list of 8 languages and the values they can have is Y or N.
What I need is to output a checkbox for each languages and, if the value is Y, the checkbox must be checked, otherwise it must be empty.
This is the code I'm using for each single language, but I would like to know if there's a better way to obtain the same result.
if ($language=='N'){
echo "<input type='checkbox' name='" . $rowlang["english"] . "' value='" . $rowlang["english"] . "'> English<br>";
} else {
echo "<input type='checkbox' name='" . $rowlang["english"] . "' value='" . $rowlang["english"] . " checked'> English<br>";}
//What I've tried to do is to build an array of the languages and use a foreach
$languages = array($rowlang["czech"],$rowlang["english"],$rowlang["german"],$rowlang["slovak"],$rowlang["russian"],$rowlang["french"],$rowlang["spanish"],$rowlang["italian"]);
foreach($languages as $language)
if ($language=='N'){
echo "<input type='checkbox' name='" . $language . "' value='" . $language . "'> " . $rowlang . "<br>";
}else{
echo "<input type='checkbox' name='" . $language . "' value='" . $language . "' checked> " . $rowlang . "<br>";
}
which is almost working, the problem is that I can't echo the single language, because with this code I'm getting "array".

The problem is that trying to use $rowlang as part of the echo is a problem as it is an array.
Instead you can create an array of the languages you want to output, this also gives the name to be displayed as the value. So use a foreach() over this array and check in the $rowlang array to see if it is set. Rather than repeat the whole HTML, this just sets the checked attribute.
// Need to expand this array for all the countries you need
$languages = array("german" => "Germany","english" => "English");
foreach($languages as $language => $label) {
if ($rowlang[$language]=='N'){
$checked = '';
}else{
$checked = ' checked';
}
echo "<input type='checkbox' name='" . $language . "' value='" . $language . "'$checked>" . $label . "<br>";
}
This will output something like
<input type='checkbox' name='german' value='german'>Germany<br>
<input type='checkbox' name='english' value='english' checked>English<br>

First create an associative array and store the languages and their values in it:
$languages = array('czech' => 'N','english' => 'Y','german' => 'N','slovak' => 'N','russian' => 'N','french' => 'N','spanish' => 'Y','italian' => 'N' );
then:
foreach($languages as $key => $value) {
if ($value=='N'){
echo "<input type='checkbox' name='" . $key . "' value='" . $value . "'> " . $key . "<br>";
}
else{
echo "<input type='checkbox' name='" . $key . "' value='" . $value . "' checked> " . $key . "<br>";
}
}
the result will be:

if it is array you should use $language->language_name or $langage['language_name'] as of your array type

Related

PHP Dropdown list maintain on reload

I am new to PHP and have just started the professional development in this language. I have created a dynamic dropdown list in php as under:
$sql="select DISTINCT State from branchinfo";
$result = $conn->query($sql);
if($result->num_rows > 0)
{
echo "< SELECT NAME='states'>";
while($row=$result->fetch_assoc())
{
echo "< OPTION NAME = '" . $row['State'] . "'" . " VALUE = '" . $row['State'] . "'>" . $row["State"];
}<br>
echo "< /SELECT>";
}
echo "< INPUT TYPE='submit' name='submit' value='submit'>";
Problem is when I select a state and click on submit, the list reloads and my selection is lost, the first option gets selected by default. I have tried to embed the script within OPTION but it didn't worked, I tried it as under:
echo "< OPTION NAME='" . $row['State'] . "'" . " VALUE='" . $row['State'] . "'" . if(isset($_POST["submit"])){ if($_POST["states"] == $row['State']) echo "selected";} . " >" . $row["State"];<br>
I am not using any javasrcipt / jquery till now on this page and not planning to use it either. plz provide a solution within this code. Please help.
Some additional information
The mthod i tried as mentioned above, works fine on hardcoded static drop downlist items written in html form. It stops working for dynamically generated list.
You have to add dropdown inside form tag, then it will work.
$sql = "select DISTINCT State from branchinfo";
$result = $conn->query($sql);
echo "<form method='POST'>";
if ($result->num_rows > 0) {
echo "<SELECT NAME='states'>";
while ($row = $result->fetch_assoc()) {
$sel = ( $_POST['states'] == $row['State'] ) ? "selected" : "";
echo "< OPTION NAME = '" . $row['State'] . "'" . " VALUE = '" . $row['State'] . "' " . $sel . ">" . $row["State"] . "</OPTION>";
}
echo "</SELECT>";
}
echo "<INPUT TYPE='submit' name='submit' value='submit'>";
echo "</form>";
Use session to remember your choice. And when the page is reloaded just retrieve your previous selected value.
like
while($row=$result->fetch_assoc())
{
if($sessionvalue==$row['State']){
echo "< OPTION SELECTED NAME = '" . $row['State'] . "'" . " VALUE = '" . $row['State'] . "'>" . $row["State"];
}else{
echo "< OPTION NAME = '" . $row['State'] . "'" . " VALUE = '" . $row['State'] . "'>" . $row["State"];
}
}

Including a html form in a php script

I am trying to create a PHP script which has a HTML form included within it. Please help me edit this:
$SoapClient = new SoapClient ( NULL, $options );
try {
$cities = $SoapClient->getCities ();
// echo var_dump($SoapClient->getCities ());
echo "<form action= " . "'$" . "PHP_SELF' method = 'post'>";
echo "<h4>Choose Origin</h4>";
foreach ( $cities as $city ) {
echo "<input type='radio' name = 'origin' value = " . $city . "> <br>";
}
echo "<h4>Choose Destination</h4>";
foreach ( $cities as $city ) {
echo "<input type='radio' name = 'destination' value = " . $city . "> <br>";
}
echo "<p>";
echo "<input type='submit' name='submitButton' value='Calculate Great Circle'>";
// show soap request and response
} catch ( Exception $e ) {
echo "<h3>SOAP error</h3><pre>" . $e . "</pre>";
echo "<h3>SOAP error last response</h3><pre>" . $SoapClient->__getLastResponse () . "</pre>";
echo "<h3>SOAP error last request</h3><pre>" . $SoapClient->__getLastRequest () . "</pre>";
}
Thanks a lot :)
You want to display the cities names next to your radios, try this in your two loops :
foreach ( $cities as $city ) {
echo "<label><input type='radio' name='origin' value='" . $city . "'>" . $city . "</label> <br>";
}
And also replace
echo "<form action= " . "'$" . "PHP_SELF' method = 'post'>";
by
echo '<form action="' . $_SERVER['PHP_SELF'] . '" method="post">';

PHP - POST form will not pass numeric value for checkbox, but accepts all other values

$squery = $cbdbc->prepare("SELECT * from sitedata");
$squery->execute();
while ($srow = $squery->fetch(PDO::FETCH_ASSOC)) {
if ($rresult[$srow['siteName']] !== $srow['siteID']) {
echo "<tr><td><input type='checkbox' id='" . $srow['siteID'] . "' name='" . $srow['siteID'] . "' value='" . $srow['siteID'] . "'><label for='".$srow['siteID']."'>" . str_replace('_',' ',$srow['siteName']) . "</label></td></tr>";
} else {
echo "<tr><td><input type='checkbox' id='" . $srow['siteID'] . "' name='" . $srow['siteID'] . "' value='" . $srow['siteID'] . "' checked='checked'><label for='".$srow['siteID']."'>" . str_replace('_',' ',$srow['siteName']) . "</label></td></tr>";
}
}
echo "<tr><td><input type='submit' value='Submit'></td></tr></table></form>";} elseif (null !== filter_input(INPUT_GET, 'setromstores')) {
$rid = filter_input(INPUT_GET, 'setromstores');
$squery = $cbdbc->prepare("SELECT * FROM sitedata");
$squery->execute();
while ($srow = $squery->fetch(PDO::FETCH_ASSOC)) {
$sid = filter_input(INPUT_POST, (string)$srow['siteID']);
if ($sid !== null) {
$uquery = $cbdbc->prepare("UPDATE roms SET " . $srow['siteName'] . "=:sid WHERE romID = :rid");
$uquery->bindParam(':sid', $sid);
$uquery->bindParam(':rid', $rid);
$uquery->execute();
} else {
$uquery = $cbdbc->prepare("UPDATE roms SET " . $srow['siteName'] . "= '0' WHERE romID = :rid");
$uquery->bindParam(':rid', $rid);
$uquery->execute();
}
}
So I'm trying to do a system where a user known as a ROM can be assigned 'sites' using checkboxes.
For every type of value except pure numbers for 'siteID' (which is VARCHAR(5) on the MySQL table), e.g. abc, abc12, 0001, the value of siteID passes correctly and the value is updated correctly in the table 'roms'.
If I have a pure number as a value for siteID, e.g. 1, 15, 2339, it will pass no value through POST and will always result in 0 being set in the 'roms' table.
I have tried making sure that at every step the value being passed is converted into a string, but this doesn't seem to help.
While typically site IDs are in the format AXXXX, I would prefer to see if this is fixable then force users to put in siteIDs of AXXXX, especially as this may change in the future to pure numbers.
Value is not the same as name or id. You can't send forms with only-number names, nor ids. Change your line to something like this:
<input type='checkbox' id='yourUniqueId" . $srow['siteID'] . "' name='checkboxes[" . $srow['siteID'] . "]' value='" . $srow['siteID'] . "' checked='checked'>
Well, as you can see, your checkboxes are named now checkboxes and it's an array of data!! You can receive in PHP
$_POST['checkboxes']; // array(value1, value2, value3)
And you fix your problem.
Form field name must be a string. You can use this method:
echo "<tr><td><input type='hidden' name='siteID[" . $srow['siteID'] . "]' value='0'><input type='checkbox' id='" . $srow['siteID'] . "' name='siteID[" . $srow['siteID'] . "]' value='" . $srow['siteID'] . "'><label for='".$srow['siteID']."'>" . str_replace('_',' ',$srow['siteName']) . "</label></td></tr>";
I change checkbox name like this name="siteId[12]", and add hidden field (it`s not necessary).
After that siteID is an associated array of checked sites, where key is siteId, and value 1, if checked, and 0 if not.
$sids = filter_input(INPUT_POST, 'siteID', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
while ($srow = $squery->fetch(PDO::FETCH_ASSOC)) {
$sid = $sids[$srow['siteID']];
// ...
}

id of the input

I'm sending muliple inputs with form, How can I get the id of the actuall input, so i can update mysql content?
my code:
if (isset($_POST['save']))
{
foreach ($_POST as $key => $value)
{
${$key} = $value;
mysql_query("UPDATE table SET img='$image_[id]', title='$title_[id]' where id='$id'");
}
}
while ($row = mysql_fetch_array($result))
{
echo "<b>Title: </b><input type='text' name='title_" . $row['id'] . "' value='" . $row['title'] . "'><br />";
echo "<b>Image: </b><input type='text' name='image_" . $row['id'] . "' value='";
}
echo '<input type="submit" name="save" value="save"><br /><hr>';
echo '</form>';
Yours naming is wrong. Use this way.
echo "... name='title[" . $row['id'] . "]'...";
And after it your $_POST['title'] will contain array of titles.
And read manual How do I create arrays in a HTML ?
But if you are still what to go that way. You can use something like this.
foreach ($_POST as $key => $value)
{
if (preg_match('^image_(\d*)$', $key, $matches))
{
$id = $matches[1];
if (isset($_POST['title_' . $id]))
{
mysql_query("UPDATE table SET title='" . $_POST['title_' . $id] . "' where id='$id'");
}
}
}
But sign here that you understand all vulnerabilities of this code.

PHP data entry (SQL)

I have a form that posts to a PHP page. This is a snippet of the page. The goal is to read out a SQL table and then you click on the text values and they are editable. You then edit them and submit and it updates the SQL table. I basically need a way to strip the letter from the beginning of the id. but the letter is important because it defines in what column the new information goes into. Also if there is a different language or method to do this, I am open to suggestions.
<script type="text/javascript">
function exchange(id){
var ie=document.all&&!window.opera? document.all : 0
var frmObj=ie? ie[id] : document.getElementById(id)
var toObj=ie? ie[id+'b'] : document.getElementById(id+'b')
toObj.style.width=frmObj.offsetWidth+7+'px'
frmObj.style.display='none';
toObj.style.display='inline';
toObj.value=frmObj.innerHTML
}
</script>
<?php
$result = mysqli_query($con,"SELECT * FROM List") or die(mysql_error());
var_dump($_POST);
echo "<table id=list>
<tr id='list_header'>
<th class='list'>ID</th>
<th class='list'>Description</th>
<th class='list'>Winner</th>
</tr><form name='edit' action='inde.php?id=prizes' method='post'>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td class='list'><span id='n" . $row['Number'] . "' onclick='exchange(this.id)'>" . $row['Number'] . "</span><input name='n" . $row['Number'] . "b' id='n" . $row['Number'] . "b' class='replace' type='text' value='" . $row['Number'] . "' style='display:none;'></td>";
echo "<td class='list'><span id='d" . $row['Number'] . "' onclick='exchange(this.id)'>" . $row['Description'] . "</span><input name='d" . $row['Number'] . "b' id='d" . $row['Number'] . "b' class='replace' type='text' value='" . $row['Description'] . "' style='display:none;'></td>";
echo "<td class='list'><span id='w" . $row['Number'] . "' onclick='exchange(this.id)'>" . $row['Winner'] . "</span><input name='w" . $row['Number'] . "b' id='w" . $row['Number'] . "b' class='replace' type='text' value='" . $row['Winner'] . "' style='display:none;'></td>";
echo "<td></td>";
echo "</tr>";
}
echo "</table><input type='submit' value='Save Changes'></form>";
?>`
From what I understand you have a string id and you want to do the following:
if(strlen($id)>1){
$important=substr($id, 0, 1); //that gets the important stuff
$id = ($id, 1, strlen($id)); //that's id without the first char
}
else{
$important=$id;
$id=""; //empty string
}
You may want to try Ajax to send the modified values to the server one by one instead of all together at the end.

Categories