Open a form by id - php

I would like to open a form using a PHP URL by id. The URL looks like this.
http://localhost/application/workordersystem/woformEditor.php?woid=4
And receiving the id into PostgreSQL like this.
if (isset($_GET['woid']))
{
$query = "SELECT * FROM orders WHERE woid='$woid'";
$result = pg_query($query) or die(pg_error());
$row = pg_fetch_assoc($result);
}
I need the forms input fields to be filled with database data by the id in the database. What am I missing?
<input type="text" name="status" id="status" value="<?php echo $row['status']; ?>" />

Try debugging like so
echo print_r($row);
Additionally, you might want to add a limit. Tell us what you get.
$query = "SELECT * FROM orders WHERE woid='$woid' LIMIT 1";
But you should review the data structure returned by pg_fetch_assoc($result);
You'll want to map the keys you need to the input fields which should be revealed (or anomalies revealed) via the print_r function.

Related

Taking a value from an array and storing it into a variable for a SQL search

Perhaps there may be an easier way to do this however, I need the project to select a patient from the drop down menu. Then when the dropdown menu has got a value, the text field needs to take the NHS number from that drop down menu (array) so that it can be posted elsewhere.
<select name="patient" class="textbox" required>
<option value="">Select a patient</option>
<?php
include 'dbconnection.php';
$sql = "SELECT * FROM clients ORDER by firstname ASC";
$result = mysqli_query($conn, $sql);
$result = $conn-> query($sql);
while($row=mysqli_fetch_array($result))
{
?>
<option value="<?php echo $row["firstname"]." ".$row["lastname"]; ?>">
<?php echo $row["firstname"]." ".$row["lastname"] .", ".$row["addressl1"].", ".$row["addressl2"].", ".$row["county"].", ".$row["postcode"].", ".$row["nhsnum"]; ?></option>
<?php
$nhs = $row['nhsnum'];
}
?>
</select>
<?php
$sql = "SELECT * FROM clients WHERE nhsnum = $nhs ";
$result = mysqli_query($conn, $sql);
$result = $conn-> query($sql);
while($row=mysqli_fetch_array($result))
{
?>
<input type="text" placeholder="NHS number" readonly value=" <?php echo $row["nhsnum"]; ?>">
<?php
}
?>
As you may see, I have created dummy variables of $nhs however its a static variable and doesnt change upon user selection from the drop down list. Can anyone explain how I can merge the two together.
DB setup
i think you should declare the $nhs outside the while loop
Use AJAX, as already suggested, or a form submit button. Your second query should be where your AJAX or submitted form goes. Use $_GET or $_POST, if you are using get or post method, to intercept the option value. Assign that value to your $nhs, then use as you have.
Set the option value to the $nhs value you want, not the person’s name. Example using $_POST
if(isset($_POST['patient'])){
$nhs=$_POST['patient'];
}else{
// whatever code you want to handle a non-submitted value.
}
Add additional code to prevent SQL injection.

While loop - Only one input from many others is sending a value through POST

