Writing single page logging tool in php - 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']) . " ;");

Related

Using the result of a select clause for a where clause to MySQL

I have a MySQL database containing 12 columns. I created a dropdown from it using distinct values of the column named 'activity' and the column named 'logdate' which is a datetime.
Like this..
<form action="define_activity" id="activityform" method="post"> <!-- Form to select an activity -->
<select name="activities" id="select1"> <!-- List of activities -->
<option value="" selected="">Select One</option>
<option value="NewActivity" id="newactivity" onclick="newactivity();">New Activity</option>
<?php
foreach($db_found->query("SELECT DISTINCT activity, logdate FROM NetLog ORDER BY activity") as $act) {
echo ("<option value='$act[activity]'>$act[activity] of $act[logdate]</option>");
}
?>
</select>
<input type="submit" name = "Submit" />
</form>
This all works great. what I want to do is use the results of the selected option to do another query against the same database that pulls all of the records associated with the selected activity and logdate values. I know how to write the query but I don't know how to find and then use the selected values.
Can someone please show me how to get the selected value from the
Thanks in advance for your consideration.
I make some changes in your code, I didn't test it, but I think that's going to help you:
<?php
//Returns an associative array with the query result:
function select($yourSQLQuery){
//Array with result:
$result = array();
//Database conection
$db = new PDO($dsn,$username,$password);
$stmt = $db->query($yourSQLQuery);
//This going to save an array with your data:
$result = $stmt->fetchAll(PDO::FETCH_NUM);
$db = null;
return $result;
}
//*********************************************************************************************
//Do here your query:
$result = select("SELECT DISTINCT activity, logdate FROM NetLog ORDER BY activity");
//*********************************************************************************************
//Form handler:
if($_SERVER[REQUEST_METHOD] == "POST"){
//If the form was submited:
//Get selected activity
if ( isset($_POST['activities']) ) {
/*Instead of sending your activity you can send the number of the submitted record in $records, then extract activity and logdate and make your query:*/
$rowNumber = $_POST['activities'];
//Get your log date:
$act = $result[$rowNumber]; //if doesn't work try '$rowNumber'
$activity = $act['activity'];
$logdate = $act['logdate'];
//Pull records asocciated with submitted activity:
$sql = "SELECT * FROM putHereYourTable WHERE activity = '$activity' AND logdate='$logdate'";
$records = select($sql);
//Pulled activities are now in $records
//do something with the records that you want. e.g.:
print_r($records);
}
}
?>
<!-- Your HTML: -->
<form action="define_activity" id="activityform" method="post"> <!-- Form to select an activity -->
<select name="activities" id="select1"> <!-- List of activities -->
<option value="" selected="">Select One</option>
<option value="NewActivity" id="newactivity" onclick="newactivity();">New Activity</option>
<?php
foreach($result as $key => $act) {
//Send the number of register instead of $act[activity]:
echo ("<option value='$key'>$act[activity] of $act[logdate]</option>");
}
?>
</select>
<input type="submit" name = "Submit" />
</form>
You need to submit the form first.
<form action="define_activity" id="activityform" method="post">
You need to submit to a valid page in your action param. So if 'define_activity' is not a valid URL (ie: not handled by htaccess) then you need to either A) use the same script/file your using or B) create another page to handle the data.
I would do this:
<form action="process.php" id="activityform" method="post">
process.php
<?php
if ( isset($_POST['activities']) ) {
// do something with the submitted data
$selectedValue = $_POST['activities'];
}
Now you have the selected value. You have also any other value that is submitted in the form, $_POST['othervalue'].
For a clear view of what is sent, dump it.
die('<pre>' . print_r($_POST, true) . '</pre>');
or you could use var_dump: die( var_dump($_POST) );
Keith,
You have to remember that web applications work in a client server environment over the HTTP protocol.
After your page is done loading the first time, the php script is basically done executing. In order for more code to run, another request needs to be sent to the server. This happens when you either:
a) submit a form or click a link that sends a new http request to the page
b) make some javascript send a new HTTP request to the page.
Since you're just getting started, lets assume you just want that form to send the new request off to the page.
So at the top of your php script, just add this statement:
print_r($_REQUEST);
As you visit the page that is running the script both with and without clicking the submit post button, you will be able to see the various request parameters show up based on your form post. One of those params will be 'activity' .. just throw an if statement checking to see if that parameter is present, then run your query inside that if statement, using the value of 'activity'
if(isset($_REQUEST['activities'])) {
//do your query here..
}

