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.
Related
I'm sending data to a db from a web form but every time I run it the data is stored in the db in six new rows rather than just one.
The form is just a standard form with inputs for email/password and a submit button. The action of the form runs this:
<?php
// connect to db
$link = new mysqli("localhost", "root", "", "db_name");
if (!$link) {die('Database Error: Could not connect: ' . mysql_error());}
// username and password sent from form
$email = $_POST['email'];
$password = ($_POST['password']);
// encrypt
$salt = substr(base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM)), 0, 16);
$em = crypt($email, '$6$'.$salt);
$pw = crypt($password, '$6$'.$salt);
// insert to db
$insert = "INSERT INTO users (email, password) VALUES ('$em', '$pw')";
$link -> query($insert);
// check succes/fail
if ($link->query($insert) === TRUE) {
echo "New record created successfully";}
else {
echo "Error: " . $sql . "<br>" . $link->error;
}
// close the db connection
$link->close();
I know this brings up a question about sanitizing inputs with encryption/salting. This page says that it's a reasonable method. Please feel free to bring that up, but I'm not really looking for an argument over best practices for sanitizing user inputs.
I'm wondering if anyone cal tell me why the data would be stored 6 times instead of just once. I changed the $6$ to $1$ but it still added 6 rows.
You have some silly seo-friendly links implementation on your site that makes it run your php code on every reques, and 5 links to non-existent resources in your html.
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
}
}
?>
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.