Unable to update database row in PHP with $_POST variable - php

I want it so that when the user types into the textarea/input and clicks save changes, the information they input has been added and saved into the database. Below is my code:
$name = $_SESSION['u_name'];
$uid = $_SESSION['u_uid'];
$id = $_SESSION['u_id'];
$con = mysqli_connect("localhost", "root", "pass123", "db_name");
if ($con->connect_error) {
die("Connection failed: " . $conn->connect_error);
echo "<script type='text/javascript'>alert('connection failed. try again');</script>";
}
$remind1 = $_POST['remind1'];
$remind2 = $_POST['remind2'];
$remind3 = $_POST['remind3'];
$remind4 = $_POST['remind4'];
$remind5 = $_POST['remind5'];
if (isset($_POST['updBtn'])){
$sql = "UPDATE reminders SET remindone='$remind1' WHERE username='$uid'";
if ($con->query($sql) === TRUE) {
echo "<script type='text/javascript'>alert('Updated successfully');</script>";
}else{
echo "<script type='text/javascript'>alert('error while updating. try again');</script>";
}
}
Below is the corresponding HTML:
<form action="body.php" method="post">
<input type="submit" class="sideBtn" value="Save Changes" name="updBtn"><br>
<input type="text" class="event" name="remind1"><br>
<input type="text" class="event" name="remind2"><br>
<input type="text" class="event" name="remind3"><br>
<textarea class="event" name="remind4"></textarea><br>
<textarea class="event" name="remind5"></textarea><br>
</form>
Ideally what would happen, is that whatever the user types into the textarea/input is updated in the database, then they can access and later tweak the text if they need to.
I have been able to pinpoint that my problem is somewhere along the $_POST variables in my PHP as, if I were to substitute the aforementioned variable with a string as such:
$sql = "UPDATE reminders SET remindone='hello' WHERE username='$uid'";
...it works perfectly. But with when using the POST variable, it does not work.
How can I fix this mistake of mine and make it so that the user is able to post text into the database? Is the $_POST variable required here or is there another method to achieve this?

Related

PHP and SQL - Trying to change user login data, does nothing

I'm trying to create a form that lets an administrator change a user's password. I used this to create the forms on the page. The first allows deletion and works fine, the second should be sending the new password from the form to a function that sends to the post function I'll post below it.
echo <<<_END
<pre>
username $row[0]
role $row[2]
</pre>
<form action="admin2.php" method="post">
<input type="hidden" name="delete" value="yes">
<input type="hidden" name="username" value="$row[0]">
<input type="submit" value="DELETE RECORD"></form>
<pre>password <input type="text" name = "password"></pre>
<form action="admin2.php" method="post">
<input type="hidden" name="change" value="yes">
<input type="hidden" name="username" value="$row[0]">
<input type="submit" value="CHANGE PASSWORD">
_END;
And the if statement:
if (isset($_POST['change']) && isset($_POST['username']) &&
isset($_POST['password']))
{
$username = get_post($connection, 'username');
$password = get_post($connection, 'password');
$query = "UPDATE users SET password='$password' WHERE username='$username'";
$result = $connection->query($query);
if (!$result) echo "UPDATE failed: $query<br>" .
$connection->error . "<br><br>";
}
The page loads but when I press the button there isn't any change on the backend. Any ideas?
EDIT:
Ok, having made the changes linked to above, it does change the password but only when it's the last entry in the table. Otherwise it just deletes the entry on the table below it.
if (isset($_POST['delete']) && isset($_POST['username']))
{
$username = get_post($connection, 'username');
$query = "DELETE FROM users WHERE username='$username'";
$result = $connection->query($query);
if (!$result) echo "DELETE failed: $query<br>" .
$connection->error . "<br><br>";
}
What you need to do is , put the password input in the second form tag.like this (the the button name to edit.) :
<form action="admin2.php" method="POST">
<input type="password" name="password" />
......
<input type="submit" name="edit" value="Edit" />
</form>
The admin2.php cannot read the password post because the form not send the password in the post request.
The change the PHP code:
if (isset($_POST["edit"]))
{
if(isset($_POST["username"], $_POST["password"])){
$username = get_post($connection, 'username');
$password = get_post($connection, 'password');
$query = "UPDATE users SET password='$password' WHERE username='$username'";
$result = $connection->query($query);
if (!$result) echo "UPDATE failed: $query<br>" .
$connection->error . "<br><br>";
}
}
Your problem is, you run two form in one php script, so you need to differ which form refer to which PHP code block. If you put 2 form run on one PHP script, with the same names (include the button), then the server will run from the first PHP script that contain the names.