Trying to copy data to a table with checkboxes, a form, and php

My webpage is pulling data from two tables - applications and archiveapps - and displays them using the following:
$sql = "SELECT * FROM applications";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Lots of info, including some html thrown in for style."
I want users to be able to click a checkbox listed next to each row and then hit an "Archive Selections" button that then moves all the selected entries from the applications table to the archiveapps one.
So far I've tried a form with it's code half in the echo above (so that a checkbox would go by each listed row from the $sql query) with the submit button outside (so that there would only be one "Archive Selections" button) but I'm sure this isn't proper syntax.
To actually move the data, I had this for the checkbox:
<form method='post' action=''><input type='checkbox' name='archname' value=".$row["charname"].">
(The above was inside an echo statement, so I assume it was able to pull the $row["charname"] no problem, but am unsure how to verify that.)
A little further down the page is the submit button and </form>.
And then I've got the function I want it to run when the submit button is clicked, to check if boxes have been selected and copy them into the archiveapps table. I'm sure there's something I'm missing here, probably in referencing what exactly is selected, and then copying that row's data to the other table... but honestly I just don't know enough about php to know what I'm missing.
if(!empty($_POST['archname'])) {
foreach($_POST['archname'] as $check) {
function archiveapp() {
$sqli="INSERT INTO archiveapps SELECT * FROM applications";
if ($conn->query($sqli) === TRUE) {
echo "<i>Archived</i>";
} else {
echo "Error: " . $sqli . "<br>" . $conn->error;
}}}}
Most of this has just been gathered from google searches and kind of mushed together, so I'm sure there are a lot of things done wrong. Any pointers or advice would be greatly appreciated!
Oh and my end goal is to copy the data to the archiveapps table and then delete it from the applications table, but for now I've just been focusing on the copying part, since I assume deleting a row will be fairly simple? Either way it's not the priority for this question.
Thanks in advance for any help!
Use a tool like FireBug to see what you are actually posting to server. You have multiple checkboxes with the same name, so you are sending only 1 value (the last checked, I think).
You need to send all of them, so use brackets after the name:
<!-- this is just an example -->
<input type="checkbox" name="archname[]" value="1">
<input type="checkbox" name="archname[]" value="2" checked>
<input type="checkbox" name="archname[]" value="3" checked>
Then on PHP, inside $_POST['archname'] you will get this:
Array(2, 3)
After this, you can do a foreach(...) loop like you are already doing, inserting only the ID you get from the $_POST variable:
foreach($_POST['archname'] as $id){
$sqli = "INSERT INTO archiveapps (id) VALUES (".(int)$id.")";
}

Having variable values shown in a textbox in php using sql

