I am totally stuck here and found tens of samples on posting to get and set values. What I am trying to do is -
Let a user enter a vehicles year model into a textbox in my form (set to post)
I then need to get this value to a variable state
$vehicle_year = $_GET['vyear'];
First error is here... vyear is the name and id for my textbox. Error - Undefined index 'vyear'. There is no submission of the form etc, because I am still on the same form/page.
With this value captured, I then search my database to return all of the manufacturers that has a year (as returned) attached to it -
$query = "SELECT * FROM `vehicledata` WHERE `year`='$vehicle_year'";
Obviously it does not work because I still do not have the value as yet returned from above with the undefined error. I've tried to change the name and id of the textbox, no luck.
Once these records has been returned, I need to add the values to a select (drop down) box. I have no idea how to get the values in there - seems I need to run a loop, which I know how to, just don't know how to add the options to the select box.
Please note that my form is NOT submitted, I need to load all the relevant data first before it gets submitted.
Any help will be appreciated, thanx guys.
P.S. I will add against sql injection once I know how to get the values and add the options. Just need the basics to get me going.
HTML:
//This would be my code...
Search Just my Wheels
Year
<?php
$vehicle_year = isset($_POST['vehicleyear']) ? $_POST['vehicleyear'] : -1;
if ($vehicle_year == -1) {
echo 'No Value Returned...';
//returns no value...
} else {
//How to get the value and echo it out...
echo $vehicle_year;
}
//$query = "SELECT * FROM (SELECT * FROM `vehicledata` WHERE `year`='$vehicle_year' ORDER BY `cid` DESC LIMIT 1, 10) AS `table` ORDER BY `cid` ASC";
$query = "SELECT * FROM `vehicledata` WHERE `year`='$vehicle_year'";
$result = mysql_query($query);
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
$vehicle_id = $line['cid'];
$vehicle_year = $line['year'];
$manufacturer = $line['carfindmake'];
//Get manufacturer data...
$images = get_make($vehicle_year);
if (!empty($make)) {
echo 'No data';
} else {
echo 'Found stuff';
}
}
?>
<td align="right"><span style="visibility:hidden" id="makelabel"><strong>Make</strong> </span></td>
<!--<td><input name="make" id="make" type="text" class="searchbox" style="visibility:hidden" onClick="toggleVisibility('modellabel'); toggleVisibility('model');"/></td>-->
<td><select name="make" id="make" class="searchbox" style="visibility:hidden" onClick="toggleVisibility('modellabel'); toggleVisibility('model');"/></td>
2) This is causing an error when your form has not yet been submitted because the value is not set.
Fix this by the following:
$vehicle_year = '';
if ( isset( $_POST['vyear'] ) ) {
$vehicle_year = $_POST['vyear'];
}
1 - If the form is set to POST, you've got to use $_POST["vyear"] to recover the value.
2 - Double check the case of the textbox's name.
my form (set to post)
$vehicle_year = $_GET['vyear'];
If your form is set to use POST, you'll need to access the form elements through the $_POST superglobal as such:
$vehicle_year = $_POST['vyear'];
If you're having issues because an index may or may not be set, use PHP's isset() to check. If the index isn't set, it won't cause an error.
if(isset($_POST['vyear'])) {
$vehicle_year = $_POST['vyear'];
}
Related
I'm writing a program to create an online forum and I am relatively new to php.
I have used a while loop to display all topics created for discussion in a table. This reads my sql database and echoes out just fine:
if ( mysqli_num_rows( $r ) >0 ) {
while ( $row = mysqli_fetch_array( $r, MYSQLI_ASSOC ) )
{
echo "<tr><th><p align = 'left'>"."Posted By ".$row['first_name']." " .$row['last_name']. " on ". $row['post_date']."<br/>";
echo "<p style = 'color:#2208A1', align='left'>"."Subject:". $row['subject']."<br/><br/>";
echo "Message: ". $row['message']."<br/>";
echo "ID Number = ". $row['post_id']."<br/>";
echo "<p style='color:red;' align = 'right'>"."<a href='http://localhost/FirstCswkAttempts/2017%20Web%20Scenario_A2/cwk_addreply.php?post_id =" .$row['post_id']." '>Reply to Post."."</a></p>";
"</tr></th>";
}
}
However,you can see that in the last line of code I try to concatenate the post_id number to the URL in the hope that I can use this information in another php file:
The code below shows my attempt to do just this. I use the GET method to capture post_id and insert it into another table in my database. If I use var_dump($_GET); I get an empty array. Where am I going wrong??
$q = "INSERT INTO responses(reply_owner, reply_text,reply_create_time,post_id)
VALUES (' ".$_POST['email']." ', ' ".$_POST["message"]."', now(),'".$_GET['post_id']."')";
$r = mysqli_query ( $dbc, $q
) ;
In response to comments, please find the form used to add posts to the topic:
<h1>Reply to Thread</h1>
<!--Display form-->
<form action="cwk_reply_action.php" method="post" accept-charset="utf-8">
<p><strong>Your email:<br><input name="email" type="text" size="55px" maxlength="100"></p>
<p>Message:<br><textarea name="message" rows="5" cols="50px"></textarea></strong></p>
<input type = "hidden" name = "post_id" value = "$_GET['post_id'] ">
<p><input name="submit" type="submit" value="Submit"></p></form>
This is a pretty common type of thing for a PHP application to do. The general pattern is:
Pull a list of items from a database and display them with links to interact with specific items.
When a link is clicked, display a form with the information of the selected item.
When the form is submitted, save the user input to the selected item.
The minimum you need to implement this pattern is the following:
Step 1 (display the items):
<?php
// using mysqli for example here, but the same general idea for pdo or any other
$result = mysqli_query('SELECT id, some_text, other_columns FROM your_table WHERE criteria');
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$id = htmlspecialchars($row['id']);
$text = htmlspecialchars($row['some_text']);
echo '' . $text . '<br>';
}
?>
Clicking a link (<a>) sends an HTTP GET request to the URL in its href parameter.
Step 2 (display the form):
When PHP handles the request, anything you have included in the query string of the URL (the ?id=x portion) will be availabe in the $_GET array.
There are two ways you can handle this piece of data so that it can be passed on to step 3. One way is to include it in the URL in the action parameter of your form:
<form action="url/to/submission_handler.php?id=<?php echo $_GET['id']; ?>" method="post">
Another way is to include a hidden form element that contains the ID.
<form action="url/to/submission_handler.php" method="post">
<input type="hidden" name="id" value="<?php echo $_GET['id']; ?>">
Step 3 (handle the form submission):
In this step, if you have passed the ID via the action parameter, it will be available in the $_GET array ($_GET['id']), and if you have passed it via an input on the form, it will be available in the $_POST array. ($_POST['id']).
Either way, you should be able to access it for use in your query.
<?php
$id = $_GET['id']; // or $_POST['id'], depending on which way you handled it on your form
// Using a prepared statement here for example rather than concatenating values into the
// SQL string, in order to reduce risk of SQL injection
// (Assuming $mysli is a connected mysqli object)
$stmt = $mysqli->prepare('UPDATE your_table SET ... WHERE id=?');
$stmt->bind_param("i", $id);
$stmt->execute();
?>
Either method of passing the id from your form to the script that handles its submission is perfectly valid, functional and commonly used. As far as I know, which way you should do it is really just determined by your own personal preference.
But you should note that passing parameters in the query string of the action paramater will only work for forms with method="post". If you ever need to use method="get" instead, only the values in the form fields will be available in $_GET; parameters in the query string will be ignored.
(For forms that will make changes on your server, (INSERT, UPDATE, or DELETE queries, writing to files, etc.) you should always be using method="post" anyway, but just FYI.)
If you want to print a variable you need it
<input type = "hidden" name = "post_id" value = "<?php echo $_GET['post_id']; ?> ">
And you will see the value of post_id
I believe you should be more specific however your code seems pretty rusty you need someone to tell you how its done what its your current uri on this script?
its it anything like that:http://localhost/forum.php?post_id=foobar
Are you send a POST or a GET request? what its your enctype?
if it is you can use the $_GET super global just fine just be careful inserting it on your querys, SQL injection still a big problem on this day.
<?php
if ( mysqli_num_rows( $response ) >0 ) {
while ( $row = mysqli_fetch_array( $response, MYSQLI_ASSOC ) )
{
echo "<tr>
<th>
<p align = 'left'> Posted By {$row['first_name']} {$row['last_name']} on {$row['post_date']} <br/>
<p style = 'color:#2208A1', align='left'>
Subject: {$row['subject']} <br/><br/> Message: {$row['message']} <br/>
ID Number = {$row['post_id'] }<br/>
<p style='color:red;' align = 'right'>
<a href='http://localhost/FirstCswkAttempts/2017%20Web%20Scenario_A2/cwk_addreply.php?post_id ={$row['post_id']}'>Reply to Post.</a>
</p>
</tr>
</th>";
}
//This is not recomenended anymore
//But since you are not using PDO and prepared statments its not that bad
$email = mysql_real_escape_string($_POST['email']);
$message = mysql_real_escape_string($_POST["message"]);
$postId = mysql_real_escape_string($_GET['post_id']);
//never name your variables less then 4 chars $q = $query, $r = $response , $dbc = $databaseConnection
$query = "INSERT INTO responses( reply_owner, reply_text, reply_create_time, post_id ) VALUES ('$email', '$message', now(),'$postId')";
$response = mysqli_query ( $databaseConnection, $query );
I've been trying to:(i) make my form fields nonempty using php scripts and
(ii) calculate average of numerical form data inserted into an array and an element of the array could be empty. For instance, suppose the form is used to harvest students' scores, some student might not offer an optional subject. How to adapt the count() array function in this instance is my headache. I admit that some folks have posed questions that partially addressed it but some issues remain unsolved, hence this post.
In summary:(i) the code below executes even when some form fields are empty, against my wish.(ii) If I grant some form fields to be empty; the result of the average calculation is incorrect; also against my wish
Code:
<?php
$name = $_POST['candidate'];
$Eng_CA = $_POST['Eng_CA'];
$Eng_Ex = $_POST['Eng_Ex'];
$Math_CA = $_POST['Math_CA'];
$Math_Ex = $_POST['Math_Ex'];
$Comp_CA = $_POST['Comp_CA'];
$Comp_Ex = $_POST['Comp_Ex'];
$engSum = $Eng_CA + $Eng_Ex;
$mathSum = $Math_CA + $Math_Ex;
$compSum = $Comp_CA + $Comp_Ex;
$tot = array();
$tot[] = $engSum;
$tot[]= $mathSum;
$tot[] = $compSum;
$total = array_sum($tot);
$Average = $total/count($tot); // Average is incorrcet if some fields are empty
$notEmpty = array();
$notEmpty = array('$name', '$Eng_CA', '$Eng_Ex', '$Math_CA', '$Math_Ex', '$Comp_CA', '$Comp_Ex');
foreach ($notEmpty as $notEmp){ // this is not working; code executes anyway
HTML
<form action ='test_Code.php' method ='post'>
<table width ='600'>
<tr><td> Cand Name</td><td colspan ='2'><input type ='text' name = 'candidate' size = '60'></td></tr>
<th>Subject</th><th>CA</th><th>Exam</th>
<tr><td>Eng</td><td><input type ='text' name = 'Eng_CA'/></td><td><input type ='text' name = 'Eng_Ex'/></td></tr>
<tr><td>Math</td><td><input type ='text' name = 'Math_CA'/></td><td><input type ='text' name = 'Math_Ex'/></td></tr>
<tr><td>Computer</td><td><input type ='text' name = 'Comp_CA'/></td><td><input type ='text' name = 'Comp_Ex'/></td></tr>
if(empty($notEmp)){
echo"You have left some fields empty, fill them pls";
die();
}
}
echo"<table border ='1'>";
echo"<th>Candidate</th><th>Eng Ca</th><th>Eng Ex</th><th>Math Ca</th> <th>Math Ex</th> <th>Comp Ca</th><th>Comp ex</th><th>Total</th><th>Average</th>";
echo"<tr><td>";
echo $name ."</td><td>".$Eng_CA."</td><td>".$Eng_Ex."</td><td>".$Math_CA."</td><td>".$Math_Ex."</td><td>".$Comp_CA."</td><td>". $Comp_Ex."</td><td>".$total."</td><td>".$Average."</td></tr></table>";
?>
Your trying to do a not empty check in an odd way to me. What I would do personally is simply loop through your $_POST vars first. Check them if they are empty. If so die or error out. example:
<?php
if(!empty($_POST)): //this is how trigger the processes for any form
foreach($_POST as $k => $v):
if(empty($v)){
echo $k.' can not be blank.<br>';
$error .= '<div>'.$k.' can not be blank.</div>'; //here is another option...
}
endforeach;
//if you get here now do your averages or whatever you were wanting.
endif;
//anywhere else in your entire php page write this
if($error){echo $error; } //this is a basic check, if error is empty it will be false, if error is not empty above it will print out the fields that
?>
I have a little problem on database update activity.
Case study:
I created a form with PHP editing, and perform queries to retrieve the value of a record that wants to be updated. Excerpts of the script:
<?php
$row = mysql_fetch_assoc(mysql_query("SELECT id, field_1, field_2 FROM mytable WHERE id = $editid"));
?>
...
<form action="" method="post">
FIELD 1 <input type = "text" name = "f1v" value = "<? Php echo $ row ['field_1'];?>" />
FIELD 2 <input type = "text" name = "f2v" value = "<? Php echo $ row ['field_2'];?>" />
<input type="submit" />
</form>
....
// When the form posted
if ($_POST)
{
$f1v = $ _POST['f1v'];
$f2v = $ _POST['f2v'];
mysql_query("UPDATE mytable SET field_1 = '$f1v', field_2 = '$f2v' WHERE id = $editid") or die ();
// Redirect form
}
In this case I want when the form submited, there are activities to check whether there is a change in one or more fields values. Its logic approximately like this:
if ($ _POST)
{
// Compare
if the submitted value is different from the existing value in the record
{
Updated record
}
else
{
Do not update record
}
// Redirect form
}
Do you have any easy way to do it? Thank you for your help.
Don't bother checking. Just make sure the entry is valid and throw it in.
Keep two hidden fields with current values of the fields. After submitting the form check whether submitted values are different from the hidden field values.
I'm continuing to hack away at my newbie php/mySQL 'Invoicer' app.
I now have a form page in which I want to run one of two queries - either an INSERT or an UPDATE, depending on whether an ID is present. When present,
the ID is used to retrieve the record and pre-populate the form accordingly, which I have working. My problem now is that my conditional bits are
obviously not right because in either case when submitting the form the INSERT query is run, can't get the UPDATE to run, and I've exhausted my
understanding (and guess-ology).
I'd love to know why this ain't working, even if it's not the best approach, and I'm definitely open to suggestions to move the queries to a process.php,
etc. I'm also wondering if I should use 'if(isset($_GET['ID'])' to simply include one block or the other.
Many thanks in advance for any help or suggestions. (p.s. my intention is to overhaul for best practices/security once I've got the broad strokes wired up)
cheers, s
<?php
// CASE I: 'EDIT RECORD':
// If there's an ID ...
if (isset($_GET['ID']) && is_numeric($_GET['ID'])) {
$id = $_GET['ID'];
echo "<p class=\"status\"><strong>ID IS SET ... ergo we're editing/UPDATING an existing record</strong></p>";
// ... retrieve the record ....
$query = sprintf("SELECT * FROM Invoices WHERE ID = %s", $id);
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
// ... assign variables to pre-populate the form
$id = $row['ID'];
$invNumber = $row['invNumber'];
$invDate = $row['invDate'];
// [ snip: more variables > field data ]
// on submit: get the form values ...
// no worky: if (isset($_GET['ID']) && isset($_POST['submit'])) {
if (isset($_POST['submit'])) {
$invNumber = $_POST['invoice-number'];
$invDate = $_POST['invoice-date'];
$projNumber = $_POST['project-number'];
// [ snip: more variables > field data ]
// ... and UPDATE the db:
$qUpdate = "UPDATE Invoices SET invNumber='$invNumber', invDate='$invDate', projNumber='$projNumber', client='$client', task='$task', issueDate='$issueDate', subTotal='$subTotal', tax='$tax', invTotal='$invTotal', datePaid1='$datePaid1', datePaid2='$datePaid2', comments='$comments' WHERE ID='3'";
$result = mysql_query($qUpdate) or die(mysql_error());
if($result) {
echo "<p class=\"status\"><strong>SUCCESS: RECORD UPDATED!</strong></p>";
}
else die("DAMMIT JIM I'M A DOCTOR NOT A DB ADMIN!" . mysql_error());
} // CLOSE '(isset($_POST['submit']))
} // END CASE I: ID present
// CASE II: 'NEW RECORD'; query = INSERT
elseif (empty($_GET['ID'])) {
echo "<p class=\"status\"><strong>No ID ... ergo we're INSERTING a new record:</strong></p>";
// on submit: get the form values ...
if (isset($_POST['submit'])) {
$invNumber = $_POST['invoice-number'];
$invDate = $_POST['invoice-date'];
$projNumber = $_POST['project-number'];
// [ snip: more variables > field data ]
$qInsert = "INSERT INTO Invoices (invNumber,invDate,projNumber,client,task,issueDate,subTotal,tax,invTotal,datePaid1,datePaid2,comments)
VALUES('$invNumber','$invDate','$projNumber','$client','$task','$issueDate','$subTotal','$tax','$invTotal','$datePaid1','$datePaid2','$comments')";
$result = mysql_query($qInsert) or die(mysql_error());
if($result) {
echo "<p class=\"status\"><strong>SUCCESS: NEW RECORD INSERTED!</strong></p>";
}
else die("DAMMIT JIM I'M A DOCTOR NOT A DB ADMIN!" . mysql_error());
} // CLOSE '(isset($_POST['submit']))
} // END CASE II: No ID present
?>
and:
<form id="invoiceData" method="post" action="/html/form.php">
When you submit the form, you need to include the ID again, otherwise it is silently dropped off since you are posting to the hard-coded value /html/form.php (with ID removed). This will cause the empty($_GET['ID']) part to match and run, causing the INSERT. You can simply include the ID value back into the action of every form post like this:
<form
id="invoiceData"
method="post"
action="/html/form.php?ID=<?php echo $_GET['ID']; ?>"
>
This should work in both the cases of the UPDATE and the INSERT, because if there was no ID to begin with, this will render as /html/form.php?ID=, which will match the case of ID being empty, I believe. You may want to test this logic out for sure.
Hope this helps!
$_GET[ID] will be set if you pass it as a URL parameter. So if you change your <form> action to
<form id="invoiceData" method="post" action="/html/form.php?ID=12">
Where 12 is whatever ID you want, you should be getting the results you're wanting -- as long as you do have a <input type="hidden" name="submit" value="1" /> (value can be whatever) in your form somewhere as well.
I have inserted some check box values in mysql database using PHP
And in the below image i have fetch the values:
Now i need the o/p like the below image: The values which i inserted in the database should be checked
Hope now its clear.
Thanks in advance..
You should have a table of available options (in this case, something like a cities table), and then a user-to-cities look-up table. Then you can loop over the cities, but also fetch which cities the user has checked.
A sample, without knowing your database structure, would be as follows:
$uid = $_SESSION['user']['id']; // your logged in user's ID
$cities = array();
// get an array of cities
$sql = "SELECT id, name FROM cities";
$res = mysql_query($sql);
while ($row = mysql_fetch_object($res)) {
$cities[$row->id] = $row->name;
}
// get an array of cities user has checked
$sql = "SELECT DISTINCT city_id FROM users_cities WHERE user_id = '$uid'";
$res = mysql_query($sql);
while ($row = mysql_fetch_object($res)) {
$checked[] = $row->city_id;
}
// this would be templated in a real world situation
foreach ($cities as $id => $name) {
$checked = "";
// check box if user has selected this city
if (in_array($checked, $id)) {
$checked = 'checked="checked" ';
}
echo '<input type="checkbox" name="city[]" value="'.$id.'" '.$checked.'/>';
}
If I understand you question properly, the obvious and simplest approach is that you need to fetch records from database and when producing HTML [in a loop ot something similar] check if that value exists in array to results. You haven't given us any examples of your DB structure or code, so you must figure it our yourself how to do it.
Usually, you insert the values into the database. After inserting, you should have access to the same values again. It's not clear how you set up your script, so let's assume you redirect to another script.
What you need to do is retrieve the values for the checkboxes from your database again. Then you know which are selected. This can be used to determine if your checkbox need to be checked or not.
Note:
I assume here that the result of your query is an array with
the selected Ids as a value.
I assume here that your fields are stored in the result of
some query and is basically an array
with Field Id as key and Field Name
as Value.
E.g., something like this:
<?php
// Retrieve values from database.
$resultArray = ... some code ... ;
?>
<?php foreach ($field_types as $field_name => $field_value): ?>
<input type="checkbox" name="<?php echo $field_name; ?>" value="<?php echo $field_value ?>" <?php if (in_array($field_name, $resultArray)) { echo 'checked'; }/>
<?php endforeach; ?>
This results in a checkbox which is checked, if the field_name is inside the result array (with your already checked results). Otherwise they're just rendered as unchecked checkboxes. Hope this is clear enough.