table not get updated after clicking update link - php

I'm new to PHP, trying to update table in php when i clicked on update link it show message "Not Updated".where i went wrong?
following is the code which is executed when update link is clicked.
<?php
$servername='localhost';
$username='root';
$password='';
$dbname = "registration";
$conn=mysqli_connect($servername,$username,$password,$dbname);
$sql= 'UPDATE members_t SET Fname =$_POST[FIRSTNAME], Lname
=$_POST[LASTNAME], Memail = $_POST[EMAIL],Mcontact = $_POST[CONTACT],Mwhtap
= $_POST[WHATSAPP], Maddress = $_POST[ADDRESS], Mprofession =
$_POST[PROFESSION], WHERE id= $_POST[id]';
if(mysqli_query($conn, $sql))
header("refresh:1; url=up.php");
else
echo "Not Updated";
?>

Please execute the following script :
<?php
$servername="localhost";
$username="root";
$password="";
$dbname = "registration";
$conn=mysqli_connect($servername,$username,$password,$dbname);
if (!$conn){
die("Connection failed: " . mysqli_connect_error());
}
$firstName = $_POST["FIRSTNAME"];
$lastName = $_POST["LASTNAME"];
$email = $_POST["EMAIL"];
$contact = $_POST["CONTACT"];
$whatsapp = $_POST["WHATSAPP"];
$address = $_POST["ADDRESS"];
$profession = $_POST["PROFESSION"];
$id = $_POST["id"];
$sql= "UPDATE `members_t` SET `FIRSTNAME` = '$firstName',`LASTNAME` = '$lastName',`EMAIL` = '$email' ,`CONTACT` = $contact,`WHATSAPP` = $whatsapp, `ADDRESS` = '$address', `PROFESSION` = '$profession' WHERE id = $id";
if(mysqli_query($conn, $sql)){
header("refresh:1; url=up.php");
}else{
echo "Not Updated";
}
?>
If any error occurs then execute the sql statement in phpmyadmin or MySQL Workbench and share the error thrown(if any).
You have created a Table with the following column names : FIRSTNAME, LASTNAME , EMAIL, CONTACT, WHATSAPP,ADDRESS,PROFESSION but you're using Fname,Lname,Memail,Mcontact and so on. Also your create table query is not correct , theres a syntax error :
CREATE TABLE MEMBERS_T(id INT(6) NOT NULL PRIMARY KEY AUTO_INCREMENT, FIRSTNAME VARCHAR(30), LASTNAME VARCHAR(30), EMAIL VARCHAR(30), CONTACT INT(20), WHATSAPP INT(20), ADDRESS VARCHAR(50), PROFESSION VARCHAR(30));
The code has been updated according to your table and should work.

Related

Why MySQL database not update when I update something in PHP?