I am trying to have a variable from one .php document to display in a textbox in another. In the process, the value of the variable is going back to a database to grab information relating to the variable.
To be more specific, the user selects a StudentID from a dynamically populated drop down box on the first form, then is taken to another form where the selected StudentID is shown in the first textbox, and other data (such as email address, phone no.) are shown in different textboxes underneath. This then allows the user to modify the data shown and save it back to the database.
The reason I am running into problems is the variable value is originally coming from a dynamically populated drop down box. From what I have tried, I do not think the variable is being passed to the second form. This is because I have tried different variations of code to get the data to show in the textboxes and nothing shows each time.
Here is the code from the drop down box:
$query="SELECT StudentID FROM Personal_Details";
$result = mysql_query ($query);
echo '<select name= "StudentID">';
//Printing the list box select command
while($nt=mysql_fetch_array($result)){ /*Array or records stored in $nt*/
echo "<option value=$nt[StudentID]>$nt[StudentID]</option>";
/*Option values are added by looping through the array*/
}
echo "</select>"; //Closing of lost box
?>
Being new to this, I am assuming the variable is "StudentID".
If this is the case, this is the code used on the second .php document to get the value of the varaible to display in a textbox, along with the other data:
$query=mysql_query("SELECT Email, Phone FROM Personal_Details WHERE StudentID = '$StudentID'") or die(mysql_error());
while ($row = mysql_fetch_row($query)) {
$email = $row[1];
$phone = $row[2];
}
?>
(There are some html code here to set up the form. I skipped over that and went straight to the code relating to the problem)
<form name="modstudent" method="post" action="modstudent2.php">
Student ID: <input name="StudentID" type="text" value="<?php printf("%s",$StudentID);?>"><br>
Email: <input name="email" type="text" value="<?php printf("%s",$email);?>"><br>
Phone: <input name="phone" type="text" value="<?php printf("%s",$phone);?>"><br>
Any help will be greatly appreciated. Thanks in advance.
UPDATE
The problem seems to be the variable from the first page not being passed over to the second page. To make sure it was a variable problem, a fixed value was substituted into the code below:
$query=mysql_query("SELECT Email, Phone FROM Personal_Details WHERE StudentID = '/StudentID-here/'") or die(mysql_error());
What needs to change so the variable can be passed over? Thanks in advance.
echo "<option value=".$nt[StudentID].">".$nt[StudentID]."</option>"; or use <option value=echo($nt[StudentID])>echo($nt[StudentID])</option>;

Passing value from a dropdown list from one php to another

I have
A dropdown list populated from a MySQL table.
A button.
Another php page
What I need to do:
On clicking the button, pass the value selected from the dropdown list as a variable to second php page.
Pass that variable into a mysql query on the second php page. eg: $result = mysql_query("Select * from table where name like "$drop_down_value");
I am new to php and pardon my naivety.
This is my code to get values for the dropdown list:
function dropdown_query()
{
mysql_connect("localhost","root","root") or die("Failed to connect with database!!!!");
mysql_select_db("student_test") or die("cannot select DB");
$result = mysql_query("Select * from marks");
if($result=== FALSE){
die(mysql_error());
}
while($r=mysql_fetch_array($result))
{
echo '<option value="' .$r['marks'] . '">' . $r['marks'] . '</option>';
}
and this is my HTML part:
select name="dropdown" onchange="somefunc()">
<option value="">Select...</option>
<?php dropdown_query()?>
</select>
Lets say I use a similar query on another php. But would use the value selected on this page as a variable in that query.
By wrapping the drop down in a form with POST method, you can send the value to the next page and retrieve via $_POST['your_field_name']. See the docs.
Your page1 will have a form something like
<form action="page2.php" method="post">
<p>Name: <input type="text" name="name" /></p>
<p><input type="submit" /></p>
</form>
And in page2.php you can do something along the lines of
$name = $_POST['name'];
$sql = "SELECT * FROM table WHERE name LIKE '$name'";
...
(But make sure to scrub the user input before using it on page2.php!)
you will need javascript to do this. The page already finish loading. php script wont work after page finish loading. try jquery, ez to use
The answer to your question is to use the $_POST or $_GET superglobal variables in PHP. You can use either of these to obtain the value of the dropdown list from the first page after the button is clicked. For example, you could use the following code to obtain the value of the dropdown list:
$drop_down_value = $_POST['dropdown'];
Then, you can pass this variable into your MySQL query on the second page, as you have outlined in your question:
$result = mysql_query("Select * from table where name like "$drop_down_value");

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