The code bellow gets a few domains from my database and outputs them in a dropdown list. I need some help as I can't get this change i want to make work.
I want to show only the domains where in the database premium_only is set to 6, nothing else. If I try to change the if statement to $shortUrlDomain['premium_only'] == 6 I can't see any domains appear in the list which has premium_only set to 6 in the database. Why?
Database layout:
id | domain | premium_only | status | date_created
---+-------------+--------------+---------+-------------------
1 | exaple.com | 0 | enabled | 2020-03-02 08:13:0
2 | exaple2.com | 6 | enabled | 2021-03-02 08:13:0
PHP code:
<div>
<label for="shortUrlDomain"><?php echo t("short_url_domain", "Short Url Domain"); ?>:</label>
<select id="shortUrlDomain" name="shortUrlDomain" style="width: 100%;">
<?php
foreach ($shortUrlDomains AS $k => $shortUrlDomain) {
// active domains only
if ($shortUrlDomain['status'] != 'enabled') {
continue;
}
$lastPremiumOnly = $shortUrlDomain['premium_only'];
echo '<option value="' . (int)$k . '"';
// selected option
if ($k == (int)$_REQUEST['shortUrlDomain']) {
echo ' SELECTED';
}
echo '>';
'</option>';
}
echo '</optgroup>';
?>
</select>
</div>
// get base urls
$shortUrlDomains = getShortUrlDomains();
static function getShortUrlDomain($domainId)
{
// get base urls
$shortUrlDomains = getShortUrlDomains();
if(!isset($shortUrlDomains[$domainId]))
{
return _CONFIG_SITE_PROTOCOL.'://'._CONFIG_SITE_FULL_URL;
}
return _CONFIG_SITE_PROTOCOL.'://'.$shortUrlDomains[$domainId]['domain'];
}
It's a bit hacky, but you might add this statement earlier in your code.
Ideally you'd alter the database query further down the stack, but you question doesn't include any mention of how you set $shortUrlDomains.
<?php
// somewhere before you render the HTML as in the snippet from your Q.
/**
* This makes shortUrlDomains into a subset of the original array,
* showing only those who have a `premium_only` key with a value of `6`.
*/
$shortUrlDomains = array_filter($shortUrlDomains, function($domain) {
return (int) $domain['premium_only'] === 6;
});
See more of array_filter here, at the PHP docs.
Related
I'm generating dynamic form inputs based on table column field names with this simple code :
<form id="generate-user-register-form" type="POST">
<?php
$queryuser= "DESCRIBE users";
$resultstmt_queryuser= $conn->query($queryuser);
$fields = array();
while($row = $resultstmt_queryuser->fetch_assoc()) {
$fields[] = $row['Field'];
}
foreach($fields as $field): ?>
<div class="col-md-6">
<?php echo "$field: "; ?>
<input class="form-control" type="text" name="<?php echo $field; ?>" />
</div>
<?php endforeach; ?>
<input type="button" name="submit" value="submit"/>
</form>
Ok this works great but the first 10 fields are unnecessary and the first column id is autoincrement so it is definitely not needed as a form input. Is there a way for me to only generate specific fields without having to manually hard code something like the below code 10 times?
if($field !="id"){
//generate input
}
I think what you are trying to do might have different approaches considering how to decide if a field should be an input or not. For example.
Consider that your table would look like this:
+----+------------+-------------+-------------+------------+
| id | name_input | email_input | phone_input | created_at |
+----+------------+-------------+-------------+------------+
| 1 | John Smith | not#me.com | 888 333 444 | 2018-08-26 |
| 2 | Lila White | not#us.com | 412 322 555 | 2018-08-27 |
+----+------------+-------------+-------------+------------+
So, with this table you could easily find the keyword input in the columns and assign only them to the form:
while($row = $resultstmt_queryuser->fetch_assoc()) {
if (strpos($row['Field'], '_input') === false) {
continue;
}
$fields[] = $row['Field'];
}
Or, as #IdontDownVote pointed out in the comments above, you can use a count inside the loop and only add the fields if after some number or betweem some, or before another, like:
$count = 0;
while($row = $resultstmt_queryuser->fetch_assoc()) {
if ($count < 1 /* adding extra clauses here as && $count > 5 */) {
continue;
}
$fields[] = $row['Field'];
}someone
But I would advise against it. Why? you might ask.
Well, by nature, each field is different. The machine will certainly not know what is the label for a specific field, or what validation it should have, or what kind of information it should hold.
Most commonly, ids are integers, thought they might not be. But what about date fields? Or phone numbers? Or Postal Codes?
Generating dynamic inputs for each of them you might also have to read the name of the column as the label of each field, but still, some information you are bound to hardcoded at some point.
Validations of phone numbers, validations of postal codes, emails, websites.
Most of it will have to be hardcoded anyway in the backend before this information reach the database. So, if you are gonna have to write some specific rules for specific fields, why not specify this fields in the form as well?
It makes your life easier when trying to track down each field and you won't be entirely dependent on creating ignore rules for certain fields to be displayed like: created_at, created_by. When these fields are commonly updated by the system and not by the user (knowing who did what and when, of course).
But well, TL; DR; sometimes hardcoding is clearer and faster (on the long run) than the opposite.
[Edit]
Adding the count to the answer to be visible, if #IdontDownVote post this answer, please choose his answer.
I'm having troubles when making a linked list in HTML, let me explain:
In HTML I have this two selects:
<!-- This select WORKS and read the opened projects from de database -->
<select name="project" id="project">
<option value="0">Select a project</option>
<?php if (isset($result2)): ?>
<?php foreach ($result2 as $res): ?>
<option value=<?php echo $res['c_project_id'] ?>><?php echo $res['d_name'] ?></option>
<?php endforeach ?>
<?php endif ?>
</select>
<!-- This doesn't work, but I want: When I select a project, the project's categories go here -->
<select name="category" id="category">
</select>
The REAL DATA are the next: Table PROJECT
c_project_id | d_name | d_description | n_budget | d_state
1 | Test | Test Project | 100 | Open
2 | Web | Web APP | 3000 | Open
3 | C Test |Closed Project | 100 | Closed
4 | Certif.| Certificates | 2500 | Open
Table Categories (conected with table project)
c_category_id | d_name | d_description | c_project_id
1 | General| General cat | 1
2 | Test | Test cat | 1
3 | General| General cat | 2
4 | General| General cat | 3
5 | Nothing| Nothing cat | 3
6 |Program | Programming | 2
...
I have a SELECT in html that takes the project name and ID, this works in the select nÂș1
$statement2 = $conexion->prepare("SELECT c_project_id, d_name FROM project WHERE d_state= 'Open'");
$statement2->execute();
$resultado2 = $statement2->fetchAll();
Now I want: When I "click" in the first select, the second select make the statement and fulfill the second select. For testing, I just wrote a simple option. I tried with AJAX and PHP but the 2nd option is empty:
AJAX:
$( "#project" ).change(function() {
var select = $( "#project option:selected" ).val();
console.log(select); //just for testing that I took the value.
$.ajax({
type: "POST",
url: "phpPage.php",
data: { selectedProject : select }
}).done(function(data){
console.log("Done");
$("#category").html(data);
});
});
AND PHP:
if(isset($_POST["selectedProject"])){
$proy = $_POST["selectedProject"];
$output = "<option value='100'> Select your category </option>";
if($proy != 0){
$output.= "<option>" . $proy . "</option>";
}
echo $output;
}
But this return me nothing, all is empty.
FINALLY, when I tried to debug, I noticed that in one of the PHP responses, the HTML code () is been written at start of the page (in the response):
<option value='100'> Select your category </option><option>1</option>
<!DOCTYPE html>
<html lang="es">
<head>
<title>
...
Sorry for that huge question, but I'm wasting a lot of time with that and I don't know what could happen.
Thanks you!
Lets look at the breakdown of what you have and want to do. First, you have an empty select element:
<select name="category" id="category">
// empty
</select>
Then, you are tripping off an ajax call which returns data from your PHP. This ajax is simply taking all the returned html from the PHP and putting it in the middle of that above select:
$("#category").html(data);
Your PHP is where you are creating too much information on output. This is usually where its a good idea to isolate your "ajax php scripts" from normal full html build php scripts. So that you are only outputting what you need for that specific ajax call.
In your above PHP, you have:
if(isset($_POST["selectedProject"])){
$proy = $_POST["selectedProject"];
$output = "<option value='100'> Select your category </option>";
if($proy != 0){
$output.= "<option>" . $proy . "</option>";
}
echo $output;
}
// you must have more page generation below this based on your Q (?)
You can either isolate the above code into a new ajax response script (include any needed db actions and pull of data from the database based on the POST arg value, etc).... OR, you can add exit; after your echo $output;... so long as no other extra html was being output BEFORE this if block.
if(isset($_POST["selectedProject"])){
$proy = $_POST["selectedProject"];
$output = "<option value='100'> Select your category </option>";
if($proy != 0){
$output.= "<option>" . $proy . "</option>";
}
echo $output;
exit; // <-- halt so none of the other following html spills out
}
I have a dynamic menu and I want to send the user to a new page on click with some db values. I want to use a session here without forms or via $_GET.
Presently, using the code below, only the last value of the loop is appearing in the $_SESSION. Perhaps I need to use a 2D array here, but I am not sure what to do:
<?php
$i = $cit['city_id'];
$selectCity = $dbh->prepare("SELECT * FROM `table` where city_id=$i");
$selectCity->execute();
$cityNum = $selectCity->fetchAll();
foreach($cityNum as $cities)
{
$_SESSION['$centreNum'] = $cities['centre_id'];
?>
<li class="first"><?php echo ucwords($cities['centre_location']); echo $_SESSION['$centerNum']; ?></li>
<?php
}
$centre_num = $cities['centre_id'];
?>
You have a couple problems (the one I think you mean to do...) in your example:
...
$cityNum = $selectCity->fetchAll();
foreach($cityNum as $cities)
{
# Not sure if you are trying keep this a variable key or not.
# | Make this session an array, you keep overwriting variable
# | |
# | |
# v------+---v v
$_SESSION['$centreNum'][] = $cities['centre_id'];
?>
...continue
i am looking to build a string while inside a mysqli while loop. i have a pages table that contains all the pages for my webapp however it has come to seo friendly these urls
my table looks like this
ID | Page Slug | Parent
------------------------
1 | Accounts | 0
2 | Customers | 1
3 | Details | 2
say i call the below function WebApp_UOC_Construct_Url(3) with the page id 3 it will echo out a url with one that looks like the below
/accounts/customers/details
this url is how i want it to be passed to my menus so i know the function is working however this will only echo on the page i need it to return a value inside the href and so if i change the echo to return and call the function like this
<a hef='" . WebApp_UOC_Construct_Url(3) . "'>Customer Details</a>
i only receive the last entry in the database so the url will look like this
/details
what other possible methods are there of creating the above
function WebApp_UOC_Construct_Url($page_id)
{
global $webapp_db;
$get_URI = mysqli_query($webapp_db,
"SELECT * FROM wa_sys_navigation WHERE wa_nav_id = '" . $page_id . "' ");
while($found_URI = mysqli_fetch_array($get_URI))
{
WebApp_UOC_Construct_Url($found_URI['wa_nav_parent']);
echo "/" . $found_URI['wa_nav_slug'];
}
}
If you change only echo to return you will get only the top level function call result. You need summarize the recursive calls results.
Example:
$parent = WebApp_UOC_Construct_Url($found_URI['wa_nav_parent']);
return $parnet . "/" . $found_URI['wa_nav_slug'];
I am trying to create a button that will either say "Follow" or "Unfollow", depending on whether or not the current user follows another user.
If John followed Tim, but not Sarah, the web view would look as follows, according to John's view:
_________________________________
| | |
| Tim | (unfollow) |
|________________|______________|
| | |
| Sarah | (follow) |
|________________|______________|
Where (" ") denotes a button.
I have a database that indicates who follows whom, but how would I display the correct button based upon validation with said database?
Assuming you have three fields "name_id","name" and "followed" where "name_id" is the id of the person, "name" is a string signifying the name of the person, and "followed" is a boolean:
<script type="text/javascript">
function toggleFollowing(name_id) {
window.location = 'toggleFollowing.php?name_id='+name_id;
}
</script>
...
<?php
...
while ($row = $result->fetch_assoc()) {
echo '<tr>';
echo '<td>'.$row['name'].'</td><td><a href=""><button type="button" onclick="toggleFollowing('.$row['name_id'].')">'.($row['followed']==1 ? 'Unfollow':'Follow').'</button></td>';
echo '</tr>';
}
...
?>
You would have toggleFollowing.php receive the variable $_GET['name_id'] to toggle on the database and come back to this page. I'm assuming you have the current user's ID stored as a session variable or by other means since you would need that as a primary reference to update the record. If you're passing that from page to page by some other means, then you would want to pass that variable as well.
Apparently, this is more truncated code, but a better method would be to use AJAX to perform the toggling on the DB, and DOM manipulation (JQuery?) for a "real-time" update.
Hard to answer without examples of your code, but something like this?
<?php
if(follow){
echo '<input type="button" value="Follow" />';
} else {
echo '<input type="button" value="Unfollow" />';
}
?>