<form action="insertresubmittedpaper.php" autocomplete="on" enctype="multipart/form-data" method="post">
<h1>Re-Submit Paper</h1>
<p>
<input type="file" name="uploaded_file"><br>
</p>
<br>
<br>
<center>
<p class="submit button">
<input type="submit" value="Submit">
</p>
</center>
</form>
Hello I'm working on a project where I need to insert a file into database, and after that I have an option where the user can update the existing file in database using a form and when once updated it will be redirected to another page.
I'm using PHP , mysql.
The Problem is a new file is not being updated into the database, but it is redirecting to another page.
Here i'm posting my code. Please suggest me necessary changes.
<?php
session_start();
if(isset($_SESSION['username']))
{
echo "<div id='User'>Welcome: " . $_SESSION['username'] . "</div>";
}
else
{
echo "<div id='Guest'>Welcome: Guest </div>";
}
/*
Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password)
*/
if(isset($_FILES['uploaded_file'])) {
// Make sure the file was sent without errors
if($_FILES['uploaded_file']['error'] == 0) {
$link = mysqli_connect("localhost", "kuda", "secret", "researchcloud");
// Check connection
if($link === false)
{
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$UserName=$_SESSION['username'];
$Subject = mysqli_real_escape_string($link, $_POST['subject']);
$Category = mysqli_real_escape_string($link, $_POST['category']);
$Journal = mysqli_real_escape_string($link, $_POST['journal']);
$mime = mysqli_real_escape_string($link, $_FILES['uploaded_file']['type']);
$data = mysqli_real_escape_string($link, file_get_contents($_FILES ['uploaded_file'] ['tmp_name'] ));
// attempt insert query execution
$sql = "UPDATE rc_ijai set FullPaper='$data', mime='$mime' where A1Email='$UserName' and Journal='$Journal'";
if(mysqli_query($link, $sql))
{
header('Location:authorprofile.php');
}
else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
mysqli_close($link);
}
}
else {
echo 'An error occurred while the file was being uploaded. '
. 'Error code: '. intval($_FILES['uploaded_file']['error']);
}
?>
Don't use mysqli_query() to check that query has been executed or not. specially for insert and update queries. Because for update query some times a query will get executed and non of the row will get updated. So for insert and update check the number of rows affected after the query execution. After checking this You can easily solve it.
Related
I'm trying to connect HTML form to SQL database using PHP but when I hit submit, it is giving me PHP page.
This is HTML code
<form method="post" action="connect.php">
Username : <input type="text" name="username"><br><br>
Password : <input type="password" name="password"><br><br>
<input type="submit" value="Submit">
</form>
Here is PHP code
$username = filter_input(INPUT_POST, 'username');
$password = filter_input(INPUT_POST, 'password');
if (!empty($username)){
if (!empty($password)){
$host = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "youtube";
// Create connection
$conn = new mysqli ($host, $dbusername, $dbpassword, $dbname);
if (mysqli_connect_error()){
die('Connect Error ('. mysqli_connect_errno() .') '
. mysqli_connect_error());
}
else{
$sql = "INSERT INTO account (username, password)
values ('$username','$password')";
if ($conn->query($sql)){
echo "New record is inserted sucessfully";
}
else{
echo "Error: ". $sql ."
". $conn->error;
}
$conn->close();
}
}
else{
echo "Password should not be empty";
die();
}
}
else{
echo "Username should not be empty";
die();
}
I expect to get 'New record is inserted successfully' or 'error'
In php, once you done with the various processes in a page, you need to write a redirect otherwise it will just die waiting for the next action. At the moment, after its done executing, you it will just echo if successful and die() is failed as per your conditions.
Add:
if ($conn->query($sql)){
header("Location: /path_of_page.html");
}
The same can be applied in the }else (){} statements.
Edit: I forgot to mention, avoid using die and echo in intermediate (processing) pages since they will output on the raw php during executions. Rather, put them in an array and pass them to the UI as parameter.
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 :))
This project involves connecting to a database using phpMyAdmin. I have a file named index.php which presents the user with a simple form that connects to a file for processing called functions.php. I'm using WAMP to connect everything but when I try running everything the form and submit work but after the form is submitted the next page displays nothing when it should be displaying some information even if its an error message. I really can't figure out what's wrong. I've already created the database on phpMyAdmin by importing a file containing sql code to create all my tables for a relational database. Here is the code, any help is appreciated.
index.php
<form action="functions.php" method="post">
First Name: <input type = "text" name = "Fname"><br>
<!-- Last Name: <input type = "text" name = "Lname"><br>
Commision: <input type = "text" name = "commision"><br>
Phone Number: <input type = "text" name = "phone"><br>
Job Title: <input type = "text" name = "job"><br> -->
<input type="submit">
</form>
</body>
functions.php
<?php
$host = 'localhost';
$username = 'kempenaar';
$password = 'Jayson38!';
$db_name = '3660Project';
//$Fname = $_POST["Fname"];
echo "in the script";
$conn = mysql_connect($host, $username, $password,$db_name)
if(!$conn)
{
die ('Error connecting to MySQL server.' . mysql_error());
}
$db_select = mysql_select_db($db_name);
if(!$db_select)
{
die('Can\'t use ' . $db_name . ': ' . mysql_error());
}
$sql = "INSERT INTO Employee (First_Name, Last_Name, Commision, Phone_number, Job)
VALUES ($_POST["Fname"], $_POST["Lname"], $_POST["commision"], $_POST["phone"], $_POST["job"])";
if(mysql_query($sql)){
echo "Records inserted successfully.";
header('Location: http://localhost:8888/3660Project/');
} else{
echo "ERROR: Could not able to execute $sql. " . mysql_error($conn);
}
echo "made it here";
?>
This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Reference - What does this error mean in PHP?
(38 answers)
Closed 5 years ago.
I have a users table and I want to be able to delete a user when a link is clicked. $user_name is set in a session. Here is the link:
<?php echo "Delete Account" ?>
Here is the code on delete_user.php:
<?php
session_start();
session_destroy();
require "connection.php";
?>
<?php
if($_GET['id'] != ""){
$user_name = $_GET['id'];
$sql = "DELETE FROM users WHERE user_name='{$user_name}'";
$result = mysqli_query($connection, $sql);
header('Location: register.php');
}
?>
<?php include "footer.php";?>
I don't understand why it's not deleting the user from the database when this code is executed?
There's no clear reason as to why your code is not working. However, you mentioned being new to PHP, so picking up good practices with your code could (1) help solve the issue at hand, (2) make your code more efficient, and easier to debug.
I recommend you use mysqli in the object-oriented manner, it requires less code, and usually easier to follow.
Making the connection is simple:
<?php
$host = 'localhost';
$user = 'USERNAME';
$pass = 'PASS';
$data = 'DATABASE';
$mysqli = new mysqli($host, $user, $pass, $data);
// catch errors for help in troubleshooting
if ($mysqli->errno)
{
echo 'Error: ' . $mysqli->connect_error;
exit;
}
?>
Creating a safe environment for your server keep in mind these things:
Do not trust user input (ever!)
Do not perform direct queries into your database.
When developing, break your code into steps so you can easily troubleshoot each part.
With those three simple things in mind, create a delete file.
<?php
if (isset($_GET['id'])
{
// never trust any user input
$id = urlencode($_GET['id']);
$table = 'users';
// set a LIMIT of 1 record for the query
$sql = "DELETE FROM " . $table . " WHERE user_name = ? LIMIT 1";
// to run your code create a prepared statement
if ($stmt = $mysqli->prepare( $sql ))
{
// create the bind param
$stmt->bind_param('s', $id);
$stmt->execute();
$message = array(
'is_error' => 'success',
'message' => 'Success: ' . $stmt->affected_rows . ' were updated.'
);
$stmt->close();
}
else
{
$message = array(
'is_error' => 'danger',
'message' => 'Error: There was a problem with your query'
);
}
}
else
{
echo 'No user id is set...';
}
The code will help you set the query, and delete the user based on their user_name... Which I am not sure that is the best solution, unless user_name is set to be an unique field on your MySQL database.
Firstly this is a horrible way to do this, you are prone to SQL Injections and also using GET literally just tags the query to the end of the URL which is easily obtainable by a potential hacker or ANY user as a matter of fact. Use POST instead with a bit of jQuery magic, I would also recommend using Ajax so that you don't get redirected to php file and it will just run. As it is not anyone can access that URL and delete users so I recommend using PHP SESSIONS so that only people from your site can delete users. Also simply passing the id to the PHP file is very insecure as ANYONE could simply create a link to your php file on their site and delete users.
Therefore try this to fix your code (with added security):
PLEASE NOTE: I am aware that this may not be the best way nor the worst but it is a fairly secure method that works well.
Your main page, index.php:
<?php
session_start();
// Create a new random CSRF token.
if (! isset($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = base64_encode(openssl_random_pseudo_bytes(32));
}
// Check a POST is valid.
if (isset($_POST['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token']) {
// POST data is valid.
}
?>
...
<form id="delete_user_form" action="delete_user.php" method="post">
<input type="hidden" name="user_id" value="<?php echo $user_name; ?>" />
<input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>" />
<input type="submit" value="Delete User" />
</form>
In your .js file (make sure you have jQuery linked):
window.csrf = { csrf_token: $("input[name= csrf_token]").val() };
$.ajaxSetup({
data: window.csrf
});
$("#delete_user_form").submit(function(event) {
event.preventDefault(); //Stops the form from submitting
// CSRF token is now automatically merged in AJAX request data.
$.post('delete_user.php', { user_id: $("input[name=user_id]").val() }, function(data) {
//When it it's complete this is run
console.log(data); //With this you can create a success or error message element
});
});
Now for your delete_user.php file, this should fix the errors:
<?php
session_start();
require "connection.php";
// Checks if csrf_token is valid
if (isset($_POST['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token']) {
if(isset($_POST['user_id']) && $_POST['user_id'] != ""){
$user_name = $_POST['user_id'];
$sql = "DELETE FROM users WHERE user_name = '$user_name' LIMIT 1"; //LIMIT 1 only allows 1 record to be deleted
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully"; //You get this in your javascript output data variable
} else {
echo "Error deleting record: " . $conn->error; //You get this in your javascript output data variable
}
$conn->close();
}
}
?>
I don't know what your connection.php contains so this is what I'd put in it:
$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);
}
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)