Declare order to show foreach output with PHP - php

I am currently trying to set up a custom sortable list. Without getting into too much detail as this would become a very large post, I would like to use the PHP foreach function to show the list.
I currently have
$video_id = $row['videos'];
$res = preg_replace("/[^0-9,.]/", "",$video_id);
$exclude = explode(',', $res);
} ?>
....
<ul id="sortable2" class="connectedSortable">
<?php foreach ($video_list as $key => $item): ?>
<?php if(in_array($item['id'], $exclude)){ ?>
<li id="video-<?php echo $item['id'] ?>"><?php echo $item['id'],
$item['title'] ?></li>
<?php } ?>
<?php endforeach; ?>
</ul>
This generates a list of items from the database excluding items with an ID from an array which is also fetched from another table.
In this example, it will only show videos with the id 3,4 and 2. This is all working as expected. My issue is once I have reordered the items and refreshed the page they are loaded in numerical order. I need these to be load in the order specified (3,4 and 2 for this example).
Any help would be highly appreciated.
Thanks

I think what you are looking for is ORDER BY FIELD (MySql), this lets you order by a field in a specific way.
I need these to be load in the order specified (3,4 and 2 for this example).
Sounds like a good fit to me!
For example
SELECT * FROM table WHERE id IN(3,4,2) ORDER BY FIELD(id, 3,4,2)
This will select rows from table where the id is in the list and then order the results by id in the order they are place there, 3 then 4 then 2.
excluding items with an ID
This might cause some issue, the Field order by assumes you know at least some of the values in the field. Excluding implies that you know what you don't want but not necessarily what you do want, if that makes sense.
Maybe it's not an issue, I don't have enough information on your particular use case to determine that, so I am just mentioning it as a cautionary thing.
Thanks!

Related

Better method to prevent users from changing data attributes in developer tools?

I am trying to find an efficient way of preventing the users from changing data attributes in a form. I need it as I use those values when making queries, and It wouldn't be great if a user changed a data-id atrribute, and the query would delete a completely different record.
I have a table called 'groups' and am listing groups from it to HTML. A data attribute holds the group id, and users can delete groups through the UI. What I have done so far is the following:
I do not display the actual group id in the html, instead I generate a random string (substring of a hash value) and that is what I insert in the data attribute as the value. Then, I create a session variable, that hold an array in which I store all the group IDs and the displayed random strings: the random string is the key, and the actual ID is the value. Later, when the AJAX call is sent, I check if the data attribute value is exists amongst the array keys, and if not, I reject the request as the random string was modified. Otherwise the key exists, and I get the value associated with it.
Here's code so far:
<?php
$groups = $user->getGroupsByAuthor();
foreach($groups as $group):
$group_id = generateGroupId();
$_SESSION['listed-group-ids'][$group_id] = $group['id'];
?>
<li>
<div class="group-image" style="background-image: url('uploads/<?php echo $group['image'] ?>')"></div>
<h4><?php echo $group['name'] ?></h4>
<small><?php echo $group['description'] ?></small>
<span class="btn-delete-group" data-group-id="<?php echo $group_id ?>"><i class="ion-close"></i></span>
</li>
<?php endforeach; ?>
And in the parser file, I check if the key exists:
if( empty($_SESSION['listed-group-ids'][$_POST['group-id']]) ){
exit('Do not try to modify values!');
}
delete the record from database...
Can it be a good way or it is unefficient? Any other experiences or methods you do?
Thanks in advance.

Search function in PHP works with numeric values but doesn't work with letters/words