I've recently setup up a MySQL server and an Apache webserver to test my Mysql Database. But there is a problem. PHP won't update the MySql server, or the MySQL server will not update.
I've even gone back and copied and pasted from W3Schools and this seems to do nothing what so ever. What am I doing wrong?
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "password";
$dbname = "form_acceptance";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "UPDATE MyGuests SET Player_name='Doe' WHERE id=2";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
MySql
CREATE DATABASE form_acceptance;
CREATE TABLE form_acceptance (
PersonID int,
Player_Name varchar(255),
Countries varchar(255),
Username varchar(255),
Level_and_rank varchar(255),
Max_BR varchar(255)
);
INSERT INTO form_acceptance (PersonID, Player_Name, Countries, Username, Level_and_rank, Max_BR)
SELECT 'SayByeBye_exe', 'SayByeBye_exe', 'US', '^GYMP^SayByeBye_exe', '12_Luitenant', '4.7';
select * FROM form_exceptance;
Nothing seems to work. PHP will not update data into MySql. Why not?
Is it maybe because I am using Linux? Or not?
For the query to execute make sure you have at least 2 records in the table
$sql = "UPDATE MyGuests SET Player_name='Doe' WHERE id=2";
if there is no id with value 2 then the query fails so make sure you check that, I don't see anything else wrong except the typing error at last line
There is couple error you are having with your setup. You do not have any MyGuests table so I assume you want to update the form_acceptance table. Then the form_acceptance table doesn't have any id column so either we have to add this or use the PersonID column. Here is the code snippet to fix your issues.
First
Please update your MySQL table creation like this. This will make PersonID as a primary auto incremental column.
CREATE DATABASE form_acceptance;
CREATE TABLE form_acceptance (
PersonID int NOT NULL AUTO_INCREMENT, //Notice we added NOT NULL AUTO_INCREMENT
Player_Name varchar(255),
Countries varchar(255),
Username varchar(255),
Level_and_rank varchar(255),
Max_BR varchar(255),
PRIMARY KEY (`PersonID `)//define PersonId as primary key
);
Second
Insert a few records
INSERT INTO form_acceptance (Player_Name, Countries, Username, Level_and_rank, Max_BR)
Values('Player_Name1', 'US', 'Username`', '12_Luitenant', '4.7'),
('Player_Name2', 'US', 'Username2', '12_Luitenant', '4.7');
select * FROM form_acceptance;//Will show you 2 records having PersonID 1 and 2
Now fix your update query
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "password";
$dbname = "form_acceptance";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "UPDATE form_acceptance SET Player_name='Doe' WHERE PersonID=2";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
This will successfully update the record of the second row where PersonID is 2.

mysqli query duplicating when trying to enter data in two different tables

Hi I have a form where a teacher can create a new school as a user and that teacher's school gets an ID. So I check the database to make sure the id doesn't already exist in the "school" table. If it does I get that school ID so the teacher can create a profile with it. If it doesn't already exist then a new one is created and entered into both the "school" table AND the "users" table for that teacher's school.
It's working fine, only except that every time the form is filled out the data is entered twice, but only in the "USERS" table. In the "school" table it is entered once as it should be.
Can someone tell me why this is happening? I have been looking for weeks.
code:
if(isset($_POST['submit'])){
$name=$_POST['name'];
$name = mysqli_real_escape_string($con,$name);
$lastname=$_POST['lastname'];
$lastname = mysqli_real_escape_string($con,$lastname);
$email=$_POST['email'];
$email = mysqli_real_escape_string($con,$email);
$phone=$_POST['phone'];
$phone = mysqli_real_escape_string($con,$phone);
$school=$_POST['school'];
$school = mysqli_real_escape_string($con,$school);
$address=$_POST['address'];
$address = mysqli_real_escape_string($con,$address);
$region=$_POST['region'];
$region = mysqli_real_escape_string($con,$region);
$state=$_POST['state'];
$state = mysqli_real_escape_string($con,$state);
$zip = $_POST['zip'];
$zip = mysqli_real_escape_string($con,$zip);
$password= $_POST['password'];
$hash = password_hash($password, PASSWORD_BCRYPT);
//GET STATE NAME
$getState = "SELECT state from `states` WHERE id= '$state'";
$stateRes = mysqli_query($con, $getState);
$stateRow = mysqli_fetch_array($stateRes);
$stateName = $stateRow['state'];
//CHECK SCHOOL
$checkSchool = "SELECT school from `schools` WHERE school= '$school'";
$schoolRes = mysqli_query($con, $checkSchool);
$schoolCount = mysqli_num_rows($schoolRes);
if($schoolCount >0){
//if school exist get it's id
$schoolIdSql = "SELECT id from `schools` WHERE school= '$school'";
$schoolIdRes = mysqli_query($con, $schoolIdSql);
$schoolRow = mysqli_fetch_array($schoolIdRes);
$schoolId = $schoolRow['id'];
}else{
//if doesn't exist insert new school
$schoolquery = "INSERT INTO schools (state_id, school) VALUES ('$state','$school')";
$schoolresult = mysqli_query($con, $schoolquery);
//get new school id
$schoolIdSql = "SELECT id from `schools` WHERE school= '$school'";
$schoolIdRes = mysqli_query($con, $schoolIdSql);
$schoolRow = mysqli_fetch_array($schoolIdRes);
$schoolId = $schoolRow['id'];
}
//CHECK USER
$checkUser = "SELECT email from `Users` WHERE email= '$email'";
$userRes = mysqli_query($con, $checkUser);
$userCount = mysqli_num_rows($userRes);
if($userCount >0){
$submitted = "Email is not available";
$invalid = '<input id="email" type="text" name="email" class="form-control is-invalid" required="required" data-error="email is required." data-remote="/validate">';
} else{
$userId = rand(1,9999999);
$check_userId ="select count(*) count from Users where user_id = " . $userId;
while ($row['count'] > 0);
$query = "INSERT INTO Users (id, user_type, name, lastname, email, phone, school, address, state, zip, password, status) VALUES ('$userId','teacher','$name', '$lastname', '$email', '$phone', '$schoolId', '$address', '$stateName', '$zip', '$hash', 'active')";
$result = mysqli_query($con, $query);
if(!$result = $con->query($query)){
die('there was an error running query [' . $con->error . ']');
}else {
header("location: thankyou");
}
}
}
It seems some old artefacts of earlier programming survived:
Maybe this is the new query:
$result = mysqli_query($con, $query);
And maybe this is the old one?
if(!$result = $con->query($query))
Should do the same and be the cause for the duplicate of the insert.

