Trying to get multiple radio buttons passed through form - php

I have a while loop printing multiple checkboxes..I changed them to checkboxes instead of radio buttons.. now all I want to do is pass the names of all those checkboxes to my vote.php file. If I give my checkbox in my loop a simple name and carry that over to my vote.php which handles all my POST data, it only carries over my last selection.. I want all of my selections. I cleaned my code up for you guys a little bit.
Tell me where I am going wrong here.. here is my initial code printing the buttons..
while($row_nominee=mysql_fetch_array($result_nominee)){
$id = $row_nominee[0];
//print "$level";
$prefix = $row_nominee[1];
$fname = $row_nominee[2];
$lname = $row_nominee[3];
$suffix = $row_nominee[4];
$city = $row_nominee[5];
$state = $row_nominee[6];
$zip = $row_nominee[7];
$bio = $row_nominee[8];
$level = $row_nominee[10];
$name = $prefix . " " . $fname . " " . $lname;
$address = $city . " " . $state . " " . $zip;
//print "$voted";
print "<tr>";
print "<td width=\"4\" valign=\"top\"><input type=\"checkbox\" name=\"candidateOne\" id=\"candidate\" value=$id></td>";
print "<td valign=\"top\"><FONT face=Tahoma,Arial,Helv size=-1><b>Name:</b> <font color=\"#ff0000\">$name</font><br><b>Hometown:</b> $address<br><b>Bio:<br /></b> $bio</font></td>";
print "</tr>";
}
?>
//now here is my vote.php file which handles the checkboxes.
//get the contents from the vote ballot Form
$voter_id = safeEscapeString(qsrequest(voter));
$candidate_id = safeEscapeString(qsrequest(candidateOne));
//print "$voter_id and $candidate_id";
include '../../sql/usagym_connection.php';
if(qsrequest(correct))
{
$voter_id1= safeEscapeString(qsrequest(voter1));
$candidate_id1= safeEscapeString(qsrequest(candidate1));
$votes1= safeEscapeString(qsrequest(votes1));
$votes1 += 1;
$sql_voter = "update stateChair_voters set voted='Y' where (usagnum='$voter_id1')";
//print "$sql_voter<br>";
$result_voter = mysql_query($sql_voter, $link) or die("Invalid query2");
$update_candidate = "update stateChair_nominees set votes=$votes1 where (id=$candidate_id1)";
//print "$update_candidate<br>";
$result_update = mysql_query($update_candidate, $link) or die("Invalid query3");
//print "Total votes is $votes1.";
header( "Location: vote_thanks.html");
exit;
}
else
{
//connect the database
$sql_candidate = "select id, prefix, fname, lname, suffix, city, state, zip, bio, votes from stateChair_nominees where id=$candidate_id";
$result_candidate = mysql_query($sql_candidate, $link) or die("Invalid query1". mysql_error());
while($row_candidate=mysql_fetch_array($result_candidate)){
$id = $row_candidate[0];
$prefix = $row_candidate[1];
$fname = $row_candidate[2];
$lname = $row_candidate[3];
$suffix = $row_candidate[4];
$city = $row_candidate[5];
$state = $row_candidate[6];
$zip = $row_candidate[7];
$bio = $row_candidate[8];
$votes = $row_candidate[9];
$name = $prefix . " " . $fname . " " . $lname;
$address = $city . " " . $state . " " . $zip;
}
?>
All I really want to do is submit multiple people to a vote and not just one person. Thoughts? Thanks guys!
Here is my code for my checkboxes..
print "<td width=\"4\" valign=\"top\"><input type=\"checkbox\" name=\"candidateOne\" id=\"candidate\" value=$id></td>";
Now here is the code that handles these checkboxes.. I didn't write this code and I am having to debug it, so any help is appreciated.
$candidate_id = safeEscapeString(qsrequest(candidateOne));
This code right now handles a string, not a variable. What's the process in having a variable represent multiple checkboxes on the other file while recording them on here?

print "<td width=\"4\" valign=\"top\"><input type=\"radio\" name=\"candidateOne\" id=\"candidate\" value=$id></td>";
You must change the 'name' as you have changed the 'value' in the loop by a variable.

Related

PHP problem with insert into database in while loop

i try to write a website for library as an exercise. I have while loop to display all books in my database. If user is logged in and state(stan) of book(ksiazka) is free(Wolny) it shows button under book. After clicking it takes all free books to database and update their state as hired not only that one which user want. Here is the code, thanks.
$findbook2 ="select ksiazka.id_ksiazka, ksiazka.tytul, ksiazka.id_stan, autor.id_autor, autor.imie_autor, ksiazka.rok_wydania, autor.nazwisko_autor, stan.id_stan, stan.nazwa_stan FROM ((ksiazka inner join autor ON ksiazka.id_autor = autor.id_autor) inner join stan ON ksiazka.id_stan = stan.id_stan);";
$stan = mysqli_query($connect, $findbook2);
while($row = mysqli_fetch_array($stan))
{
echo "Tytuł:" . " " .$row['tytul']." ". "Autor:" . " " . $row['imie_autor']." ". $row['nazwisko_autor']. " ". "Rok wydania" . " ". $row['rok_wydania'] . " ". "Stan ". $row['nazwa_stan']. " ";
if(isset($_SESSION['id_czytelnik'])){
if($row['nazwa_stan']=='Wolny'){
echo '<form method = "GET" action = "ksiazki.php">';
echo '<input type = "submit" name = "submit" value = "Wypożycz"/>';
echo '</form>';
if(isset($_REQUEST['submit'])){
$id_czytelnik = $_SESSION['id_czytelnik'];
$id_ksiazka = $row['id_ksiazka'];
$data_oddania = date('Y-m-d', strtotime('+30 days'));
$wstaw_ksiazke = "INSERT INTO `wypozyczenie`(`id_wypozyczenie`, `id_czytelnik`, `id_ksiazka`, `id_pracownik`, `data_wypozyczenia`, `data_oddania`) VALUES ('','$id_czytelnik','$id_ksiazka',2,NOW(),'$data_oddania')";
if(mysqli_query($connect, $wstaw_ksiazke)){
$update = "Update ksiazka set id_stan = 3 where id_ksiazka = '$id_ksiazka'";
if(mysqli_query($connect, $update)){
echo "Wypozyczyłeś książkę";
}
}
}
}
}
echo "</br>";
}
Consider the statement if(isset($_REQUEST['submit'])) which is always true inside your while loop after clicking submit as it is not unset anyway.It causes repeated execution of a statement while the Array is not empty.

PHP array implode keys and values to function

I'm not too familiar with PHP arrays, I have the following code that generates query to output the results needed.
$allstore = $_POST['store'];
function createSelect($allstore)
{
if (empty($allstore))
return "";
$querySelect = "";
$queryJoin = "";
$baseTable = "";
foreach ($allstore as $store => $value) {
if (!$querySelect) {
$baseTable = $store;
$querySelect = "SELECT " . $store . ".item_no, " . $store . ".actual_price, " . $store . ".selling_price, " . $store . ".qty as " . $store;
} else {
$querySelect .= ", " . $store . ".qty as " . $store;
$queryJoin .= "
INNER JOIN " . $store . " ON " . $baseTable . ".item_no = " . $store . ".item_no";
}
}
$querySelect .= " FROM " . $baseTable;
$query = $querySelect . $queryJoin;
return $query;
}
//Stores to be shown
$allstore = ['s_M9' =>0 , 's_M10' =>1];
$query = (createSelect($allstore));
$result = mysql_query($query);
//rest of code...
As you can see above, at the very top there is $allstore = $_POST['store']; Which collects values based from previous form POST method that has checkbox with the name=store[] .
Now According to the function shown, if I create my own keys and values like this
$allstore = ['s_M9' =>0 , 's_M10' =>1];
the output shows exactly what i'm looking for. But the problem goes on how to let $allstore implode those stores s_M9, s_M10 based on what the user has selected on the previous page ( checkbox )? I mean, the user can select either one of the stores or Both stores . How can I implode the checked results between those brackets without inserting them manually?
Thank You
Edit :
<?php
echo "<form action='somewhere.php' method='POST'>";
$query = "SELECT * from stores_list ORDER BY short Asc";
$result = mysql_query($query);
if(mysql_num_rows($result)>0){
$num = mysql_num_rows($result);
for($i=0;$i<$num;$i++){
$row = mysql_fetch_assoc($result);
echo "<input type=checkbox name=store[] value={$row['short']} style='width:20px; height:20px;'>{$row['short']}";
}
}
else{
//No Stores Available
echo "No Stores Found !";
}
echo "</td><input type='submit' value='Search'/></form>";
$allstore = [];
if (!empty($_POST['store'])) {
foreach ($_POST['store'] as $value) {
$allstore[$value] = 1; // or 0, it doesn't matter because your function adds all the keys
}
}
$query = (createSelect($allstore));
$result = mysql_query($query);
And of course you have to take care of your createSelect function to avoid SQL Injections, please read here

php mysql $_post does not work

I have written this code, but it does not work and I cannot find any mistake. It filters data from mysql database. Below I pasted one code without $_post form and this works fine. But I need a filter due to the high volume of data.
`
include "db_connect.inc.php";
$sql = "SELECT versicherungsnamen, franchise, praemie FROM praemien";
$sql .= " where kanton = " . $_POST["kanton"]
. " and franchise = ". $_POST["franchise"];
$sql .= " order by praemie";
$res = mysqli_query($con, $sql);
$num = mysqli_num_rows($res);
if ($num==0) echo "Keine Datensätze gefunden";
while ($dsatz = mysqli_fetch_assoc($res))
echo $dsatz["versicherungsnamen"] . ", "
. $dsatz["praemie"] . "<br />";
mysqli_close($con);
?>
</body>
</html>`
But when i try this code without $_post option it works fine
<html>
<body>
<?php
include "db_connect.inc.php";
$res = mysqli_query($con, "SELECT versicherungsnamen, franchise, praemie FROM praemien");
while ($dsatz = mysqli_fetch_assoc($res))
{
echo $dsatz["versicherungsnamen"] . ","
.$dsatz["franchise"] . ","
.$dsatz["praemie"] . "<br />";
}
?>
</body>
</html>
before select replace post vars into separate variables then use this new vars in select query.
$kanton = $_POST['kanton'];
$franchise = $_POST['franchise'];
$sql = "SELECT versicherungsnamen, franchise, praemie FROM praemien where kanton = " . $kanton . " and franchise = ". $franchise. " order by praemie";
...

PHP won't echo after a query fetch

I have written up some code to take a upc entry from a text box and upon submit will pass the "upc" to the query code.
My problem is, none of my echos will post to my page. I can get them to post in CLI, but not on my web browser. If I put in test echos before the fetch line of the query they will echo to the page, but anything after the query will not. Here is the code:
<?php
//setup
require_once('Factual.php');
$factual = new Factual("mykeyhere","myotherkeyhere");
$upc = $_GET["upc"];
$query = new FactualQuery;
$query->search($upc);
$res = $factual->fetch("products", $query);
$data = $res->getData();
//print_r($res->getData());
$item = $data[1];
$itemAvgPrice = $item['avg_price'];
$itemBrand = $item['brand'];
$itemCategory = $item['category'];
$itemEan13 = $item['ean13'];
$itemFactualID = $item['factual_id'];
$itemImage = $item['image_urls'][0];
$itemSize = $item['size'][0];
$itemUPC = $item['upc'];
echo "Average Price: " . $itemAvgPrice;
echo "\nBrand: " . $itemBrand;
echo "\nCategory: " . $itemCategory;
echo "\nEan13: " . $itemEan13;
echo "\nFactual ID: " . $itemFactualID;
echo "\nImage URL: " . $itemImage;
echo "\nSize: " . $itemSize;
echo "\nUPC: " . $itemUPC;
?>

Php If statement not working as expected

I am making an email script in php. What happens is a mysql query is made, and the output of this is stored in the following strings :
$personal1 = $userinfo->salutation;
$personal2 = $userinfo->surname;
$business = $userinfo->businessname;
Next I have an if statement, this checks to see if the surname is blank, if it is, it then substitutes the salutation + surname with the business name. The problem I am having is that the emails keep being sent out with Dear, Business Name , even if the surname field is not blank, I am not sure what I am doing wrong with the following code for it to do this though ?.
if ($personal2=="") {
$name = $business; }
else {
$name = $personal1 . ' ' . $personal2;};
EDIT >>>>>>>>>>
If I echo out the contents of the strings I get :
personal1 = Mr
personal2 = Johnson
business = Hat Trick Media
Edit 2 >>>>>>>
This is some of the code, it is then passed onto the mailer.
<?php
$cf_uid = $_GET['token'];
$query = mysql_query("SELECT * FROM hqfjt_chronoforms_data_addupdatelead WHERE cf_uid = '$cf_uid'") or die(mysql_error());
$userinfo = mysql_fetch_object($query);
$personal2 = $userinfo->surname;
$personal1 = $userinfo->salutation;
$business = $userinfo->businessname;
?>
<?php
$result = mysql_query("SELECT * FROM hqfjt_chronoforms_data_addemailtemplate");
while ($row = mysql_fetch_object($result)) {
echo '<tr class="table-row">';
echo '<th class="template-name">';
echo '<div class="namerow">';
$id = $row->cf_uid;
$form_id = $row->form_id;
$query = mysql_query("SELECT `$form_id` FROM email_history WHERE cf_id = '$user_id'") or die(mysql_error());
$datesent = mysql_fetch_object($query);
$date = $datesent->$form_id;
if ($personal2=="") {
$name = $business; }
else {
$name = $personal1 . ' ' . $personal2;};
Is your code a valid statement? Your code structure is awful. Instead of...
if ($personal2=="") {
$name = $business; }
else {
$name = $personal1 . ' ' . $personal2;};
Use
if ($personal2=="") {
$name = $business;
}
else {
$name = $personal1 . ' ' . $personal2;
}
You seem to have an extra ; that you dont need.
You also dont seem to close the while loop in the code you posted...
Ok, I have found out what the problem was, $name was coming in the session from the previous page and overwriting $name on this page, I have now set it to destroy the session before it loads this page and it seems to have sorted it now, thanks for everyone's help :-)

Categories