People can order links at my platform and these get stored in two different tables, eg wp_project and wp_articles. The reason for this is that when people place an order for 1 link one project row gets created and one article row gets created.
However if a client orders 10 links there will be one project entry and ten article entries. Now this isn't very relevant to my problem but just to explain how the system works.
There are two common identifiers for projects and articles, both the ID and the project title are stored in both inpu_project and inpu_articles.
Now if I want to echo all the links from one project I built a search function where I can select the project ID, click search and whether a client ordered 1 link or 20 links that amount of links will show.
The problem starts when I want to search based on the project title instead of ID, which is non-numeric but just words (with spaces in between sometimes).
This to prevent the error undefined index in my error logs
$where_clouse='';
This is the search function based on the project title:
if(isset($_GET['todo']) && $_GET['todo']=='search')
{
if($_GET['proid']!=0){
$where_clouse.=' AND P.`project_title`='.$_GET['proid'];
}
}
This is the database query to pull the links from it:
$sql="SELECT P.`project_title`, P.`backlink` FROM `inpu_articles` AS P
WHERE P.`post_it_posted` = '1' ".$where_clouse." ORDER BY P.`project_title` ASC";
$backlinks=$wpdb->get_results($sql, ARRAY_A);
This is the actual search function that triggers the first code I pasted:
<p>Select a project title and hit search!</p>
<form action="" method="get">
<input type="hidden" name="todo" id="todo" value="search" />
<select name="proid" id="proid">
<option value="0">All Projects</option>
<?php $projects=getTitles(); foreach($projects as $project){ ?>
<option value="<?php echo $project['title']; ?>" <?php if(isset($_GET['proid']) && $_GET['proid']==$project['title'] ) { echo 'selected="selected"'; } ?> ><?php echo $project['title'] ?>
</option>
<?php } ?>
</select>
<input class="submit_search" type="submit" id="search_button" value="Search"/>
</form>
And this is the code that pulls the project titles from the project table:
function getTitles($where=false)
{
global $wpdb;
$sql="SELECT `title`, `link` FROM `inpu_project` WHERE `link`='1' ORDER BY `title` ASC";
$result = $wpdb->get_results($sql, ARRAY_A);
return $result;
}
All pretty straight forward and it works 100% fine if I replace the non-numeric title in the code for both the inpu_articles and the inpu_project tables with the numeric id.
Then the code does exactly what it does, but when I use the project title instead it just shows ALL of the links that every client ever ordered and no error shows up in my database. It's like it can't find a match or something, which is plain weird.
So am I missing something here? Is it not possible to match words or is there something that I should adjust when using words instead of numeric values?
Lastly, for what it's worth, this is the code that echos the query:
<?php foreach ($backlinks as $backlink) {
$backlink_overview=$backlink['backlink'];
?>
<ul>
<li><?php echo $backlink_overview; ?></li>
</ul>
<?php } ?>
The titles do show up in my form / search drop down menu so I am surprised it can't match the project title with the title that's stored in the article table.
My gut says this is where it goes wrong:
P.`project_title`='.$_GET['proid'];
But it doesn't throw any syntax errors or any errors whatsoever, it just shows all the links that are stored in the inpu_article table, ignorning my search function altogether.
The problem is in the condition for where_clause and the where_clause itself.
To check for input you need to check if the parameter is set and is not empty. Then for where clause you need to put the string into quotes. Change that part of the code like bellow
if(isset($_GET['proid']) && !empty($_GET['proid'])){
$where_clouse.=" AND P.project_title='".$_GET['proid']."'";
}
i think you can be wrong in SQL statement. And you can print the sql string statement to the screen and copy it into Mysql to check. I hope you can find your mistake.

Displying Multiple Arrays Data

