How do I change state value on MySQL with an a href? - php

I can't change the state of a value with a href.
I have tried in all ways. Here is my code
Giallo
giallo.php=
<?php
// Create connection
$conn = new mysqli('localhost','root','','agenda');
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$id = $_GET['id'];
$qry = mysqli_query($db,"select * from note where id='$id'"); // select query
// when click on Update button
if(isset($_POST['update'])) {
$colore=1;
$edit = mysqli_query($db,"update note set colore='$colore' where id='$id'");
if($edit) {
mysqli_close($db); // Close connection
header("location:udienze.php"); // redirects to all records page
exit;
} else {
echo mysqli_error();
}
}
if (mysqli_query($conn, $sql)) {
echo "<script>
alert('Nota inserita correttamente');
window.location.href='add-udienze.php';
</script>";
} else {
echo "<script>
alert('Errore');
window.location.href='add-udienze.php';
</script>";
}
mysqli_close($conn);
?>
What is wrong with my code? There are probably cleaner ways to do it. I have tried all ways that I know.

I think the problem is that you are calling the giallo.php script with multiple kind of params (POST and GET).
So when you click on the link, the "href" attribute redirects to giallo.php, but nothing happen because it miss the $_POST['update'] action.
Probably the solution fit your case can be edit the href attribute, adding a GET parameter for "update", like:
Giallo
And then edit the giallo.php file and consider the new $_GET["update"] and not the POST one.

Related

User not being deleted on link click [duplicate]

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);
}

PHP link to profile page

Im new on php, so i need some sugests for following code:
<?php
// Start the session (pretty important!)
session_start();
// Establish a link to the database
$dbLink = mysql_connect('', '', '');
if (!$dbLink) die('Can\'t establish a connection to the database: ' . mysql_error());
$dbSelected = mysql_select_db('', $dbLink);
if (!$dbSelected) die ('We\'re connected, but can\'t use the table: ' . mysql_error());
$isUserLoggedIn = false;
$query = 'SELECT * FROM users WHERE session_id = "' . session_id() . '" LIMIT 1';
$userResult = mysql_query($query);
if(mysql_num_rows($userResult) == 1) {
$_SESSION['user'] = mysql_fetch_assoc($userResult);
$isUserLoggedIn = true;
} else {
if(basename($_SERVER['PHP_SELF']) != 'conectare.php') {
header('Location: conectare.php');
exit;
}
}
?>
Upper code verify if user it's logged in or not..
I need to create a profil link, like following:
http://site.com/profile.php?name=NAME-OF-USER
Can someone give me a ideea?
Im newbie on php, so pls understand me..
PS: Please dont tell me to use mysql, pdo and another, i allready know the beneficts, i need only answers for my code..
Thank you !
you simply need to use the get variable
create the link that will be clicked like this
the link that will be clicked on home page or any other page
<?php
$username='test';//the variable containing the username
echo'<a href="mysite.com/profile.php?user='.$username.'">
The link redirecting to profile page
</a>';
?>
the address bar will turn something like this www.mysite.com/profile.php?user=test
then on the profile page
<?php
$username_selector=$_GET['user']//in this case the value got from the link clicked is test
//then just select the necessary data using the variable storing the value got from th link clicked
?>
All you need to do is echo some html:
$username = "foo";
echo "profile link";
Note: I use \" to escape the "
More information about strings in php: http://php.net/manual/en/language.types.string.php

Form to insert data in database works, but does not show success-page

