I would like to populate addresses for client from my db.
I use this code to select from db:
$stmt = $conn->prepare("SELECT * FROM peopleaddress WHERE peopleID=?");
if ( !$stmt ) {die(printf("Error: %s.\n", mysqli_stmt_error($stmt) ) );}
else if ( !$stmt->bind_param('i', $peopleID ) ) {die(printf("Error: %s.\n", mysqli_stmt_error($stmt) ) );}
else if ( !$stmt->execute() ) { die(printf("Error: %s.\n", mysqli_stmt_error($stmt) ) ); }
else {
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
$addressID_array = array ($row['addressID']);
$addresstype_array = array ($row['addresstype']);
$addressactive_array = array ($row['active']);
$street_array = array ($row['street']);
$city_array = array ($row['city']);
$town_array = array ($row['town']);
$state_array = array ($row['state']);
$zip_array = array ($row['zip']);
$country_array = array ($row['country']);
$latitude_array = array ($row['latitude']);
$longitude_array = array ($row['longitude']);
}
} /* end else */
and this code to display the form:
<?php
for ($i = 0; $i < count($addressID_array); $i++) {
echo '<input type="text" name="street[]" id="" placeholder="street" value="';
if (isset ($street_array[$i])){echo $street_array[$i];} echo '" />';
echo '<input type="text" name="city[]" id="city" placeholder="city" value="';
if (isset ($city_array[$i])){echo $city_array[$i]; } echo '" />';
echo '<input type="text" name="zip[]" id="zip" placeholder="postalcode" value="';
if (isset ($zip_array[$i])){echo $zip_array[$i]; } echo '" />';
echo '<input type="text" name="town[]" id="town" placeholder="town" value="';
if (isset ($town_array[$i])){echo $town_array[$i]; } echo '" />';
echo '<input type="text" name="state[]" id="state" value="';
if (isset ($state_array[$i])){echo $state_array[$i];} echo '" />';
echo '<input type="text" name="country[]" id="country" value="';
if (isset ($country_array[$i])) {echo $country_array[$i];} echo '" />';
echo '<input type="text" name="addresstype[]" id="" value="';
if (isset ($addresstype_array[$i])) {echo $addresstype_array[$i];} echo '" />';
echo '<input type="text" name="addressactive[]" id="" value="';
if (isset ($addressactive_array[$i])) {echo $addressactive_array[$i];} echo '" />'; echo '<input type="text" name="latitude[]" id="latitude" READONLY value="';
if (isset ($latitude_array[$i])) {echo $latitude_array[$i];} echo '" />';
echo '<input type="text" name="longitude[]" id="longitude" READONLY value="';
if (isset ($longitude_array[$i])) {echo $longitude_array[$i];} echo '" /> <br>';
}
?>
Problems:
1) it only display one address, even if in db there are 2 addresses for the same client.
2) I'm pretty new at this. Am I doing it right or there is a fastest (less code) option to do this?
Thanks!!
The problem is within your while loop:
$addressID_array = array ($row['addressID']);
This assigns a new array every time the while loops to the variables. These assignment lines should all be changed like
$addressID_array[] = $row['addressID'];
As for your 2nd question: it is not really answerable because we do not know the requirements you need to work against.
Check out : https://en.wikipedia.org/wiki/SQL_injection
Look down at the "Hexadecimal Conversion" part. I put a short function to do SQL commands in there. When you get the information back it will be in an array. So if you used $row to get the information back it would be in $row[0][<Fields>], $row[1][<Fields>], and so on.
The problem with the above is - every time you do the "array()" it makes a new array. So it wipes what you had in there before. :-)
You are overwriting the values in your array by doing this
$addressID_array = array ($row['addressID']);
instead of
$addressID_array[] = $row['addressID'];
Update:
Also, it would be a good idea to iterate over your data, instead of making an array of data and then reading that array again. Use this:
else {
$result = $stmt->get_result();
}
// Then in display
while($row = $result->fetch_assoc()) {
echo '<input type="text" name="street[]" id="" placeholder="street" value="';
if (isset ($row['street'])){echo $row['street'];} echo '" />';
}
Related
I have a form with multiple checkboxes and hidden inputs, which I'm passing to a second page using GET.
I'm then trying to retrieve the value of each checkbox and the input in a loop and echo out the combined value.
HTML:
<form action="criteria.php" method="GET">
<input name="id[]" type="hidden" value="<? echo $criteria_id; ?>" />
<input type="checkbox" name="checked[]" class="checkbox-md" id="<? echo $criteria_id; ?>" value="Y">
<button type="submit" class="btn btn-lilac" role="button">Complete</button>
</form>
PHP:
$criteria_id = $_GET['id']; //get all criteria id
$criteria_checked = $_GET['checked']; //get checked criteria id
foreach($criteria_id as $id) //get id of all checkboxes {
echo "<BR>Criteria = ".$id."Checked = ".$criteria_checked; //returns id + array?
if ($checked='Y')//check if checked {
echo "<BR>Criteria =".$id." Checked = Y";
} else {
echo "<BR>Criteria =".$id." Checked = N";
}
}
You will need to make sure that the inputs have matching array keys:
<input name="id[0]" type="hidden" . . .
<input name="checked[0]" type="checkbox" . . .
<input name="id[1]" type="hidden" . . .
<input name="checked[1]" type="checkbox" . . .
Depending on how you create these you could use the $criteria_id:
<input name="id[<? echo $criteria_id; ?>]" type="hidden" . . .
<input name="checked[<? echo $criteria_id; ?>]" type="checkbox" . . .
This way the id and checked array keys will match. All hidden inputs will be passed from the form but only the checked checkboxes, so check if the key of the id is set in the checked array:
foreach($_GET['id'] as $key => $id) {
if (isset($_GET['checked'][$key])) {
echo "<BR>Criteria =".$id." Checked = Y";
} else {
echo "<BR>Criteria =".$id." Checked = N";
}
}
There are two values I want to get from user that is name and price. I have made an auto generating rows function that generate input boxes with same name. Now the thing is I want to store them in database. I using foreach but that only get one array. I want to store both name as well as price. How can I do that. Here is my code.
HTML Form
<form method="post">
<input type="text" name="name[]" /><input type="text" name="price[]" />
<input type="text" name="name[]" /><input type="text" name="price[]" />
<input type="text" name="name[]" /><input type="text" name="price[]" />
<input type="text" name="name[]" /><input type="text" name="price[]" />
<input type="submit" value="Submit" name="submit" />
</form>
PHP Code
if(isset($_POST['submit']))
{
foreach($_POST['name'] as $name)
{
echo $name;
}
}
Call the index in the loop as well and then select the corresponding value from the other array.
foreach($_POST['name'] as $id => $name)
{
echo $name;
echo $_POST['price'][$id]
}
How about this
if(isset($_POST['submit']))
{
$names = $_POST['name']; # array
$prices = $_POST['price']; # array
foreach($names as $id => $name)
{
echo $name;
echo "<br>";
echo $prices[$id]
}
}
Provided you know both arrays will be the same length, a simple for loop will do:
if(isset($_POST['submit']) && count($_POST['name']) == count($_POST['price']))
{
for($i=0; $i < count($_POST['name']); $i++)
{
echo $_POST['name'][$i] . ' ' . $_POST['price'][$i];
}
}
Try this
$names = array_combine($_POST['name'], $_POST['price']);
foreach($names as $firstname => $price) {
echo $firstname . ' ' . $price . '<br>';
}
I have displayed check box values(ugroup field) from group table.now what i want to do is,when user select multiple check boxes and submit it should be insert into relavent column in one row.now it's insert check boxes values.but not in relevant column .this is my code.Please help me.
//select ugroup's from group table.
<?php
$result = "SELECT id,ugroup FROM group";
$res_result = db::getInstance()->query($result);
?>
<form action="db_sql/db_add_page.php" method="get">
Tittle :<input type="text" size="100" name="tittle" />
Description :<textarea cols="80" id="editor1" name="description" rows="10"></textarea>
//Display ugroups in textboxes and checkboxes
<?php
while( $line=$res_result->fetch(PDO::FETCH_ASSOC)) {
echo '<input type="checkbox" name="group[]" value=" '. $line['ugroup'] .'" />';
echo'<input type="text" name="ugroup" disabled="disabled" value=" '. $line['ugroup'] .'" size="7" "/>';
echo ' ';
}
?><input type="submit" value="Submit">
</form>
db_add_page.php
if(isset($_POST))
{
$tittle = $_POST['tittle'];
$description = $_POST['description'];
$ugroup = $_POST['group'];
$acc_status = "INSERT INTO add_services (id,tittle,description,g1,g2,g3,g4,g5,g6,g7,g8)
VALUES(NULL,'".$tittle."','".$description."','".$ugroup[0]."','".$ugroup[1]."','".$ugroup[2]."','
".$ugroup[3]."','".$ugroup[4]."','".$ugroup[5]."','".$ugroup[6]."','".$ugroup[7]."')";
$rate = db::getInstance()->exec($acc_status);
if(!$rate){
echo '<script type="text/javascript">alert("Update Error !");</script>';
}else{
header('Location:../add_page.php');
echo '<script type="text/javascript">alert("Successfuly Updated User Group !");</script>';
}
}
i click on checkbox2,checkbox8 and submit.it's insert to g1 and g2.when i click on checkbox 1, checkbox3 its also added to g1 and g2.like below
Change line
echo '<input type="checkbox" name="group[]" value=" '. $line['ugroup'] .'" />';
To
echo '<input type="checkbox" name="group['.$line['id'].']" value=" '. $line['ugroup'] .'" />';
And yes start array index using 1
Normally, when we use $_POST values in checkboxes, those that are not checked will not be included in POST.
[group] => Array
(
[G1] => G1 // those the one you did not picked will not be included
[G3] => G3 // so that means your input is jagged
[G5] => G5 // you cannot hardcode each index (0 - 7)
[G7] => G7 // or they will be undefined (the ones that are missing)
)
So what you do is create a default value (an array) which will hold the defaults.
Then you combine those inputs, to the ones you have in default so that in return you will have a complete structure of insertion, instead of jagged inputs.
So in your form, do something like this:
while($line = $res_result->fetch(PDO::FETCH_ASSOC)) {
echo '<input type="checkbox" name="group['.$line['ugroup'].']" value=" '. $line['ugroup'] .'" />';
// assign G1, G2, indices
echo'<input type="text" name="ugroup" disabled="disabled" value=" '. $line['ugroup'] .'" size="7" "/>';
echo ' ';
}
Then on your processing form:
$default_values = array(); //create a default value
while($line = $res_result->fetch(PDO::FETCH_ASSOC)) {
$default_values[':' . $line['ugroup']] = '';
}
if(isset($_POST)) { // if submitted
$ugroup = array();
$temp = $_POST['group'];
foreach($temp as $val) {
$ugroup[':' . $val] = $val;
}
$combined_input = array_merge($default_values, $ugroup); // combine them so you have a complete structure
$sql = 'INSERT INTO add_services (tittle, description,g1,g2,g3,g4,g5,g6,g7,g8) VALUES (:title, :description, :G1, :G2, :G3, :G4, :G5, :G6, :G7, :G8)';
$acc_status = $db->prepare($sql);
$insert = array(':title' => $title, ':description' => $description,);
$insert = array_merge($insert, $combined_input);
$acc_status->execute($insert);
}
OK this is my script:-
<form action="results.php" method="post">
<?php mysql_select_db($database, $databasename) or die("Opps some things went wrong");
$sqlQueryTestDisplay = mysql_query("SELECT * FROM questions WHERE test_id='$testtaken_id' ORDER BY question_id ASC");
$i = 0;
while($DisplayItems = mysql_fetch_array($sqlQueryTestDisplay))
{
$i = $i + 1;
$question_id = $DisplayItems['question_id'];
$question = $DisplayItems['question'];
$opta = $DisplayItems['opta'];
$optb = $DisplayItems['optb'];
$optc = $DisplayItems['optc'];
$optd = $DisplayItems['optd'];
$answer[$i] = $DisplayItems['answer'];
$thisAnswer = $answer[$i];
echo '<li>'.$question.'</li>';
echo '<p>';
echo '<label><input type="radio" name="optans'.$i.'" value="radio" id="RadioGroup'.$i.'_0" />'.$opta.'</label>';
echo '<label><input type="radio" name="optans'.$i.'" value="radio" id="RadioGroup'.$i.'_1" />'.$optb.'</label>';
echo '<label><input type="radio" name="optans'.$i.'" value="radio" id="RadioGroup'.$i.'_2" />'.$optc.'</label>';
echo '<label><input type="radio" name="optans'.$i.'" value="radio" id="RadioGroup'.$i.'_3" />'.$optd.'</label>';
echo '<input name="ans'.$i.'" type="hidden" value="'.$thisAnswer.'" />';
echo '</p>';
}
echo '<input name="total_questions" type="hidden" value="'.$i.'" />';
echo '<input name="test_id" type="hidden" value="'.$TestID.'" />';
?>
<input name="submittest" type="submit" />
</form>
As you can see i am using array to store values in different fields. Now on the next page i.e on my result.php page I am writing this:-
<?php
if(isset($_POST['submittest']))
{
global $ans1;
$TotalQuestions = $_POST['total_questions'];
$TestID = $_POST['test_id'];
$TestResult = 0;
for ($i=1; $i<=$TotalQuestions; $i++)
{
$ansValue = 'ans'.$i;
$optansValue = 'optans'.$i;
$ans = $_POST[$ansValue];
$optans = $_POST[$optansValue];
if ($ans == $optans)
{
$TestResult = $TestResult + 1;
}
}
$st_id = $row_Recordset1['id'];
mysql_select_db($database, $databasename) or die("Opps some things went wrong");
$sqlQueryInsertResult = mysql_query("INSERT INTO results (student_id, test_id, test_result) VALUES ('$st_id', '$TestID', '$TestResult')");
header('location:results.php');
}
?>
Now my script is not reading ans1, ans2.....and so on AND even quesans1, quesans2.....and so on.
I think problem is in the way i am calling the array using the $_POST method.
Is the syntax correct, how can i FIX it... Please help :|
All of your radio buttons are returning "radio" as their value. Make them return the answer and you should be OK
Change your radio definitions to:
'<INPUT type="radio" name="optans'.$i.'" value="'.$opta.'" >'.$opta.'</INPUT>'
'<INPUT type="radio" name="optans'.$i.'" value="'.$optb.'" >'.$optb.'</INPUT>'
'<INPUT type="radio" name="optans'.$i.'" value="'.$optc.'" >'.$optc.'</INPUT>'
'<INPUT type="radio" name="optans'.$i.'" value="'.$optd.'" >'.$optd.'</INPUT>'
Might be worth not putting the answer onto the page as a hidden field - makes a quiz quite easy. Do another SQL query to check the answers when they come back
Use some more loops to display the radio buttons and you can shorten your code a bit.
0Change your test options to this:
echo '<label><input type="radio" name="optans'.$i.'[]" value="1" id="RadioGroup'.$i.'_0" />'.$opta.'</label>';
echo '<label><input type="radio" name="optans'.$i.'[]" value="2" id="RadioGroup'.$i.'_1" />'.$optb.'</label>';
echo '<label><input type="radio" name="optans'.$i.'[]" value="3" id="RadioGroup'.$i.'_2" />'.$optc.'</label>';
echo '<label><input type="radio" name="optans'.$i.'[]" value="4" id="RadioGroup'.$i.'_3" />'.$optd.'</label>';
and your processor to this:
<?php
if(isset($_POST['submittest']))
{
global $ans1;
$TotalQuestions = $_POST['total_questions'];
$TestID = $_POST['test_id'];
$TestResult = 0;
for ($i=1; $i<=$TotalQuestions; $i++)
{
$ans = $_POST['ans'.$i];
$optans = $_POST['optans'.$i];
for ($j=0;$j<count($optans);$j++) {
if ($optans[$j]==$ans) {
$TestResult = $TestResult + 1;
}
}
}
This is a very insecure way to compare test answers. Someone could easily View Source and see the correct answers. You should validate the test answers after the $_POST
I am trying to update multiple rows here.However I fail to point the right ID of the row.
<?php
$table = 'DynamicPage';
$query = mysql_query(Query::SelectAllFrom($table));
// Count table rows
$count = mysql_num_rows($query);
while ($row = mysql_fetch_array($query)) {
$id[] = $row['ID'];
echo '
<h3>Column name: </h3><input type="text" name="name" maxlength="30" value="' . $row['Name'] . '" />
<h3>Tekst: </h3><textarea type="text" name="fulltext[]" maxlength="2000">' . $row['FullText'] . '</textarea>';
}
echo '<input name="Submit" type="submit" value="Submit" />
</form>';
// Check if button name "Submit" is active, do this
if (isset($_POST['Submit'])) {
for ($i = 0; $i < $count; $i++) {
$queryUP = mysql_query("UPDATE $table SET Name='" . $_POST['name'] . "' WHERE id='??????????????'");
$result = mysql_query($queryUP);
}
if ($result) {
header("location:index.php");
}
}
?>
So far I can update the first row (if id='1') from the last <h3>Column name: </h3><input type="text" name="name"... I know that I am not passing the ID's in the right way, but I have to idea about the syntax. If anyone has an idea, please let me know :)
Thanks
Perhaps you should add a hidden input field with IDs:
HTML part
<input type="hidden" name="id[]" value="'.$row['ID'].'" />
<h3>Column name: </h3><input type="text" name="name[]" maxlength="30" value="'.$row['Name'].'" />
<h3>Tekst: </h3><textarea name="fulltext[]" maxlength="2000">'.$row['FullText'].'</textarea>';
PHP
for($i=0; $i<count($_POST['ID']); ++$i){
//query goes here
}
SQL QUERY
UPDATE $table SET Name='{$_POST['name'][$i]}', Tekst='{$_POST['fulltext'][$i]}' WHERE id='{$_POST['id'][$i]}'
This is from top off my head, not tested, but should give you an idea.
And of course, escape all the input fields.
Try this after your $_POST['Submit'] isset test:
for($i=0;$i<sizeof($id);$i++) {
$queryUP = mysql_query("UPDATE $table SET Name='".$_POST['name']."' WHERE id = " . $id[$i]);
$result = mysql_query($queryUP);
}
input type="text" ids="id[]" maxlength="30" value="'.$row['id'].'"
//then submit part
for($i=0; $i<count($_POST['id'];$i++) {
$queryUP = mysql_query("UPDATE $table SET Name='".$_POST['name']."' WHERE id='$_POST['id'][$i]'");
$result = mysql_query($queryUP);
}
You may concatenate $row['ID'] and $row['Name'] to create a name you can parse later
<h3>Column name: </h3><input type="text" name="name" maxlength="30"
value="' . $row['ID'] . '_' . $row['Name'] . '" />
then you can use something like:
list($name, $id) = explode($_POST['name'], '_');
** also note you have a security risk using user input directly inside SQL statement