PHP, MySQL input data

I create some table(in MySQL):
create table clients
( clientid int unsigned not null auto_increment primary key,
Name char(50) not null,
SecondName char(50) not null,
address char(100) not null,
City char(30) not null
Email char(100);
I want to input datas(Name,SecondName,address,City,Email) into my database NewClientBase from webpage by filling by customer his personal data, but clientid should be generated by program:
<html>
<?php
...
// short names initialization. Taken from filling external form
$Name=$_POST['Name'];
$SecondName=$_POST['SecondName'];
$Address=$_POST['Address'];
$City=$_POST['City'];
$Email=$_POST['Email'];
$clientid=0;
if (!$Name || !$SecondName || !$Address || !$City || !$Email) {
echo "Not all data completed.<br />"
."Return and try again";
exit;
}
if (!get_magic_quotes_gpc()) {
$Name = addslashes($Name);
$SecondName = addslashes($SecondName);
$Address = addslashes($Address);
$City = addslashes($City);
$Email = doubleval($Email);
}
# $db = new mysqli('localhost', 'root', '********', 'NewClientBase');
$wynik_sprawdzania= mysqli_query($db, $sprawdzanie);
$ile_znalezionych=$wynik_sprawdzania->fetch_row();
$ilosc_pol=$wynik_sprawdzania->field_count;
.....
// a new record with the next number is calculated:
$clientid=$wynik_sprawdzania->fetch_row()+1;
....
and created a new record with this number:
$zapytanie = "insert into clients values ('".$clientid."','".$Name."','".$SecondName."', '".$Address."','".$City."', '".$Email."')";
$wynik = $db->query($zapytanie);
.....
$db->close();
?>
</html>
the problem is:
if (for example) 5th record is generated and input into database like this
$zapytanie = "insert into clients values (5,'".$Name."','".$SecondName."', '".$Address."','".$City."', '".$Email."')";
$wynik = $db->query($zapytanie);
all record is inserted into database correctly.
but if it is inserted like this
$zapytanie = "insert into clients values
('".$clientid."','".$Name."','".$SecondName."', '".$Address."','".$City."', '".$Email."')";
$wynik = $db->query($zapytanie);
($clientid No 5 is calculated programly as shown above) record is not created. Neither '".clientid."' nor '.$clientid.' Can anybody help me? Any solution exists? Thanks
ClientId is defined as Int, not as string. You try to input string. Remove the single quotes on $clientid.
$zapytanie = "insert into clients values
(".$clientid.",'".$Name."','".$SecondName."', '".$Address."','".$City."', '".$Email."')";
$wynik = $db->query($zapytanie);
The variable $clientid should be considered as integer and should not add any quotes.
$zapytanie = "insert into clients values
(".$clientid.",'".$Name."','".$SecondName."', '".$Address."','".$City."', '".$Email."')";
$wynik = $db->query($zapytanie);
Hope this helps

mysqli cannot insert and update query into mysql database [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 6 years ago.
Please find my code below:
<?php
//Insert New User to Database
$username = "root";
$password = "root";
$hostname = "localhost";
$db = "ab-cargo";
$conn = mysqli_connect($hostname, $username, $password, $db);
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$user_id = $_SESSION['namechat'];
$user_email = $_SESSION['emailchat'];
$last_login = $datetime_formatted;
mysqli_query($conn,"INSERT INTO users (`user_id`, `user_email`, last_login, isActive) VALUES ('".$user_id."', '".$user_email."', '".$last_login."', 1)");
mysqli_query($conn,"UPDATE users SET last_login = ".$last_login.", isActive = 1 WHERE `user_email` = ".$user_email."");
?>
Please help me to find what's wrong with mysqli_query because it won't update and insert the data in my database, even though the connection is finely working (I know it because user is able to login).
Edit: Query insert is to input new user data into the database and if the user data is already in the database before, the update query will update last_login time/date only.
You need to prevent MySQL injection with mysqli_real_escape_string. Read up more about this function here.
Use or die mysqli_error($conn) to check for errors in query.
Also, check if each query is successful before proceeding to the next one.
$user_id = mysqli_real_escape_string($conn, $_SESSION['namechat']);
$user_email = mysqli_real_escape_string($conn, $_SESSION['emailchat']);
$last_login = mysqli_real_escape_string($conn, $datetime_formatted);
$query1 = mysqli_query($conn,"INSERT INTO users (`user_id`, `user_email`, last_login, isActive) VALUES ('$user_id', '$user_email', '$last_login', 1)") or die mysqli_error($conn);
if ($query1) $success = 1;
if ($success) $query2 = mysqli_query($conn,"UPDATE users SET last_login = '$last_login', isActive = 1 WHERE `user_email` = '$user_email'");
if ($query2) echo 'User added';
$_SESSION['namechat']= "1";
$_SESSION['emailchat']= "example#gmail.com";
//SET DATE TIME ZONE
date_default_timezone_set("Asia/Calcutta");
$datetime_formatted = date("h:i:sa");
$user_id = $_SESSION['namechat'];
$user_email = $_SESSION['emailchat'];
$last_login = $datetime_formatted;
//HERE INSERT THE DATA INTO USER
$sql = "INSERT INTO users (user_id, user_email, last_login, isActive) VALUES ('$user_id', '$user_email', '$last_login', '1')";
if(mysqli_query($conn,$sql)){
echo "sql inserted successfully";
}
else
{
echo "failed to insert".$sql."<br>".mysqli_error($conn);
}
//HERE UPDATE THE DATA INTO USER
$sql_up ="UPDATE users SET last_login ='$last_login', isActive = '1' WHERE user_email = '$user_email'";
if(mysqli_query($conn, $sql_up)){
echo "Data Updated";
}
else
{
echo "Failed to Updated the data".$sql_up."<br>".mysqli_error($conn);
}

unable to update table specific row

I had been trying many methods to update a specific row in my sql data base named juytdb having table users having colum names username and email. First I tried to connect and connection was successfull,
$localhost = "localhost";
$dbuser = "google";
$dbpass = "";
$dbname = "juytdb";
$connect = mysql_connect($localhost ,$dbuser ,$dbpass);
mysql_select_db($dbname, $connect);
Now while I wanted to update a specific row I used
session_start();
$username = $_SESSION['var']; //acutally users are logged so I just need to add their email
$email = $_POST['email']; //value I got from an inputbox
UPDATE users
SET email='google#gmail.com';
WHERE username='billy';
this does not work, I also tried
$sql = "UPDATE 'users' SET 'email' = '$email' WHERE 'username' = '$username'";
mysql_query($sql);
additionally the default values of email is set to "not added"
You have single quotes where you should have backquotes. Try this:
$sql = "UPDATE `users` SET `email` = '$email' WHERE `username` = '$username'";
Try this:
$sql = "UPDATE users SET email = '".$email."' WHERE username = ".$username;

Categories