I have a form
<form action="inserir.php" method="POST">
<tr>
<td><INPUT type='checkbox' name='chk'/></td>
<td><input type='text' name='ppdata[$x]'/></td>
<td><input type='text' size='40' name='ppempresa[$x]'></td>
<td><input type='text' name='ppfuncao[$x]' size='40'></td>
</tr>`
</form>`
In my code, the user can insert more rows to the table, insert data and send it to a new file (insert.php)
foreach ($_POST["ppdata"] as $dat){
echo $dat. ' ';
}
foreach ($_POST["ppempresa"] as $empresa){
echo $empresa. ' ';
}
foreach ($_POST["ppfuncao"] as $funcao){
echo $funcao. ' ';
}
$data = count($dat);
$emp = count($empresa);
$func = count($funcao);
if($data == $emp){
for($x = 0; $x < $emp; $x++){
$str[] = "('{$dat[$x]}','{$empresa[$x]}','{$funcao[$x]}','{$id}')";
}
$s = implode(',',$str);
$sql = mysql_query("INSERT INTO pp (data,empresa,descricao,id_user) VALUES $s;");
}
The array i'm seng only saves one char per field.
if i do:
echo '$dat';
It'll echo the whole array.
If i do this:
echo '$dat[0]';
It'll only show the first letter of the string. If i write 'Hello' on the input, It will only show 'H'.
EDIT: I need to insert data in the database, depending on how much rows the user adds. but right now, the array only inserts the last letter of the last word of each field.
Let's look at what happens when you write "Hello".
The following POST array is sent:
$_POST = array(
"ppdata" => array(
"Hello"
)
);
Now, you run this:
foreach ($_POST["ppdata"] as $dat){
echo $dat. ' ';
}
At this point, $dat is equal to "Hello".
Notably, $dat is a string. This means that $dat[0] is the first character of the string, namely "H". That is how accessing a string as an array of characters works.
You probably meant to use $_POST['ppdata'] everywhere you used $dat (in count, in the loop etc.) as this is your array.
Related
In trying to set up a contact database I'm trying to use a multi word string to search a database of people to narrow down search results.
I have the following code. My problem is taking the result of my forms input string converted to an array and inserting it into the $sql SELECT coding so that it checks every word against every column. The reason for that is so when doing a search you can either type in 'Joe Bloggs New York' or 'New York Joe Bloggs' and get the same result.
<?php
// **My String collection and conversion to an array**
// Get Form String
$input = $_POST['input'];
// Split String into an Array
$input = preg_split("/[\\/\s,]+/", $input);
// Checking That We Now Have An Array
print_r($input);
// Loop Through Array Values
for ($i = 0; $i < count($input); $i++) {
// Checking Array Output
echo '<br />';
echo $input[$i];
echo '<br />';
}
// **My database query**
// Connect To Database
require_once("connect.php");
// Query The Database
$sql="SELECT * FROM contact WHERE name LIKE '%$input[$i]%' AND lastName LIKE '%$input[$i]%' AND area LIKE '%$input[$i]%' ORDER BY name";
if ($result=mysqli_query($con,$sql))
{
// Fetch one and one row
while ($row=mysqli_fetch_row($result))
{
echo "<h2><u>$row[1]</u></h2><br />";
echo "<img src='img/$row[5]' style='width:300px; height: auto;'/>";
echo "<h3>Name - $row[1] $row[2]</h3>";
echo "<h3>Phone - $row[3]</h3>";
echo "<h3>Email - $row[4]</h3>";
echo "<br /><br />";
}
// Free result set
mysqli_free_result($result);
} else {
echo "No Results";
}
// Close Database Connection
mysqli_close($con);
?>
<h1>Contacts</h1>
<form method="post" action="search.php">
<table>
<tr>
<td>
<input type="text" name="input" size="30" maxlength="50"/>
</td>
<td>
<input type="submit" name="SEARCH" value="Search"/>
</td>
</tr>
</table>
</form>
If I could please get help putting both pieces of code together so that it takes the string, converts it to an array and then only gives me a return from the database of Joe Bloggs's that live in New York I'd be very grateful.
You might try changing your ANDs to ORs in the query, otherwise you are querying for john john who lives in john...
Struggling with a one page form that i want to first populate a form from a mysql query, then enable a user to update some of the values in each of several table rows from text input fields in the form.
The code's intent is to update the field by referencing the row ID.
But for some reason I'm only able to update the last row in the form (the last row from the array). I've included some troubleshooting code to see what the ID variable is and it always comes up as the last iteration of the array. I think I'm either overwriting the ID variable in the while loop or the for loop.
I have tried moving the POST/update to a 2nd file but get the same results. Any thoughts/suggestions would be greatly appreciated
Here is the code minus the db connection:
$saveClicked = $_POST["saveClicked"];
{ // SAVE button was clicked
if (isset($saveClicked)) {
unset($saveClicked);
$ID = $_POST["ID"];
$win = $_POST["Winner"];
$winScr = $_POST["WinnerScore"];
$losScr = $_POST["LoserScore"];
$tschedule_SQLupdate = "UPDATE tschedule SET ";
$tschedule_SQLupdate .= "Winner = '".$win."', ";
$tschedule_SQLupdate .= "WinnerScore = '".$winScr."', ";
$tschedule_SQLupdate .= "LoserScore = '".$losScr."' ";
$tschedule_SQLupdate .= "WHERE ID = '".$ID."' ";
if (mysql_query($tschedule_SQLupdate)) {
echo '<p> the number of mysql affected rows is '.mysql_affected_rows().'</p>';
echo 'this is the value for post id '.$ID;
} else {
echo '<span style="color:red; ">FAILED to update the game.</span><br /><br />';
echo mysql_error();
}
}
// END: SAVE button was clicked ie. if (isset($saveClicked))
}
{ // Get the details of all associated schedule records
// and store in array: gameArray with key >$indx
$indx = 0;
$tschedule_SQLselect = "SELECT * ";
$tschedule_SQLselect .= "FROM ";
$tschedule_SQLselect .= "tschedule ";
$tschedule_SQLselect .= "WHERE week = 1 ";
$tschedule_SQLselect_Query = mysql_query($tschedule_SQLselect);
while ($row = mysql_fetch_array($tschedule_SQLselect_Query, MYSQL_ASSOC)) {
$gameArray[$indx]['ID'] = $row['ID'];
$gameArray[$indx]['Date'] = $row['Date'];
$gameArray[$indx]['week'] = $row['week'];
$gameArray[$indx]['Favorite'] = $row['Favorite'];
$gameArray[$indx]['Line'] = $row['Line'];
$gameArray[$indx]['Underdog'] = $row['Underdog'];
$gameArray[$indx]['OU'] = $row['OU'];
$gameArray[$indx]['Winner'] = $row['Winner'];
$gameArray[$indx]['WinnerScore'] = $row['WinnerScore'];
$gameArray[$indx]['LoserScore'] = $row['LoserScore'];
$indx++;
}
$numGames = sizeof($gameArray);
mysql_free_result($tschedule_SQLselect_Query);
}
{ // Output
echo '<form name ="postGame" action="'.$thisScriptName.'" method="post">';
echo '<table border="1">';
echo '<tr>
<th>ID</th>
<th class="date">Date</th>
<th class="num">Week</th>
<th>Favorite</th>
<th class="num">Line</th>
<th>Underdog</th>
<th class="num">OU</th>
<th>Winner</th>
<th>WScore</th>
<th>LScore</th>
<th>Save</th>
</tr> ';
for ($indx = 0; $indx < $numGames; $indx++) {
$thisID = $gameArray[$indx]['ID'];
$saveLink = '<input type = "submit" value = "Save" />';
$fld_ID = '<input type="text" name="ID" value="'.$thisID.'"/>';
$fld_saveClicked = '<input type="hidden" name="saveClicked" value="1"/>';
echo $fld_ID;
echo $fld_saveClicked;
echo '<tr>
<td>'.$gameArray[$indx]['ID'].'</td>
<td>'.$gameArray[$indx]['Date'].'</td>
<td>'.$gameArray[$indx]['week'].'</td>
<td>'.$gameArray[$indx]['Favorite'].'</td>
<td>'.$gameArray[$indx]['Line'].'</td>
<td>'.$gameArray[$indx]['Underdog'].'</td>
<td>'.$gameArray[$indx]['OU'].'</td>
<td><input type="text" size =5 name="Winner">'.$gameArray[$indx]['Winner'].'</td>
<td><input type="number" size=5 name="WinnerScore">'.$gameArray[$indx]['WinnerScore'].'</td>
<td><input type="number" size=5 name="LoserScore">'.$gameArray[$indx]['LoserScore'].'</td>
<td>'.$saveLink.'</td>
</tr> ';
}
echo '</table>';
echo '</form>';
echo' View Schedule';
}
You're using the same names for each field in each row, so when you post the form, only the last is accessible. Use array notation for the fields like this:
<input type="text" size =5 name="Winner[]">
^^
This will give you an array for $_POST['Winner'] instead of a single value. Do the same for the other <input> elements.
Also, the code that processes the form after it's submitted only processes one value. You'll need to modify that to loop through these arrays.
Warnings:
don't use mysql_*() for new code - it's depracated. Switch to mysqli_*() or PDO now.
Your code is susceptible to SQL injection. Escape your input variables with mysql_real_escape_string() (or the mysqli equivalent) or better, switch to prepared statements.
After some more research I think I understand the two answers already shared much better. However I have chosen a different path and have resolved my issue -I wrapped the form tags directly around each row:
echo '<form name ="postGame'.$indx.'" action="'.$thisScriptName.'" method="POST">';
$fld_saveClicked = '<input type="hidden" name="saveClicked" value="1"/>';
echo $fld_saveClicked;
$fld_ID = '<input type="text" name="ID" value="'.$thisID.'"/>';
echo $fld_ID;
echo '<tr>
<td>'.$gameArray[$indx]['ID'].'</td>
<td>'.$gameArray[$indx]['Date'].'</td>
<td>'.$gameArray[$indx]['week'].'</td>
<td>'.$gameArray[$indx]['Favorite'].'</td>
<td>'.$gameArray[$indx]['Line'].'</td>
<td>'.$gameArray[$indx]['Underdog'].'</td>
<td>'.$gameArray[$indx]['OU'].'</td>
<td><input type="text" size=5 name="Winner" id="Winner">'.$gameArray[$indx]['Winner'].'</td>
<td><input type="number" size=5 name="WinnerScore" id="WinnerScore">'.$gameArray[$indx]['WinnerScore'].'</td>
<td><input type="number" size=5 name="LoserScore" id="LoserScore">'.$gameArray[$indx]['LoserScore'].'</td>
<td><button type="submit" />Save</button></td>
</tr></form>';
}
One of the key trouble shooting steps was to use var_dump to validate that the $_POST actually contained data. I understand there are several ways this could be done including the responses shared by Hobo and Syed, as well as using javascript, but was really glad I could accomplish my goal with just php.
Your For Loop is storing the last value of the array in your form.
$fld_ID = '<input type="text" name="ID" value="'.$thisID.'"/>';
Store the ID value as an array in HTML form and when a form is posted get all the ID values and update using your same mysql update query.
Your winner and loser score are also returning the last array values.
So lately i have been working on a way to post values from a database through checkbox selecting. Thanks to a previous question: How to use checkboxes to retrieve specific data in a database, i managed to get it working!
Although i got it working, i wanted to make my queries a bit more effective when multiple checkboxes are selected instead of writing queries with if/else for every checkbox possibility.
Through some research on stack overflow, this topic in particular: Run a query based on multiple checkboxes, i created the code for my own project. Though, for some reason it just wont output the data correctly, it even wont output anything at all.
So i looked in my code to see where stuff goes wrong. I passed in several echo's to get array information etc, but it all seems ok EXCEPT the last echo where i am echoing the query results (which returns 0).
So i am kinda stuck now since i cant figure out what goes wrong.
NOTE: It is for wordpress so that explains the little difference in querying.*
The code is as follows:
The HTML Code to display the checkboxes
<form method="post">
<div id="list1" class="dropdown-check-list">
<span class="anchor">Select Authors</span>
<ul class="items">
<li><input type="checkbox" name="columns[]" value="Barry" />Barry</li>
<li><input type="checkbox" name="columns[]" value="Henk" />Henk</li>
<li><input type="checkbox" name="columns[]" value="Nicolas" />Nicolas</li>
</ul>
</div>
<input type="submit" name="go" value="Submit"/>
</form>
The ID is for a Jquery dropdown effect.
The PHP code is as follows:
*The code below defines the column titles that are being displayed/echo'd in a table
$column_names = array(
"Authorss" => "Authorss",
"Research_Source" => "Research_Source",
"Research_Title" => "Research_Title"
);
$sql_columns = array();
foreach($column_names as $i) {
$sql_columns[] = $column_names[$i];
}
The next lines of code checks the checked checkbox values and queries the selected values:
if(!empty($_POST['columns'])) { // empty() checks if the value is set before checking if it's empty.
foreach($_POST['columns'] as $key=>$value){
// Runs mysql_real_escape_string() on every value encountered.
$clean_criteria = array_map('mysql_real_escape_string', $_REQUEST['columns']);
// Convert the array into a string.
$criteria = implode("','", $clean_criteria);
}
$tmp = $wpdb->get_results("
SELECT"
.implode(",", $sql_columns)."
FROM
wp_participants_database
WHERE
authorss IN ($criteria)
ORDER BY
authorss ASC
");
}
If non is selected the query selects all possible results (this still has to be created tho since i want the specific select query to work first):
else {
echo 'still needs to be edit to show everything here';
//$tmp = $wpdb->get_results( "SELECT ".implode(",", $sql_columns)." FROM wp_participants_database;");
}
Now comes the part where the queried data is being showed/put in tables:
echo "<table>
<tr>";
foreach($column_names as $k => $v) {
echo "<th>$v</th>";
}
echo "</tr>";
if(count($tmp)>0){
for($i=0;$i<count($tmp);$i++){
echo "<tr>";
foreach($tmp[$i] as $key=>$value){
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
}
echo '</table>';
*****UPDATE*****
Got it fixed myself! First i deleted:
$column_names = array(
"Authorss" => "Authorss",
"Research_Source" => "Research_Source",
"Research_Title" => "Research_Title"
);
$sql_columns = array();
foreach($column_names as $i) {
$sql_columns[] = $column_names[$i];
}
This above code was unnecessary as the columns were all preset, so i just echo'd them by typing them out.
The problem was the following:
$tmp = $wpdb->get_results("
SELECT"
.implode(",", $sql_columns)."
FROM
wp_participants_database
WHERE
authorss IN ($criteria)
ORDER BY
authorss ASC
");
The $criteria variable should give a string to the IN, though in my code it was parsed as an literal (so no string). It seemed very easy, i just had to add the '' so it would be parsed as a string. Result: WHERE authorss IN ('$criteria')
<div>
<?php
$corpServicesValue = $row['corp_services'];
$value= explode(",",$corpServicesValue);
if(in_array("1",$value))echo '<input type="checkbox" name="corporationServices[]" value="1" checked >Management<br>';
?>
</div>
I try to pass a form which contains other forms (same inside forms, dynamic) , but I have checked that the data which are sent to the 'script handler' (php) are incomplete data. I think somewhere buffer is overwriting or something. Here is the code :
<?php
if(isset($_POST['submit_num']))
{
$number=$_POST['sky'];
if($number== 0)
{
header('Location: /ceid_coffee/user_order_form.php');
}
else
{
$_SESSION['number'] = $number;
echo '<form action="user_order_form.php" method="POST">';
for($i=0;$i<$number;$i++)
{
$item = $_SESSION['item'];
echo $item;
$rec_query = "SELECT * FROM ylika";
$rec_result= mysql_query($rec_query) or die("my eroors");
while($row_rec = mysql_fetch_array($rec_result))
{
echo '<br>';
echo '<input type="checkbox" name="yliko[][$i]" value='.$row_rec['onoma'].'> '.$row_rec['onoma'].'';//<~~~~this line is form's data
}
echo '<br>';
}
echo '<input type="submit" name="submit" value="FINAL_ORDER">';
echo '</form>';
}
}
?>
And this is the handling script:
<?php
if (isset($_POST['submit']))
{
$number= $_SESSION['number'];
$item = $_SESSION['item'];
$max_id = "SELECT MAX(id_order) FROM id_of_orders";
$x=mysql_query($max_id) or die("my eroors");
$id= mysql_fetch_array($x);
$xyz = $id['MAX(id_order)'];
for($i=0;$i<$number;$i++)
{
$temp = $_POST['yliko'][$i]; // <~~~~ this line is the form's data
$temp2 = implode("," , $temp);
$inserts = ("INSERT INTO orders (order_id,product,ulika) VALUES ('$xyz' , '$item','$temp2')");
$inc_prod=("UPDATE proion SET Counter = Counter + 1 WHERE proion.onomasia='$item'");
mysql_query($inserts) or die(mysql_error());
mysql_query($inc_prod) or die(mysql_error());
}
}
?>
This line here contains the data of each form , but i have echo them ($temp2) and i saw that they are incomplete.
$temp = $_POST['yliko'][$i];
If i select more than 1 checkbox for each item ($i) I get only one value from the checkboxes into the sql.
Do you see if I miss something ?
Ok i found the error. I replace this row :
echo '<input type="checkbox" name="yliko[][$i]" value='.$row_rec['onoma'].'> '.$row_rec['onoma'].'';//<~~~~this line is form's data
with this row :
echo '<input type="checkbox" name="yliko['.$i.'][]" value='.$row_rec['onoma'].'> '.$row_rec['onoma'].'';
I do not know how (i'm new to php) but it worked.
You will only get one value for each form because you are assigning the value of $i to each one:
echo '<input type="checkbox" name="yliko[][$i]" value='. etc.
is your problem line.
Have a look at the HTML that your code produces (ctrl-u in most browsers) and you will see why you get the wrong answer. All your checkboxes need to have unique names.
I would do it by assigning each checkbox a name that relates to the line in the database from which they are drawn eg:
name="checkbox_"'.$row['ylikaprimarykey']."etc.
This will get you up and running fairly quickly. For what it is worth, the ids of your table keys can give attackers information about your site so it is best practice to obfuscate them in some way. There are a number of excellent classes available free on the net that will do this for you.
If you really need to deal with what would have been in each form as a separate chunk of data, you can easily change the checkbox names vis:
name="checkbox_$formnumber_$obfuscatedkeynumber"
then loop through them with nested loops in your handling page.
So I have a mysql table for the charges of a hospital. My program currently only gets the price of the checked procedure. But now, I also want to get the procedure name when it is checked.
transaction.php
while($row = mysql_fetch_array($result))
{
echo ' <tr> <td>'.$row[0].'</td> <td>'.$row[1].'</td><td>'.$row[2].'</td>';
$procedure=$row['procedure'];
echo '<td><input type="checkbox" name="er[]" value="$price."|".$procedure"></td>';
echo "</tr>";
}
echo '</table>';
computation.php
<?php
if(isset($_POST['er']))
{
$ercharge=$_POST['er'];
$totalofer = array_sum($ercharge);
}
if(isset($_POST['ultrasound']))
{
$x=$_POST['ultrasound'];
$totalofultrasound = array_sum($x);
}
if(isset($_POST['confinement']))
{
$y=$_POST['confinement'];
$totalofconfinement = array_sum($y);
}
$total = $totalofer + $totalofultrasound + $totalofconfinement;
$p = explode("|", $ercharge);
echo $p;
echo $total;
?>
It only gets the row for price. Can the value attribute have two values? I can't just make another checkbox cause that would be inappropriate.
edit: the explode function doesnt work. It says: Warning: explode() expects parameter 2 to be string, array given in C:\xampp\htdocs\computation.php on line 18
You should split your parameters in the HTML:
echo '<td><input type="checkbox" name="checked[$row_index][]" value="1">';
echo '<input type="hidden" name="prices[$row_index][]" value="$price">';
echo '<input type="hidden" name="procedures[$row_index][]" value="$procedure"></td>';
where $row_index is incremented on each row (tr tag)
By the way, explode will work on the items of the er array, not on the array itself. Try:
foreach ($er as $item) {
var_dump( explode( "|", $item ) );
}
I'm not sure I understand your question but couldn't you set the name attrtibute for your checkbox to the name of the procedure? It looks like you are setting the name to the er[] array but you never reference that later.