I've a simple order-form on my website. If I click the submit-button the the form will send the data to my database. This works. But it does not show the success.php - it only shows the start.php again. So there must be a mistake. On my previous hoster it worked. But now I have a new one.
Here's my php-script (start.php):
<?php
$con = mysql_connect("localhost", "user", "pw") or die ("No connection to db possible");
mysql_select_db("db", $con) or die ("No connection to db possible");
mysql_query("SET NAMES 'utf8'");
if (isset($_POST['button']))
{
foreach ($_POST AS $key => $postvar)
$_POST[$key] = stripslashes($postvar);
$_POST['name'] = mysql_real_escape_string($_POST['name']);
$_POST['strasse'] = mysql_real_escape_string($_POST['strasse']);
$_POST['plz'] = mysql_real_escape_string($_POST['plz']);
$_POST['ort'] = mysql_real_escape_string($_POST['ort']);
$_POST['mail'] = mysql_real_escape_string($_POST['mail']);
$_POST['anzahl'] = mysql_real_escape_string($_POST['anzahl']);
$sql = "INSERT INTO `bestellungen` (`name`,`strasse`,`plz`,`ort`,`mail`,`anzahl`,`datetime`)
VALUES ('".$_POST['name']."', '".$_POST['strasse']."', '".$_POST['plz']."', '".$_POST['ort']."', '".$_POST['mail']."', '".$_POST['anzahl']."', '".date("Y-m-d H:i:s")."');";
$result = mysql_query($sql,$con);
if (!$result) echo mysql_error();
mysql_close($con);
?>
<?php Header("Location: success.php");
exit();
?>
<?php
} else { ?>
That won't work because header('Location: success.php') needs to happen before you output anything to the browser. You seem to have gaps before that is called.
$result = mysql_query($sql,$con);
if (!$result) echo mysql_error();
mysql_close($con);
// Now its time for the header!
header("Location: success.php");
exit();
You cannot have any output before the header() redirection.
Check your script for possible errors, warnings or notices, any of these will output text and the redirection will no happen.
So far, whenever I found this kind of problem; there must be two reasons I often do. Either I print any html code before the header function or I don't realize that my success.php also redirect to start.php.
Maybe you can check either of these two exist in your code.
Format it this way.
$result = mysql_query($sql,$con);
if (!$result) {
echo mysql_error();
} else {
Header("Location: success.php");
}
mysql_close($con);
?>

php require and javascript

I use this code to connect to a database:
#mysql_connect("localhost","root","") or die(mysql_error());
#mysql_select_db("ECOLE") or die (mysql_error());
#mysql_set_charset('utf8');
if(isset($_POST['profname_in'])){
$querycheck = "SELECT prof_som FROM prof_table
WHERE prof_som=$_POST[profsom_in];";
$_querycheck=mysql_fetch_array(mysql_query($querycheck));
if(isset($_querycheck['prof_som'])){
echo "0";
}else{
$query="INSERT INTO prof_table
VALUES('$_POST[profname_in]',
'$_POST[profcin_in]',
'$_POST[profsom_in]',
'$_POST[profville_in]',
'$_POST[profecole_in]',
'$_POST[profmat_in]',
'$_POST[profpass_in]');";
if(mysql_query($query)){
echo "1";
}
}
}
the echos is recupered by a javascript function (ajax):
function adding_prof_Reply() {
if(http.readyState == 4){
var response = http.responseText;
if(response==0){
document.getElementById('prof_validation').innerHTML = '<font color="red">'+response+'</font>';
}else if (response==1){
document.location.href="dir_paneau.php";
}else{
document.getElementById('prof_validation').innerHTML = '<font color="red">'+response+'</font>';
}
}
}
everything works good, the problem is when I use require('anyfile') in the php code then the test if(response==0) is always false even when respose==0 ; if I remove the line of require everything works as it should.
I need the require to not repeat the connection information, any ideas?
"i need the require to not repeat the connection information"
To only connect once, put the 'connection information' in a separate file, maybe dbConnect.php and use the function require_once('dbConnect.php') in the files which need a database connection.
This ensures you only connect to your database once, which may solve your problem.

file download using mysql and PHP

I am creating PHP page that allows users to download files when they click in this button:
<td><a href='download.php?id={$row['file_name']}'>Download</a></td>
then the page redirect to download.php, code:
<?php
// Make sure an ID was passed
if(isset($_GET['file_name'])) {
// Get the ID$id
$file_name= ($_GET['file_name']);
// Make sure the ID is in fact a valid ID
if($file_name == NULL) {
die('The name is invalid!');
}
else {
// Connect to the database
$dbLink = new mysqli('localhost', 'root', "", 'db_name');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ".mysqli_connect_error());
}
// Fetch the file information
$query = "
SELECT `type`, `file_name`, `size`, `data`
FROM `pdfs`
WHERE `file_name` = {$file_name}";
$result = $dbLink->query($query);
if($result) {
// Make sure the result is valid
if($result->num_rows == 1) {
// Get the row
$row = mysqli_fetch_assoc($result);
header("Content-Type: ".$row['type']);
header("Content-Length: ".$row['size']);
header("Content-Disposition: attachment");
// disopsition = attachment to force download request
// Print data
echo $row['data'];
}
else {
echo 'Error! No file exists with that ID.';
}
// Free the mysqli resources
#mysqli_free_result($result);
}
else {
// if there is an error excuting the query
echo "Error! Query failed: <pre>{$dbLink->error}</pre>";
}
// close database connection
#mysqli_close($dbLink);
}
}
else {
// if no ID passed
echo 'Error! No ID was passed.';
}
?>
however, wehn i click in download i always get the massage of the last else statement "error no id was passed", but i can't find the problem, is the problem that i made the primary key of the file is the name??
If your link looks like this:
<a href='download.php?id={$row['file_name']}'>
Then the GET variable will be 'id' as in $_GET['id'] and not $_GET['file_name']
$_GET['file_name'] should be $_GET['id']
since <a href='download.php?id={$row['file_name']}'> you sending "id" not "file_name"
Typo
<td><a href='download.php?id=<?php echo $row['file_name']; ?>'>Download</a></td>
<a href='download.php?id={$row['file_name']}'>
u should use <a href="download.php?id=<?= $row['file_name'];?>">
then use $_GET['id'] since id is the variable u pass in url not $_GET['file_name']

Categories