This is the code where I get my input names and values from a table called optionale and doing something with these:
<form role="form" autocomplete="off" action="includes/functions/fisa-init.php" method="POST">
<?php
connectDB();
$query = mysqli_query($mysqli, "SELECT * FROM `optionale`") or die(mysqli_error($mysqli));
while($row = mysqli_fetch_array($query))
{
?>
<span><?php echo $row['denumire']; ?></span>
<input type="text" name="nrBucati">
<input type="hidden" value="<?php echo $row['cod']; ?>" name="codProdus">
<?php } ?>
</form>
The optionale table looks like this:
The HTML looks like this:
As you can see in the last picture, I have in HTML, a name for input (taken from optionale table) and the actual input in which I write a value.
fisa-init.php:
$stmt3 = $mysqli->prepare("
UPDATE
`stocuri`
SET
`cantitate` = `cantitate` - ?
WHERE `cod` = ?
");
$stmt3->bind_param("is", $bucata, $cod);
// set parameters and execute
$bucata = mysqli_real_escape_string($mysqli, $_POST['nrBucati']);
$cod = mysqli_real_escape_string($mysqli, $_POST['codProdus']);
if (!$stmt3->execute())
{
echo "Execuția a întâmpinat o eroare: (" . $stmt3->errno . ") " . $stmt3->error;
}
$stmt3->close();
$mysqli->close();
In the code above (fisa-init.php) I am trying to take all the input values from my HTML and update rows in another table called stocuri:
As you can see, only the second row from stocuri table was updated, but I wrote values in all 5 inputs. It got only the last input.
How to modify the while loop in order to take all my inputs value?
If something is not clear, I apologize a hundred times. I will explain all the informations that are needed.
P.S. cod in table optionale is the same with cod in table stocuri. In this way, I know where to update values.
Each <input> MUST have an individual name or a named array.
So give each an aditional number like name1,name2 or use an named array like name[]
Finally this name="codProdus[]" is your solution.
Read more here
HTML input arrays
Have a nice day

Writing single page logging tool in php

Im making a small php webpage which I plan to use to track on which subjects a helpdesk receives calls. My database has 3 important fields: id, name, and amount for each subject.
On my page I have a form with a dropdown list where you select a type of call and click submit. The idea is that every time you click submit the page reloads and the amount in the database for the chosen id is heightened by 1.
The form gives me the id and name for each call:
<form method="post" action="index.php">
<select class="select" id="calltype" name="calltype">
<?php
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<option value=".$row["ID"].">".$row["NAAM"]."</option>".PHP_EOL;
}
}
?>
</select></br>
<input class="input" type="submit" name="Submit" value="Submit">
</form>
This part works, if I echo $_POST['calltype'] I get the correct ID. What I can't get to work is the update statement which I want to heighten the counter, like:
if(isset($_POST['calltype']{
mysqli_query("UPDATE calls SET amount=(amount+1), WHERE id = $_POST['calltype']");
}
How would I go about this? I tried several methods but can't get it to work
besides for the extra comma, interpolation with the POST array like this is risky. maybe try:
mysqli_query("UPDATE calls SET amount=(amount+1) WHERE id = " . mysqli_real_escape_string($link, $_POST['calltype']) . " ;");

How to use the GET method in php to capture information needed for sql

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 );

HTML input value change

I have a PHP update page in which I am showing a text field containing a value from the database. It is like this, and it is working,
<input type="text" name="title" id="title" class="text_box" value="<?php echo $row['title']?>"/>
Now I need to put this updated value back in the database! I have used the code like this, but it's not updating:
$title=$_POST['title'];
$v_id = $_GET['v_id'];
$sql = mysql_query("update vehicles set title = '$title' where v_id = '$v_id'");
In detail... an input field is there. It's showing a value contained in $title (retrieved from the database) and that value is to be edited and updated.
From my side my code is working perfectly without showing any error, but the value that I give $title is giving the same one without any change.
Is there any other way to show a value in an input field without putting in a "value" tag?
Two things wants to happen in a single input field!
You'll need to post your form HTML as well.
Unless your form looks like the following, that code won't work
<form method='post' action='page.php?v_id=1'>
<input type="text" name="title" id="title" class="text_box" value="<?php echo $row['title']?>"/>
</form>
This is because you're using $_GET to get the id field and $_POST to get the value field
EDIT
Your edit has muddied the water a bit more. I'm going to assume all you want to do is show a title and let the user update the title
<?php
if ($_POST) {
$title = mysql_escape_string($_POST['title']);
$id = intval($_GET['v_id']);
$sql = "update vehicles set title = '$title' where v_id = '$id'";
mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
}
if (isset($_GET['v_id'])) {
$id = intval($_GET['v_id']);
$sql = 'SELECT title FROM vehicles WHERE v_id = ' . $id;
$rs = mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
$row = mysql_fetch_assoc($rs);
$title = htmlspecialchars($row['title']);
}
?>
<form method='post' action='?v_id=<?php echo $id?>'>
<input type="text" name="title" id="title" class="text_box" value="<?php echo $title ?>"/>
<input type='submit' value='update'>
</form>
This should work for you. I haven't error tested obviously, but the idea is sound. You should also add any other input screening you feel necessary.
You are using both $_POST and $_GET.
Depending on the method element value of <form>, you need either $_POST or $_GET.
If this is not helping, please show more code so it is possible to determine which one you need.
Also, you can try to update the database without reading the form, to check if the updating itself is working correctly.
is there any other way to showing a value in a input field without putting a "value" tag?
Nope.
That's exactly what value attribute for.
What's wrong with it?
only thing to mention, it should be not <?php echo $row['title']?> but
<?php echo htmlspecialchars($row['title'])?>

Categories