I am displaying the list of users in the select box. There are two types of users i-e selected users and non selected users. The values of these users are coming from the database in two arrays i-e One array contains selected users record and other array contains all users record. Now i want if the page loads the selected users record should be shown as selected in the select box and non selected users will be shown as non selected. Here is my code:
if ($selected != false ){
foreach ($selected as $select)
{}
foreach ($data as $rows) { echo $rows->id."<br />"; echo $select->id; ?>
<option value="<?php echo $rows->id; ?>" <?php if ($rows->id == $select->id) echo "selected";?>><?php echo $rows->username; ?></option>
<?php } } else{
foreach ($data as $rows) ?>
<option value="<?php echo $rows->id; ?>" <?php if ($rows->id == $select->id) ?>><?php echo $rows->username; ?></option>
<?php } ?>
The $selected object contains the selected users list and the $data object contains non selected/total number of users
If i am not wrong you have two array like
$arr1 = array(array('id'=>1,"name"=>'abc1',"user"=>'select'),array('id'=>2,"name"=>'abc2',"user"=>'select'),array('id'=>3,"name"=>'abc3',"user"=>'select'),array('id'=>4,"name"=>'abc4',"user"=>'select'),array('id'=>5,"name"=>'abc5',"user"=>'select'),array('id'=>6,"name"=>'abc6',"user"=>'select'),array('id'=>7,"name"=>'abc7',"user"=>'select'));
$arr2 = array(array('id'=>8,"name"=>'abc8',"user"=>'noselect'),array('id'=>9,"name"=>'abc9',"user"=>'noselect'),array('id'=>10,"name"=>'abc10',"user"=>'noselect'),array('id'=>11,"name"=>'abc11',"user"=>'noselect'),array('id'=>12,"name"=>'abc12',"user"=>'noselect'),array('id'=>13,"name"=>'abc13',"user"=>'noselect'),array('id'=>14,"name"=>'abc14',"user"=>'noselect'));
$arraymerege = array_merge($arr1,$arr2); // Merge the array into one
check out the html it display the user selected. i'll just put the condition under select box if user is noselect then it show selected. Please check the image for loop
you are closing your first foreach before you actually get inside the loop...try this. (rewritten with a little shortcode added)
<select name="users" type="multiple">
<?php
//no need to write $selected == false,
//this is the same, a ! will compare this var to false
//also i use : instead because its much nicer to read i.m.o
//its also a little easier to tell the difference from a closing
//if and foreach this way if you have a lot of nested comparisons.
if (!$selected) :
//you want to loop through all rows first.
foreach ($data as $rows) :
//now look at each selected user per user
foreach ($selected as $select) : ?>
//here is where you make the comparison. no need for any other loops
//this is called a turnary comparison. its basically short code for
//if(blah) else this;
//read up on it here:
// http://www.php.net/manual/en/language.operators.comparison.php
//the <?= is the same as <?php echo. This does require for you to have
//short codes turned on in your main php.ini. It usually is though.
<option value="<?= $rows->id; ?>
<?= (($rows->id == $select->id) ? 'selected' :''); ?>
<?= $rows->username; ?>
</option>
endforeach;
endif;
?>
</select>
This is all the code you need. You should only require two loops. The very first loop would iterate through each user, and the nested loop would then compare each of those users to each selected user. Also, the ability to write cleaner code requires planning. I would suggest investing in a white board or a notepad to draw out flow charts, diagrams etc before you start writing your code. You will get a basic picture in your head. There are always 100 million ways to do one thing, but only one way that is right for you. And its up to you to find that way.
From how I read the question, he is showing all users and highlighting the selected ones in a multiple select box. He has multiple selected users so you couldn't merge the arrays together. You would have to compare each user in the table to each selected user then decide if you need to highlight that user or not.

Post multiple values from database, in one Option

