Mission: Verify that "players" have placed vintage promotional jpegs on their social media site(s). Doing so earns them crypto tokens towards game play. All non-verified postings are displayed on an administrator's dashboard with a checkbox if the listing has been visually verified and "Approved." The value of each checkbox is the database ID of the listing (see screen capture). Once the listings have been verified and the check box ticked, the page is POST(ed) to a query page where the default value "confirm" is changed from 0 to 1. This then awards them the designated tokens.
enter image description here
However, I haven't found the right formula of code to get the UDPATE to work. The checkbox values will display in "echo" mode, but the SQL won't function within the FOREACH loop.
<?php
$checked_arr = $_POST['checkbox'];
$count = count($checked_arr);
echo "There are ".$count." checkboxe(s) are checked <br>";
foreach($_POST['checkbox'] as $val) {
$sql = "UPDATE media SET confirm = 1 WHERE id = $val " ;
echo "$val\n";
?>
Scoured the Net for working examples, including Stack Overflow, but to no avail. Assume there's a simple answer here, but as a novice PHP programmer, it eludes me.
Thank you in advance for suggestions.
you could use the IN operation in the conditional.
The only thing you would have to do is capture all the IDS and do an "implode" to give it the format that is needed for the sql.
for example:
<?php
$ids = [];
foreach($_POST['checkbox'] as $val){
$ids[] = $val;
}
$values = implode(",", $ids); // => 'id1, id2, id3, ...'
// this is a massive update based on selected items
$sql = "UPDATE media SET confirm = 1 WHERE id IN ($values)";
?>
Related
I've started to code in April 2021 so I'm super new to this. Working on my final exam, I'd need your precious help! I want to generate a dynamic list from a database, containing 2 joined tables (users and interest). The 2 tables both contain "ID_user" which links them as a foreign key. The idea is that one the user is logged in, the profile page displays all the interests the user selected at sign up. At the moment I can only display the last interest selected and not all of them.
Here is my php:
$request2 = "SELECT `interest`.`name_Interest`
FROM `interest`
INNER JOIN `users`
ON `interest`.`ID_user` = `users`.`ID_user`
WHERE `pseudo` = '".$url_pseudo."'
";
$resultat2 = mysqli_query($connexion, $request2) or die (mysqli_error($connexion));
$nb_resultat2 = mysqli_num_rows($resultat2);
if ($nb_resultat2 > 0) {
while ($row = mysqli_fetch_array($resultat2)){
$name_Interest = $row["name_Interest"];
}
}
Here is the HTML displaying the response:
enter image description here
Here is my db:
enter image description here
Any idea why I can get only 1 value?
enter image description here
thanks in advance
Your while loop is writing to the same variable for each iteration of the loop;
while ($row = mysqli_fetch_array($resultat2)){
$name_Interest = $row["name_Interest"];
}
This will leave $name_Interest containing the last value from your database after the loop has completed.
To resolve this, you will need to keep a list of interest names - this can be achieved by using an array. PHP Array Documentation
// Declares the empty array
$interests = [];
// Loop through database results
while ($row = mysqli_fetch_array($resultat2)){
// Add this value to the array
$interests[] = $row["name_Interest"];
}
Now, $interests will hold all of the values from the database!
You will need to print these out differently in your HTML, by looping through all the values in the array and printing one at a time:
(PHP foreach documentation)
<ul>
<?php foreach ($interests as $interest) { ?>
<li><?php echo $interest; ?></li>
<?php } ?>
</ul>
Solution
Simple store all user interests on array and then show in iteration on page.
Code:
$user_interests=array();
while ($row = mysqli_fetch_array($resultat2)){
$user_interests[] = $row["name_Interest"];
}
Now $user_interests array holds all interests of users as a result of join.
At last loop over it
<?php foreach ($user_interests as $interest) { ?>
<p><?php echo $interest; ?></p>
<?php } ?>
okay friends,
I have two tables
1st table: social_networks
2nd table: members_social_accounts
In the user control panel, I have a page contains a form where I list all the social networks; and in a front of each one of them there is an input text box.
When the member opens that page, he will see all the social networks listed, and if he previously added his account in any social network, then he will see it in the text box, otherwise, the text box will be empty. I used the following code to that:
$s = mysqli_query($link, "SELECT social_networks.network_id, social_networks.network_name, members_social_accounts.member_account FROM social_networks LEFT JOIN members_social_accounts ON social_networks.network_id = members_social_accounts.network_id AND members_social_accounts.member_id = '$member_id' ORDER BY social_networks.network_id");
while($i = mysqli_fetch_assoc($s)){
$network_id = $i['network_id'];
$network_name = $i['network_name'];
$member_account = $i['member_account'];
}
and the input box is:
<?=$network_name;?> = <input type="text" name="ids[<?=$network_id;?>]" id="<?=$network_id;?>" value="<?=$member_account;?>" /><br />
Now, what I am trying to do is when the user update the page (submit the form), I want the code to update the database by the following steps:
If the member (e.g. $member_id =1 ) has already added his account to that network (e.g. $network_id = 1) then, we will UPDATE the members_social_accounts table with the member network account (e.g. $member_account = 1111111111). So, I DO NOT add a new record for the same member_id and the same network_id but with different account value.
so, the database table will be something like this:
else if the member (e.g. $member_id=1) is adding a new account (e.g. $member_account = 2222222222) to a network (e.g. $network_id = 3), then I want to INSERT that to the members_social_accounts table as a new record, and the table will be for example like the following:
What I've tried so far is the following:
<?php
if(isset($_POST))
{
foreach($_POST['ids'] AS $ids)
{
$s = mysqli_query($link, "SELECT * FROM members_social_accounts WHERE network_id = '{$ids}' AND member_id = '$member_id'");
echo $n = mysqli_num_rows($s);
if($n == 1)
{
// UPDATE the members_social_accounts table
}
else
{
// INSERT a new record in members_social_accounts table
}
}
}
?>
but I have a problem which is that $_POST[ids] AS $ids is getting the member_account (e.g. aaaaaaaaaa and bbbbbbbbbb) instead getting the netword_id (e.g. 1 and 2). Therefore, I am not able to update or insert in the members_social_accounts table.
I appreciate your help in pointing what is wrong with my code or logic.
Thanks in advance
P.S. You can download a copy of the files and the database from this link:
sample files and db
This is due to the fact that the actual value of your input is the member_account field.
<input type="text" name="ids[<?=$network_id;?>]" id="<?=$network_id;?>" value="<?=$member_account;?>" />
Take a look at the value which has been assigned the return from $member_account variable.
You could just do:
<input type="hidden" name="nid" value="<?=$network_id;?>"/>
Then you can do $_POST['nid'] to get the real value of the network id.
I'm quite new to php and mysql so forgive me if I'm doing this completely wrong. I am making a printing balance application and the code below is a part of it.
$command="SELECT itemname FROM items";
$results = mysql_query($command);
while($row = mysql_fetch_assoc($results))
{
foreach ($row as $key => $value) {
print "<input type='radio' name='itemtype' value='$value'>".$value."</input><br />";
}
}
This here is supposedly the price printing form where the user chooses between SHORT BOND PAPER and LONG BOND PAPER (the column itemname from items). The options appear as radio buttons. It works but now I'm stuck with the issue of being able to fetch the price as inserted in their respective rows. Since the itemname and their price are all user-inputted into the database, I'm not supposed to declare their specific price into the code itself, and should be able to retrieve it from the database. I want to be able to get the prices based on the item chosen by the user once they click submit, because I'd need to do this to compute for the price of printing when multiplied with the number of pages later.
I think it's definitely possible but I'm not quite sure how. Theoretically, it would be along the lines of SELECT itemprice FROM items WHERE itemname = $value but ha, I don't think it works that way.
solution edit: here's the complete solution for reference. $compute is just a sample to test if it works while 5 is a sample number of pages that would be entered.
if ($command = mysql_query("SELECT `itemprice` FROM `items` WHERE `itemname` LIKE '" . mysql_escape_string($_POST['itemtype']) . "'"))
{
while($row = mysql_fetch_assoc($command))
{
$compute = $row['itemprice'] * 5;
echo $compute;
}
}
else
{
echo (mysql_error ());
}
It would be something like that indeed.
SELECT itemprice FROM items WHERE itemname = $_POST['itemtype']
assuming that itemprice is the actuial colum of the price. HOwever, doing it like this, makes your code vulnerable to mysql injections. So before you contine, consider reading up a little.
Ive been battling away with the following problem
Ive got a page where I pull names from players specific to their positions in a sport squad.
Example: I will display all the Wings in the squad using a dropdown where a coach can then pick his wing for the game.
There are dropdowns for each different position
The aim of the page is to let the coach quickly select his team for a fixture
After the coach selected his team he will, select the opponents for which the selected team will play against.
When he clicks submit the selected oppents and players will get stored in two arrays which will get called to display the team selected and their opponents on a new page. (After which it will get uploaded to the DB.)
I am having trouble getting the values from the select list to display on the new page.
I guess I have to do something like this on the new page:
foreach ($_REQUEST['opponents'] as $opponents){
print $opponents;
echo'<br>';
}
but it is not giving the desired results.
Strangely what gets printed is the variable name from the previous page select menu.
Upon further inspection I did a vardump on the new page and it says that $opponenets gets passed a value of string which is the variable name and not the value thereof?
My page looks like this
My question is how would I go abouts getting the values from the select dropdowns
if(isset($_POST["submit"]))
{
foreach ($_REQUEST['opponents'] as $against){
var_dump($against);
print $against;
echo'<br>';
}
}
else
{
echo'<h1>Select your Team</h1>';
$x = array("THP", "HKR", "LHP", "LH", "FLH"); //players positions gets assigned to x which will be used to query the database
echo '<form name="playerselect" method="post" action="">';
//query database with different query after each loop
for ($i = 0; sizeof($x) > $i; $i++)
{
//query where position field equeals variable x
$result = mysql_query("SELECT `name`, `position` FROM `player_info`
WHERE `position` = '$x[$i]'") or die(mysql_error()) ;
//Gets data from DB and assigns values to arrays below
while($row = mysql_fetch_array($result))
{
$playername[] = $row['name'];
$position[] = $row['position'];
}
//print player position
print $position[0];
echo'<br>';
//unset the array so that it is empty for the next query in the new loop
unset($position);
echo '<select name="players[]" >' ;
foreach ($playername as $name )
{
//Put playernames relevant to the position in the option element
echo'<option value="$name" selected="selected">'.$name;'</option>';
echo'<br>';
}
echo'</select>';
//unset array so that its contents is empty for the next query in the new loop
unset($playername);
echo'<br>';
}
You cannot. Your submit will only transmit select values. This is not a bug, it is a feature. You do not want to send data back and forth from/to the server/client which is known to both of them.
On the server you are free to query your database at any time. You can also cache your select list into the $_SESSION variable in your initial list read. However this is advanced fittling as your cache list may become outdated and also your server memory utilization must leave space for file caching (the SESSION cache goes to files).
If you go for the database query you may need some ID as sort of anchor. Just put the into the $_SESSION variable - eg.:
$_SESSION['positions']=$x;
In your example the $x seems to be static, which obviously reduces the need to cache it into the $_SESSION - however on other occasions you may need this method.
I have a database with the following table:
id value
-----------
1 yes
2 no
3 no
4 maybe
I'm using some simple php to log the choices entered on a poll website. The user selects a radio box and it is entered into the above table. However, I want to make this a little more flexible. I created a simple backend that allowed an admin user to add or delete poll choices. What would I do to show on the frontend the number of votes for each individual choice, when the number of choices is not constant? I know I could do this easily if the poll choices were static but since the backend user will be changing the choices, how could I dynamically display the results?
I am not really sure what you are asking. Is it COUNT you're looking for?
Don't worry about the choices or the number of choices, grab all the votes/choices and iterate through them and add them to an array indiscriminately: http://codepad.org/LWPyuTqj
$total = array();
$votes = array(1=>'yes',2=>'no',3=>'no',4=>'maybe');
foreach($votes as $vote) {
if (!isset($total[$vote]))
$total[$vote] = 1;
else
$total[$vote] += 1;
}
print_r($total);
I would recommend google graph API for this. It is really easy!
http://code.google.com/apis/chart/interactive/docs/gallery/piechart.html
Generate the code dynamically, using the first example on the link above. First select the values. This assuming there is a question ID so you can relate to the question. In this case id 1.
$result = mysql_query('SELECT value,COUNT(*) as num FROM choises WHERE question_id = 1 GROUP BY value');
Then with PHP loop through the data
$results = array();
while ($row = mysql_fetch_assoc($result)){
$results[$row['value']] = $num;
}
With this you can generate the graph:
echo 'data.addRows('.count($results).');';
$i = 0;
foreach ($results as $value => $num){
echo'
data.setValue('.$i.', 0, "'.$value.'");
data.setValue('.$i.', 1, '.$num.');
';
$i++;
}