how to return values from mysql table with ajax and php

I am new to programing. I have one form to create Groups. It has two text fields Code Id and Code description. After submitting it showed me that the Code Id which i entered is already exist and if not it add one record in MySQL table. What I want that when I leave the Id text field at the same time with onchange event and Ajax to search table and alert if the Id already exit and at the same time fill name text box with description of that Code Id. How to do that? My code is
HTML file
...
</style>
<body>
<H1>Create Grup</h1>
<br>
<form action="creategrup.php" method="post">
<p>
<label for="codigo">Grup Id:</label>
<input type="text" required="required" autofocus="autofocus"
maxlength="4" name="codigo" id="codigo">
</p>
<p>
<label for="nombre">Grupo description:</label>
<input type="text" required="required" name="nombre" id="nombre"">
</p>
<input type="submit" value="Submit">
</form>
</body>
</html>
And PHP is
<?php
include 'connectdb.php';
$nombre=$_POST['nombre'];
$codigo=$_POST['codigo'];
$sql = "select codigogrupo,nombregrupo from grupo where
codigogrupo='$codigo'";
$query = mysqli_query($conn, $sql);
if (mysqli_num_rows($query) >0) {
echo "<p><h1><b>Grup Id $codigo allready exist....</h1></b></p><br>";
echo "<a href='creategrup.html'>Go Back</a>";
}
else {
mysqli_query($conn, "insert into grupo(codigogrupo,nombregrupo)
values('$codigo','$nombre')");
if(mysqli_affected_rows($conn)>0){
echo "<p><h1><b>Grup $nombre added</h1></b></p>";
echo "<a href='creategrup.html'>Go Back</a>";
} else {
echo "Grup not added<br>";
echo mysqli_error ($conn);
}
}
?>
Connectdb.php
<?php
$servername = "server name";
$username = "user name";
$password = "password";
$dbname = "database";
// Create connection
$conn = mysqli_connect($servername, $username, $password,$dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// echo "Connected successfully";
?>
Please help me.
You are getting already exist message so that may be confirm that there is another data with same id. For further assistance please knock me

Save input into database

Hello guys i need some help.I connected to database from server and can insert some info like $sql = "INSERT INTO Posts (Text_Post) VALUES ('Sample Text')";. Now I want to save on click text from <input type="text" /> to database. Can you tell me what i am doing wrong.
<?php
$servername = "google.com";
$username = "google";
$password = "google";
$dbname = "google";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['Submit'])) {
$sql = "INSERT INTO Posts (Text_Post) VALUES ('".$_POST['text']."')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>anonim</title>
</head>
<body>
<form name="form" action="" method="post">
<input type="text" name="text" id="text" value="Salut" /=>
<input type="submit" id="Submit" />
</form>
</body>
</html>
You're missing the name tag on your submit. When data is POST'ed to the server, it uses the name tag.
<input type="submit" id="submit" name="Submit">
Remember to watch your Capitals also - (since you're checking if Submit is SET then you need to POST the submit).
You could just do:
if(isset($_POST['text'])) {
Also, going off the comments: I'd suggest taking a look at this link because you're prone to SQL Injections.
when we are going to post a form using POST or GET. we should always give name to all our fieds so we get get them just using $_POST['name'] or $_GET['name']. In Your case just give a name to your submit tag and check whether data is submitted or not.
replace
<input type="submit" id="Submit" />
with
<input type="submit" id="submit" name="submit">
and check it like
if(isset($_POST['submit'])) {// it will only check where form is posted or not
// your code...
}

Why can't I "INSERT INTO" my table through my php script?

I have two different directories on my wampserver, this code works on one, but not on the other, I don't understand why.
PHP
<?php
error_reporting(E_ALL & ~E_NOTICE);
session_start();
$msg = "";
if (!isset($_SESSION['username'])) {
header('Location: login.php');
die();
}
if(isset($_SESSION['username'])) {
if (isset($_POST['submit']))
{
$className = $_POST['className'];
$classColour = $_POST['classColour'];
include_once("connection.php");
$sql = "INSERT INTO class (className, classColour) VALUE ('$className', '$classColour')";
mysqli_query($dbConnection, $sql);
$msg = "New class '" . $className . "' added.";
} else {
$msg = "No class added yet.";
}
}
?>
HTML
<form method="post" action="add_class.php">
<input type="text" name="className" placeholder="Class" />
<input type="text" name="classColour" placeholder="Colour" />
<div><input type="submit" name="submit" value="Add" class="btn butn-orange"/></div>
</form>
This is in the file "add_class.php" and I've tried many different things, putting single quotes (`) around the table columns in the $sql but still, it won't work. I've tried adjusting the names in the table, which had underscores but now have camelCasing, still made no difference. This code works perfectly in another directory, can someone please tell me why this is happening and possibly propose a solution? Thank you in advance.
P.S My connection works because I inserted a new row via phpmyadmin and looped through the database printing every existing "className" and it worked, I just can't insert from the php script.
connection.php
<?php
$dbConnection = mysqli_connect("localhost","root", "", "main");
if(mysqli_connect_errno())
{
echo "Failed to connect" . mysqli_connect_error();
}
?>
When asked if you've had assigned the sessions, you replied I assigned this when the user logs in. Moving forward from that, let's assume the assigned session as one written below:
<?php
error_reporting(E_ALL & ~E_NOTICE);
session_start();
$_SESSION['username'] = "HawqasKaPujaari";
$msg = "";
// this fails, as session is already set.
if (!isset($_SESSION['username'])) {
header('Location: login.php');
die();
}
if(isset($_SESSION['username'])) {
if (isset($_POST['submit']))
{
$className = $_POST['className'];
$classColour = $_POST['classColour'];
include_once("connection.php");
$sql = "INSERT INTO class (className, classColour) VALUES ('$className', '$classColour')";
mysqli_query($dbConnection, $sql);
echo $msg = "New class '" . $className . "' added.";
} else {
$msg = "No class added yet.";
}
}
?>
<form method="post" action="">
<input type="text" name="className" placeholder="Class" />
<input type="text" name="classColour" placeholder="Colour" />
<div><input type="submit" name="submit" value="Add" class="btn butn-orange"/></div>
</form>
Note: The only changes I made were to change the action="" empty and changed VALUE to VALUES in your query.
connection.php:
<?php
$dbConnection = mysqli_connect("localhost","root", "", "main");
if(mysqli_connect_errno())
{
echo "Failed to connect" . mysqli_connect_error();
}
?>
As the above posted code seemed to be correct and was bugging me so I thought of testing it myself by creating the database/tables and it seemed to work properly without any errors. I have posted the relevant pictures below:
Note: Make sure you have the connection.php file in the same
directory as the add_class.php.

Display user name in a page

I have an input text area where the user enter his name and i want his name to be shown in another page.
This is what i've tried so far:
HTML of the form:
<html>
<form method="post" name="input" action="name.php" >
Name:<br/>
<input name="user" type="text"/><br/>
<input type="submit" name="Submit" value="insert" />
</form>
name.php
<?php
mysql_connect("localhost", "root", "root") or die("Connection Failed");
mysql_select_db("user")or die("Connection Failed");
session_start();
$_SESSION['user'] = $_POST['user'];
$user = $_POST['user'];
$query = "INSERT INTO test(user)VALUES('$user')";
if(mysql_query($query)){
echo "inserted";}
else{
echo "fail";}
?>
and the page where i want the name to be shown:
<?php
$connection = mysql_connect('localhost', 'root', 'root');
mysql_select_db('user');
echo $user;
mysql_close();
?>
Thanks in advance
Before printing the value for $user with echo $user;, you've to fetch its value either from database with a SELECT query or from the SESSION Right now you're opening a connection to the database on the page where you want to print $user but are not fetching data from the table. $user has no value assigned here.
You haven't done anything to populate the $user variable in the final page.
You need to make an SQL query or read some form data.
(You also need to defend against XSS attacks)

Categories