I am looking to populate a drop down field with a list of names from a database, and when an option is selected from that drop down, it will post all its values in the row, belonging to that chosen option.
This is probably hard to describe/understand, so to help illustrate, this is my table row:
I then proceed to populate the dropdown, and associate its value to whatever the selected option is posted
//////db_conx is db connection //////main_meal is table name
<form action="#" method="post">
<?php
$dropdown = $db_conx->query("SELECT * FROM main_meal") or die ("somethings broken");
while($array[] = $dropdown->fetch_object());
//echo '<option value ="'.$record['Mname'].'">'.$record['Mname'].'"</option>';
array_pop($array);
?>
<select name="changeCal">
<?php foreach($array as $option) :?>
<!--//get chosen value in drop down, and get its calories-->
<option value="<?php echo $option->calories;?>"><?php echo $option->Mname; ?></option>
<?php endforeach; ?>
</select>
This works great for one value, such as calories, in the above code, but I need more values.
For example, if choose Healthy egg and chips, the value will post 218, as the loop only associates calories and names at the moment.
I attempted various things, like this post:How to get multiple values from a single <select> variable in HTML/PHP?
But the foreach errors.
How can I something similar to what I have done, but store multiple values from one chosen option?
Thank you
Well, I think I understood your problem, but I think that the way you want to use is not usable, maybe I recommend that you put the id in the value of the option in the < select> and then with php you can get all the data from the data base.
For me that is the best way, but if you want do it like the example that you show, you can make an string, for example:
<option value="id:5_calories:258_protein:11g">Healthy eggs & Chips</option>
with your php should look like:
echo '<option value="id:'.$option->id.'_calories:'.$option->calories.'_protein:'.$option->protein.'">'.$option->Mname.'</option>';
you can make bigger the string with others values that you want to put.
In the backend when you send the select you can catch the data with a:
$myArray = explode("_", $_POST["changeCal"]);
Then you will get an array with values like:
$myArray[0]; // id:5
$myArray[1]; // calories:258
$myArray[2]; // protein:11g
Then if you need for example the calories you can make an explode like:
$calories = explode(":",$myArray[1]);
And you will have:
$calories[0]; //calories
$calories[1]; //258 <= Here are the calories.
Maybe if you want to do it of that way, this can be the easiest way, but I recommend send the ID.
Let me know if you need more help. Regards, Have a nice day.

Not understanding how to add cart into PHP

I am stuck on this code. I am making a web page and on the side there is a place for a cart. And with the you should be able to click on an item and add it to cart. Well I am having trouble getting it to add it to cart. Can someone help me understand what I should be doing. I have been working on it for a few days and no matter what I am doing nothing is working. If i get the code to show you have 0 in your cart it wont add anything if i try to put it in the cart.
<h1>Cart Contents?</h1>
<div class="p2">
<?php
// Get all the categories and
// link them to category.php.
// Define and execute the query:
$q = 'SELECT category_id, category FROM categories ORDER BY category';
$r = mysqli_query($dbc, $q);
// Fetch the results:
while (list($fcid, $fcat) = mysqli_fetch_array($r, MYSQLI_NUM)) {
// Print as a list item.
echo "<li>$fcat</li>\n";
if($_SERVER['PHP_SELF']!="CART FILE"){
echo "<h1>Cart Contents</h1>";
echo "<div class=\"p2\">";
$itemCount=X;
foreach($_SESSION['cart'] as X=>X){
for($i=0;$i<count(X);$i++){
$itemCount+=X;
}
}
echo "You have ".$itemCount." total items in your cart.";
echo "</div>\n";
} // End of while loop.
?>
<h1>Specials?</h1>
<div class="p2">
<p>Maybe place specials or new items or related items here.</p>
</div>
</div>
<div class="content">
Ok here is a link to what the cart should do if you look over to the side it should do what that one is doing.
http://www.programmerskit.com/advPHP/ch5/
Shouldn't
$itemCount=X;
foreach($_SESSION['cart'] as X=>X){
for($i=0;$i<count(X);$i++){
$itemCount+=X;
}
}
just be:
$itemCount = count($_SESSION['cart']);
I can't otherwise figure out what that code is supposed to be doing.
Also, that code that outputs the cart appears to be in a while loop outputting each item category, so you will be displaying the cart multiple times, which I can only assume is not desired functionality.
Also, another poster made a point about the invalid use of X as a constant, which is also a good point.
You've got a bare X used all over the place. While saying
$somevar = X;
would be legitimate if you'd already done define('X', 'somevalue') previously, this next one
foreach($_SESSION['cart'] as X=>X){
is completely invalid. You cannot assign new values to a defined constant, let alone try to assign TWO different values at the same time
foreach($_SESSION['cart'] as $key => $value)
is how that particular bit of code should be.

Categories