i want to make so my webpage takes values from a table in a database and displays them on the screen in the format that is shown below in the code, however i would then like to take the values for BikeID and ContactEmail and save them to session storage to be used on the update confirm page which your taken to when the update button is clicked. however the first issue is that the values wont save to the session storage and the second is that even if they did would the session get the correct value according to the Table/BikeID selected where the button is clicked. Image of the page layout after the code is run is below.
if anyone has any ideas i would be grateful.
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$username="Username"; // change this to your database username
$password="Password"; // change this to your database password
$database="Database"; // change this to your database username
$conn = new mysqli('localhost', $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM tblBikeStolen, tblBike WHERE tblBike.BikeID=tblBikeStolen.BikeID";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<div id='UpdateTable'><table><tr><td> User No: " . $row["User"] . "</td>
<td>Bike ID: " . $row["BikeID"]. "</td><td> Contact: " . $row["ContactEmail"] . "</td></tr><tr><td>
Reported Time: " . $row["ReportTime"] . "</td><td> Address: " . $row["Address"] . "</td><td> Bike
MPN: " . $row["BikeMPN"] . "</td></tr><tr><td> Bike Brand: " . $row["BikeBrand"] . "</td><td> Bike
Model: " . $row["BikeModel"] . "</td><td> Bike Type: " . $row["BikeType"] . "</td><tr><td>
Investigation Notes: " . $row["UpdateNotes"] . "</td></tr><tr><td> Status: " . $row["Status"] . "
</td></tr><tr><form><button class='btn btn-primary btnUpdateInvest' type='submit'
value='Update'formaction='ConfirmUpdate.php' onClick='UpdateFunctionDAO.php'>Update</button></form>
</tr></table></div>";
$BikeID = $row['BikeID'];
$_SESSION["BikeID"] = $BikeID;
$ContactEmail = $row['ContactEmail'];
$_SESSION["ContactEmail"] = $ContactEmail;
}
} else { echo "0 results"; }
$conn->close();
?>
I recommend starting simple and then expanding your use case:
Instead of using formaction = 'ConfirmUpdate.php', try using formaction = 'ConfirmUpdate.php?bikeid=<your-bike-id>&contactemail=<the-contact-email>'
In ConfirmUpdate.php, check if $_GET['bikeid'] and $_GET['contactemail'] are set and valid. If you didn't get either of those keys or if they were invalid, write a meaningful error message on the screening instructing the user what to do next.
If you received both those keys and their values were reasonable, you can store them in a session for future processing. Once your processing is done, clear out that information from the session.
Your PHP code will look something like this:
echo "...value='Update' formaction='ConfirmUpdate.php?bikeid=" . $row["BikeID"] . "&contactemail=" . $row["ContactEmail"] . "' onClick='UpdateFunctionDAO.php'>...";
Try this and see how it works. You might have to do more work after this to ensure that the data you are publishing on the page is sanitized and not susceptible to injection.
Example
Let's say your initial page is called test.php and it looks like this:
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$username=""; // change this to your database username
$password=""; // change this to your database password
$database=""; // change this to your database username
$conn = new mysqli('localhost', $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "your sql query";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
while ($row = $result->fetch_assoc())
{
$displayText = sprintf('<div>Some other info. Bike ID is %s and contact is %s.</div>',
$row['bikeid'],
$row['contactemail']
);
$form = sprintf('
<form method="post" action="ConfirmUpdate.php">
<input type="hidden" name="bikeid" value="%s">
<input type="hidden" name="contactemail" value="%s">
%s
<input type="submit" value="Submit">
</form>',
$row['bikeid'],
$row['contactemail'],
$displayText
);
echo $form;
}
}
$conn->close();
?>
Result
Your ConfirmUpdate.php will look like this:
<?php
session_start();
$_SESSION['bikeid'] = $_POST['bikeid'];
$_SESSION['contactemail'] = $_POST['contactemail'];
echo sprintf('Received bike id %s and contact email %s',
$_SESSION['bikeid'],
$_SESSION['contactemail']
);
?>
When you click on the first button, you will be taken to ConfirmUpdate page, which will look like this:
Received bike id 1 and contact email test#gmail.com
When you click the 2nd button, you will see:
Received bike id 2 and contact email test#yahoo.com
Test this out on your own systems and you should be able to replicate this code in your project.
Related
I want to be able to read the raw data from the URL path. The URL will look like:
https://newtest.000webhostapp.com/db.php?datainurl
The db.php is:
<?php
$postdata = file_get_contents("php://input");
$conn = new mysqli('localhost','2541','yhte','tg543');
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "insert into cloud set rfid='.$postdata'";
if ($conn->query($sql) === TRUE)
{
echo "New record created successfully";
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
When I press enter in the URL the webpage echos: New record created successfully. I see the id in the database but the contents is not shown in the database.
Why the "datainurl" in the URL is not showing in the database?
The query string is available through $_SERVER['QUERY_STRING'].
php://input contains the request body.
I'm Not so good about PHP, I m still learning that language, so I have made Form which one will add data to mysql using PHP and Method POST. But in when i click on submit nothings happens in the database, no data added.
This is config.php
$SETTINGS["hostname"]='localhost';
$SETTINGS["mysql_user"]='username';
$SETTINGS["mysql_pass"]='passw';
$SETTINGS["mysql_database"]='database';
$SETTINGS["data_table"]='defaulttable'; // this is the default database name that we used
/* Connect to MySQL */
if (!isset($install) or $install != '1') {
$connection = mysql_connect($SETTINGS["hostname"], $SETTINGS["mysql_user"], $SETTINGS["mysql_pass"]) or die ('Unable to connect to MySQL server.<br ><br >Please make sure your MySQL login details are correct.');
$db = mysql_select_db($SETTINGS["mysql_database"], $connection) or die ('request "Unable to select database."');
};
?>
and here is my HTML FORM
<form action="insert.php" method="post">
<li>Place Name: <input type="text" name="plname" /></li>
<li>City: <input type="text" name="plcity" /></li>
<li>Address: <input type="text" name="pladdress" /></li>
<li>Terminal QTY: <input type="number" name="plqty" /></li>
<li><input type="submit" name="save" value="Add Place" /></li>
And What About insert.php
<?php
include ("config.php");
$current_user = wp_get_current_user();
$UserID = $current_user->user_login ;
// Check connection
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
//$sql="INSERT INTO wp_telemetry_place (plUserID, plName, plCity, plAddress, plTerminalQ) VALUES ('".$UserID."','".$_POST['plname']."','".$_POST['plcity']."','".$_POST['pladdress']."','".$_POST['plqty']."')";
$sql = "INSERT INTO wp_telemetry_place (plUserID, plName, plCity, plAddress, plTerminalQ) VALUES ('{$UserID}','{$_POST['plname']}','{$_POST['plcity']}','{$_POST['pladdress']}','{$_POST['plqty']}')";
if (mysqli_query($connection, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($connection);
}
mysqli_close($connection);
?>
And when I klick to Button for add data, it does not works. No Errors, No Data updated or added in mysql database. What about Passwords, Host, Usernames, Table names etc... I Checked twice :( I would appreciate any helps from your side guys, Thanks in advance and SORRY FOR MY BAD ENGLISH
Your SQL query is not formatted properly. Try this:
$sql = "INSERT INTO wp_telemetry_place (plUserID, plName, plCity, plAddress, plTerminalQ) VALUES ('{$UserID}','{$_POST['plname']}','{$_POST['plcity']}','{$_POST['pladdress']}','{$_POST['plqty']}')";
Your query is probably giving you an error message, but you have a typo in your code, replace $conn with $connection to read it, like so:
echo "Error: " . $sql . "<br>" . mysqli_error($connection);
Finally, and this is important, the way you're writing your code is hugely dangerous, because you're accepting user input without any filtering. I recommend you google SQL injection to learn more about it.
The main Problem was 'i' I changed
if (mysqli_query($connection, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($connection);}
to
if (mysql_query($connection, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysql_error($connection);}
Now it works perfect, Just I need to look at SQL Injection thats all. Thank you guys anyway :))
Ok, so I'm making this website (kind of like bitly or goo.gl) where you enter a link and it shortens it, but with some extra goodies.
Right now I'm just hosting a local mysql server for testing, and the way it is setup, once a link is entered to shorten, a random 3 digit code is generated and put into the mysql table, along with its link.
When you enter the code on the site, it goes to the mysql table, finds the code, finds the corresponding link, and in theory is supposed to bring back that link, and then open it.
This is where the problem is. It simply does not work. I cannot figure out whether it is a problem with the html page, or with the scripting but I have no idea.
I'm not very experienced with PHP (language im using for query script) so I'm not sure how to go about troubleshooting.
I was hoping someone on here could offer some insight into why it may be not working.
All I know is when I click the "Go" button, it opens the php code rather than running it, and I'm not sure how to fix it.
Because of me not knowing exactly what the problem is, here is both the html and php code.
HTML:
(stripped down to just body for convenience. nothing interesting anywhere else)
<body>
<center><form action="sql_query.php" method="post">
<input class="enjoy-css" placeholder="" maxlength="3" name="var" type="text" />
<script type="text/javascript" script-name="josefin-sans" src="http://use.edgefonts.net/josefin-sans.js"></script>
<input type="submit" class="enjoy-css_1" value="Go" src="sql_query.php" />
<script type="text/javascript" script-name="josefin-sans" src="http://use.edgefonts.net/josefin-sans.js"></script>
</form></center>
PHP:
<?php
$servername = "localhost";
$username = "nimbleadmin";
$password = "admin";
$dbname = "nimble";
$var = $_POST['var'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = mysql_query("SELECT id, nimblecode, urlredirect, messageredirect FROM linker WHERE nimblecode = '" + $var + "'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo "id: " . $row["nimblecode"]. " //// URL: " . $row["urlredirect"]. " //// Message: " . $row["messageredirect"]. "<br>";
if ($row["messageredirect"]. == null) {
header('Location: ' . $row["urlredirect"]);
} else {
header('Location: http://nic.x10.mx/message?' . $row["nimblecode"]);
}
$conn->close();
?>
Any help is greatly appreciated! I know it's a bit of a interesting question, but I am still learning!
There is syntax error in your code, please use dot for concatentation in php and use mysqli object while querying instead of mysql.
$result = mysqli_query($conn, "SELECT id, nimblecode, urlredirect, messageredirect FROM linker WHERE nimblecode = '" . $var . "'");
Full Code changes: Store this file in the name as "tinyurl.php"
<?php
$servername = "localhost";
$username = "nimbleadmin";
$password = "admin";
$dbname = "nimble";
$var = $_GET['var'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = $conn->query("SELECT id, nimblecode, urlredirect, messageredirect FROM linker WHERE nimblecode = '%s', $var);
if (!$result) {
echo 'Could not run query: ' . mysql_error(); exit;
}
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
echo "id: " . $row["nimblecode"]. "
//// URL: " . $row["urlredirect"]. "
//// Message: " . $row["messageredirect"]. "";
}
if ($row["messageredirect"] == "") {
header('Location: ' . $row["urlredirect"]);
} else if ($row["nimblecode"] != "") {
header('Location: http://nic.x10.mx/message?' . $row["nimblecode"]);
} else {
header('Location: http://nic.x10.mx/');
}
$conn->close();
?>
In .htaccess need to add this rule :
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/?$ http://nic.x10.mx/tinyurl.php?var=$1 [QSA,NC,L]
Sample URL entry
http://nic.x10.mx/abc
Will redirect to the target URL present in DB.
If you can't run php code then check if apache's httpd.conf file has PHP MIME type uncommented, besides there are other things to consider. Check this Apache shows php code instead of executing
I am trying to make a messenger using PHP and SQL
This is my code
<form action="send_post.php" method="post">
<h3>Name:</h3>
<input type="text" name="name">
<h3>Message:</h3>
<input type="text" name="message">
<input type="submit">
</form>
<?php
$servername = "servername";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name, message FROM chat";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
while(1){
ob_start();
echo "" . $row["name"]. " - " . $row["message"]. "<br>";
sleep(10);
echo "" . $row["name"]. " - " . $row["message"]. "<br>";
ob_end_clean();
}
}
}
$conn->close();
?>
However this does not work, is there any reason for this?
The problems started once I added the infinite while loop to refresh the messages.
PHP works serversided, which means that the client(guest) requests a page that the server then "compiles" to then send to the client as a clientsided language such as HTML. If the PHP code never reaches an end/stop the client browser is going to think the server stopped responding and give an error.
To achieve what you are trying to do you might want to look into something like JQuery AJAX which allows for the client to fetch data from the server seperatly from the main request. That way you can have one file showing only the messages and request that file on a timer, while having the form as usual page load. You can however also make the form dynamic using JQuery AJAX
UPDATE You can look at this blogpost to get an idea of what I'm talking about.
My site is an admin login site, therefore users cannot register. However they can post comments to the site. I have delete buttons on the comments but didn't realise that anybody can then delete anybodies comments. How can I change this so when the admin is logged in they are able to delete inappropriate comments (if any) and get rid of the delete button from the general public.
This is my Comment.php code with the delete button function in there:
<?php
session_start();
require_once 'templates/open.php';
require_once 'connect.php';
require_once 'functions/cleanstring.php';
require_once 'functions/encrypt.php';
?>
Another code file:
<?php
$db_hostname = 'localhost';
$db_database = 'cs12e2g_MyFirstDB'; //'Your database name'
$db_username = 'cs12e2g_DBuser'; //'your username';
$db_password = 'vtjppqs7'; //'Your password';
$db_status = 'not initialised';
$db_server = mysqli_connect($db_hostname, $db_username, $db_password);
$db_status = "connected";
if (!$db_server){
die("Unable to connect to MySQL: " . mysqli_connect_error());
$db_status = "not connected";
}
// Includes and variables always required
require_once 'recaptcha/recaptchalib.php';
require_once 'functions/cleanstring.php';
$privatekey = "6Lem4-gSAAAAADsaa9KXlzSAhLs8Ztp83Lt-x1kn";
$publickey = "6Lem4-gSAAAAAMHLAVbieIknMtUZo71ZKzzCkoFN";
mysqli_select_db($db_server, $db_database);
$str_message = "";
if (!$db_server){
die("Unable to connect to MySQL: " . mysqli_connect_error());
}else{
if(isset($_GET['delete'])){
$deleteq="DELETE FROM comments WHERE ID={$_GET['delete']} LIMIT 1";
$deleter=mysqli_query($db_server, $deleteq);
IF($deleter){
echo"<p>That message was deleted!</p>";}}
//Test whether form has been submitted
if(trim($_POST['submit']) == "Submit"){
//Handle submission
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
$str_message = "The reCAPTCHA wasn't entered correctly. Go back and try it
again.
(reCAPTCHA said: " . $resp->error . ")";
} else {
// Your code here to handle a successful verification
$comment = $_POST['comment'];
if($comment != ""){
$query = "INSERT INTO comments (comment) VALUES ('$comment')";
mysqli_query($db_server, $query) or die("Comment insert failed: " .
mysqli_error($db_server) );
$str_message = "Thanks for your comment!";
}else{
$str_message = "Invalid form submission";
}
}
}
//Create page with or without submission
$query = "SELECT * FROM comments";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server) );
while($row = mysqli_fetch_array($result)){
$ID= $row['ID'];
$str_result .= "<p><em>Comment $j (" . $row['commDate'] .
")</em><br /> " .$row['comment'] . "</p>
<a href ='commentnow.php?delete=$ID
'>Delete</a><hr />";
}
mysqli_free_result($result);
}
?>
<h1>What do you think?</h1>
<p><h5>Did you find everything you wanted? Please comment below:<h5></p>
<form action="commentnow.php" method="post">
<textarea rows="10" cols="50" name="comment"></textarea><br />
<?php echo recaptcha_get_html($publickey); ?>
<input type="submit" name="submit" value="Submit" />
</form>
<span style="color:#FF0000;">
<?php echo $str_message; ?></span>
<hr />
<h2>Comments:</h2>
<?php echo $str_result; ?>
</div>
<?php
require_once 'templates/close.php';
?>
I have a members.php page which corresponds to when the admin logs in (they are the only ones that can access this page) would the delete button code have to go in here? so they are the only ones that can use the function? If so where would it go, and how?
Restrict the delete button to show only for the admin. Also this would mean that you somehow identify if the logged in user is an admin.
if ($is_admin) {
// Code to display button
}
Also in the backend check if the logged in user is admin
if ($is_admin) {
// Code to delete comment
delete_comment();
}
and you welcome to php.
You have that identify the users that enter in your application.
Using database or arrays or files or variables etc etc.
If permission is equal to admin or editor (For example) allow delete.
For example
if( $login == 'admin' ){
// Allow action
}
My you understand?
(My English is bad, sorry)