I am developing a php/mysql system.
I have a table juncfees which has the fields - juncid, matterid, staffid, fee. The fee stores to hourly rate to be charged for a matter.
The matterid refers to a matter table and staffid refers to a staff table but I don’t think that is relevant for what I want to achieve.
Every year the fees will be subject to an annual rise and what I want to be able to do is to have a page that will enable an admin to do this without involving me. In the past I have changed the values using code such as UPDATE juncfees SET fee=’45’ WHERE staffid=‘5’; This works fine but I would rather others could do it without direct database access.
I was imagining a page where there was a dropdown list of staff to give me the staffid and a box where the new fee could be entered then a button which, once clicked, would update all of the relevant data.
Is this possible and, if so, how do I go about doing it? (Of course, if there’s a better way then I am happy to follow that route.)
Many thanks
Here is an adapted sample from w3.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE juncfees SET fee='".$_POST['fee']."' WHERE staffid='".$_POST['staffid']."'";
if ($conn->query($sql) === TRUE) {
echo "Records updated successfully";
} else {
echo "Error updating records: " . $conn->error;
}
$conn->close();
?>
The HTML is just a simple form:
<form action="update.php" method="post">
StaffID: <input type=text name=staffid><br>
Fee: <input type=text name=fee><br>
<input type=submit>
</form>
HTML form is just an example, actually any markup or language which can post http data can trigger the PHP code (which is pretty much all of them). So if you want to create a desktop application to do this that would be quite easy as well.
using System.Net;
function postData(float fee, int id)
{
var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/update.php");
var postData = "fee="+fee;
postData += "&staffid="+id;
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
}
Keep in mind, this is just the most basic of example and has no protection as far as user access or from SQL injection.
Related
I want to set a url parameter by using uniqid function in php, I get the unique numbers and place them in my database by useing them in a hidden input form. I try to make it so, at the start of the script $number is set to a uniqid which I placed in the hidden input so it will be posted into the database and I can use the same variable to create a href link.
The problem I'm having is that the value stored in my database is not the same as the value stored in the number variable used in the href link which renders the link useless. How do I get both the values equal is there a better way to do what I'm trying to do?
I have tried putting uniqid() in a function
<?php
$servername = "localhost";
$username = "root";
$password = "";
$homeDB = "homeDB";
$conn = new mysqli($servername, $username, $password, $homeDB);
if($conn->connect_error) {
die("failed to connect to server".$conn->connect_error);
}
$number = uniqid();
if(isset($_POST["namn"])) {
$sql = "INSERT INTO information (firstname, lastname, urlID)
VALUES ('".$_POST["namn"]."','".$_POST["efternamn"]."',
'".$_POST["hide"]."')";
if($conn->query($sql)== TRUE){
$link = "http://localhost/sqltutorial/execute.php?id=".$number;
} else {
echo "failed";
}
echo $link;
}
html
<html>
<body>
<form method="post" action="home.php">
<input type="text" name="namn"> <br>
<input type="text" name= "efternamn"><br>
<input type="hidden" value="<?php $number ?>" name="hide">
<input type="submit" >
</form>
<br>
</body>
</html>
I get different values on the link that is echoed and the value stored in my database ( I know this form is not secure )
I think you just need to use the $_POST['hide'] value on the link.
It would also be better to echo the link only if it has been created.
Where you have the echo currently, it is possible to echo the $link variable even if it was not been created!
<?php
$servername = "localhost";
$username = "root";
$password = "";
$homeDB = "homeDB";
$conn = new mysqli($servername, $username, $password, $homeDB);
if($conn->connect_error) {
die("failed to connect to server".$conn->connect_error);
}
$number = uniqid();
if(isset($_POST["namn"])) {
$sql = "INSERT INTO information (firstname, lastname, urlID)
VALUES ('".$_POST["namn"]."','".$_POST["efternamn"]."',
'".$_POST["hide"]."')";
if($conn->query($sql)== TRUE){
$link = "http://localhost/sqltutorial/execute.php?id=$_POST[hide]";
// line moved to here
echo $link;
} else {
echo "failed";
}
}
The problem is that when the postback runs, you also run the line $number = uniqid(); again. So the final number which is output is not the one you placed in the hidden field.
Now, you could write
$link = "http://localhost/sqltutorial/execute.php?id=".$_POST["hide"];
and it would output the number which was passed in the POST variable.
Or you could just wait until the postback has happened to generate the unique ID, and use that in both the database call and the output. This saves a) a round-trip for the variable to the browser and back to the server, and b) anyone trying to tamper with the form data. So move the number creation code inside the if:
if(isset($_POST["namn"])) {
$number = uniqid();
...and then replace both references to $_POST["hide"] with $number instead. You can also remove the hidden field from your form.
One final alternative suggestion: Do you even need to do this? I assume your database table has an auto_increment integer field as the primary key? Why not just use the value already being generated by the database as the value for your link?
if($conn->query($sql)== TRUE){
$link = "http://localhost/sqltutorial/execute.php?id=".$conn->insert_id;
would get the auto-generated ID of the last row you inserted and use that in the link instead. See also documentation
I don't see any great purpose in creating a second ID for your row (especially since uniqid() does not promise to always give you a completely unique value), unless you have some specific reason?
So, you want to create a row and redirect on that link after creating.
Steps:
1) First get the next auto increment value for this informations table by this function and store it in $number.
$stmt = $this->db->prepare("SHOW TABLE STATUS LIKE 'informations'");
$stmt->execute();
$result = $stmt->fetchAll();
foreach ($result as $row) {
$number = $row[10];
}
2) Now do inserting, and after insert you'll get the same autoincrement ID and do everything with that.
Hope, it will help.
NB: You can make a function to grab that auto Increment ID for any table also.
I am trying to create a simple chat application. Below, you notice that my PHP code is inside a div, which is for the chat data, and that div is inside another div representing the chat box. Inside my PHP code, I wrote my PHP function. It connects to the myPHPadmin server and then it has a query to place the inputted data from the person's name into the database. I have an echo statement to write what the person wrote. As soon as I press the submit button, it will show what the person wrote, but if I type another message in, the message text gets replaced. How do I get my PHP code to dynamically create echo statements as if it were a chat conversation? It should create a new line each time I send a message.
<div id="chat_box">
<div id="chat_data">
<?php
function sendMessage()
{
//I hid my login credentials
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$dbc = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($dbc->connect_error)
{
die("Connection failed: " . $dbc->connect_error);
}
$name = $_POST['name'];
$msg = $_POST['log'];
$query = "INSERT INTO `chatApp` (`name`, `pwd`, `message`) VALUES ('$name', NULL, '$msg')";
$run = $dbc->query($query);
echo "<p>" . $name . " : </p> ";
echo "<p>" . $msg . "</p>";
}
?>
</div>
</div>
Use Ajax (Asynchronous Javascript and XML) to fullfill your requirement.
Since, PHP is a server side programming language, on clicking submit button the page need to contact with the server and should refresh for getting data.
Ajax will remove the headache of refreshing and get the data from the server on the way without refreshing your page.
Learn the basics of Ajax and apply it in your project on your own.
I'm new to PHP and am trying to build my a website to display information on TV shows stored in a MySQL DB. I've currently got a webpage that will create a table to display the information in the DB, however I'd like each row to link to a dynamically populated page with more info on each show (also pulling from the DB). My question is how do I get the site to know which link has been clicked and then save that as a variable so it can then be recalled on a new to populate the correct information?
I'm currently using this to populate the page.
<!--Populate page with data from SQL-->
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "media_server";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT show_title, show_desc, thumbnail_path FROM tv_shows WHERE status = 'Y'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th></th><th></th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "
<tr>
<td>
<img src='../images/thumbnails/tv/".$row["thumbnail_path"]."'>
</td>
<td class='td_title'>
<a href='#' onclick='show_var_set();'>".$row["show_title"]."</a>
</td>
<td class='td_desc'>".$row["show_desc"]."</td>
</tr>";
}
echo "</table>";
} else {
echo "Error - 0 results were returned my the database. Please try again.";
}
$conn->close();
?>
One option is to change your href links to point to this page and pass a GET variable you can retreive. The added bonus to this approach is you could bookmark a particular show and come back to that page, since the bookmark will include that GET variable.
So you could change your links to something like this:
echo '', $row['show_title'],'';
Then you'd retrieve that variable by testing for, then reading the GET variable and performing a db query to populate the page with that show's data.
Here's how you'd test for and retreive that variable:
if (isset($_GET['show']))
{
$show = $_GET['show'];
// Perform database lookup using $show
}
Remember to never put user input directly into a query, but use prepared statements and bind the user data to avoid the risk of SQL injection.
There are many ways to pass values from page to page but one is to use session variables:
//Include this at the top of your php scripts that use session variables
session_start();
$_SESSION['your_variable_name_here'] = value_you_want_to_store;
Then on the page you would like to access this use:
$someVariable = $_SESSION['your_variable_name_here'];
Change the SQL to return the show_id,
$sql = "SELECT show_id, show_title, show_desc, thumbnail_path FROM tv_shows WHERE status = 'Y'";
and use that as a parameter to the show_var_set() function.
<a href='#' onclick='show_var_set(".$row["show_id"].");'>".$row["show_title"]."</a>
The show_var_set() function can then use that parameter to get the details for that show from the database.
I'm learning PHP and SQL by running MAMP on my Mac, and accessing the database through phpMyAdmin.
I've made one PHP script to add a new user to a table, one for comparing inputted data with the table (login) and one to close an account. All of the scripts are very basic and the data isn't sanitized at all, as I'm just getting used to the basics of PHP.
I've noticed that after I run the script for account creation (inserting data), a few seconds after the script is run, a new row is added to the table with an id (which I've set to auto increment) but no other data.
I'm just wondering if the reason for this is something obvious in MySQL that I'm just missing.
The following is the account creation script:
<?php
//Get values from HTML form
$varUsername = $_POST['username'];
$varPassword = $_POST['password'];
$varPasswordHash = password_hash($varPassword, PASSWORD_DEFAULT);
//Establish connection to database
$server = "localhost";
$username = "root";
$password = "root";
$database = "members";
$connection = mysqli_connect($server, $username, $password, $database);
if(!$connection)
{
die("Connection failed: " . mysqli_connect_error());
}
//Send data to database
$action = "INSERT INTO details (USERNAME, PASSWORD) VALUES ('$varUsername', '$varPassword')";
if(mysqli_query($connection, $action))
{
echo 'Account created.';
}
else
{
echo 'Account creation failed: ' . mysqli_error($connection);
}
mysqli_close($connection); //End connection to database
?>
and the HTML form to go with it:
<html>
<body>
<form action="sign_up.php" method="post">
<input type="text" name="username">
<input type="text" name="password">
<input type="submit">
</form>
</body>
</html>
I'm making a guess right now...
I would add an extra if-statement to the script itself. Like this:
if (isset($_POST['submit-form'])) {
// All the above to insert the data into the script...
}
It would make sense if you visit the sign_up.php itself and notice there is a new entry made into your database.
You'll have to modify your HTML a little, to make the if-statement work.
Just add name='submit-form' to the submit button: <input type="submit" name="submit-form">
This will make the script more complete.
Also a little update on the matter as I just read that it adds an empty row after you submit an empty form.
You can check wether the fields are filled in with, guess what, another if-statement:
if (empty($_POST['username'])) {
echo 'Please enter your username...';
} else
if (...)
You do not verify if the POSTed values have anything in them, thus submitting an empty form results in an empty entry in the DB with just the ID.
I am trying to create a form builder that will enable users generate survey form/page.
After the form is generated the form attribute is stored on a table.
Question 1:
Where can I store the form attribute knowing fully well that the number of fields user might add in the form is unknown.
Question 2:
Where and how do I store data submitted through the generated form when some one for example completes the survey form.
Should I create new tables on fly for each of the form attributes? If yes what if over a million forma are created which translates to a million tables.
Is this where multi-tenancy comes into play.
Please provide your answer based on best practices.
I think I get what you're asking, but why not create one table with 100 columns, labelled 1-100. Set a limit on the amount of fields a user can create(Limit 100).
Then, POST the fields and add a sql query to store the values...?
COMMENT ANSWER
If the user is already signed in filling this form I would personally do the POST request on the same page.
<?php if (isset($_POST['field1'])){
$valueforField1 = $_POST['field1'];
$valueforField2 = $_POST['field2'];
$valueforField3 = $_POST['field3'];
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO Survey (field1, field2, field3) // I guess you would `have to add 100 fields here to accommodate the fields in your DB Also, you can set a default value in MySQL that way if field 56-100 is not set it has a value like 0 or add the value in this php file`
VALUES ('$valueforField1', '$valueforField2', '$valueforField3')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close(); ?>
COMMENT ANSWER or if you want to wait for the user to log in you can store all the values in a SESSION variable.
<?php
session_start();
if (isset($_POST['field1'];)){
if (!(isset($_SESSION['email']))){
$_SESSION['field1'] = $_POST['field1'];
// You would have to do 100 of these
}
}
?>