Contactus table schema - php

I have two HTML form in first form i am adding Id and product and second form is contact us form. I have created one table with column name is ID,Product,name,email,mobile.In first form i am adding id and product and rest of values are NULL,than form will redirect to contact us form there i am updating name,email,mobile..I am getting pop is updated successfully but when i checked in database there was no update....please help me
//insert code
<?php
try{
$product=$_POST['product'];
/*
$product2=$_POST['product2'];
$product3=$_POST['product3'];
*/
// form data
//database Connection details
$servername = "localhost";
$username = "root";
$password = "";
$database="store";
$error = "";
$conn=mysql_connect($servername, $username, $password) or die('Connection failed: ' . mysql_error());
#mysql_select_db($database, $conn) or die("Could not select your database".mysql_error());
$insertQuery = "Insert into contactus(Id,Product) values('null','$product')";
$result = mysql_query($insertQuery);
mysql_close($conn);
header('Location: /newstore/contact.html');
}
catch(Exception $e) {
echo ("<script>alert('Something went terribly wrong. Please try again later.');location.href = ''../index.html';</script>");
return false;
}
?>
//Update code
<?php
// Start the session
session_start();
?>
<?php
$_SESSION['user_name1']=$_POST['product'];
try{
// form data
$name=$_POST['name'];
$email=$_POST['email'];
$mobile=$_POST['mobile'];
$product=$_SESSION['user_name1'];
//database Connection details
$servername = "localhost";
$username = "root";
$password = "";
$database="store";
$error = "";
$conn=mysql_connect($servername, $username, $password) or die('Connection failed: ' . mysql_error());
#mysql_select_db($database, $conn) or die("Could not select your database".mysql_error());
;if ((strlen($name) < 3) or (strlen($email) < 3) or(strlen($mobile) < 3))
{
echo ("<script>alert('Something went wrong with your data inserted. Please fill the form again.');location.href = '../newstore/index.html';</script>");
}else
{
//$insertQuery = "Insert into contactus(Id,Name,Email,Mobile,Product) values('null','$name','$email','$mobile','$product')";
//$UpdateQuery = "update contactus set Name='$name',Email='$email',Mobile='$mobile' where Product='$product' ";
$UpdateQuery = "update contactus set Name='".$name."',Email='".$email."',Mobile='".$mobile."' where Product='$product' ";
$result = mysql_query($UpdateQuery);
if($result){
echo "<script>alert('Thank You. Your Data Received Succefully.');location.href = '../newstore/index.html';</script>";
}
else
{
echo "<script>alert('Something went wrong with your data inserted. Please fill the form again.');location.href = '../newstore/index.html';</script>";
}
}
mysql_close($conn);
}
catch(Exception $e) {
echo ("<script>alert('Something went terribly wrong. Please try again later.');location.href = ''../newstore/index.html';</script>");
return false;
}
?>

Related

Php getting id of current user not working

I was trying to make a page where you can log in and then change your nickname or/and password. Everything in mySQL database, but when I try to save the id to session variable, it doesn't work. Any suggestions?
I am using XAMPP, users is my table in database users, I'm not posting login form code, because it's very simple.
Everything is connected, code doesn't give any warnings or errors.
login.php (fragment):
$sql = "SELECT * FROM users WHERE nickname = '$myusername' and pass = '$mypassword' and confirmed = 1";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count == 1) {
$logged = true;
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"];
$_SESSION['currentId'] = $row["id"];
echo 'Id: ' . $_SESSION['currentId'];
}
}else {
$error = "Your Login Name or Password is invalid";
}
}
change.php (whole):
<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "Users";
$currentId = $_SESSION['currentId'];
if($currentId<1){echo 'No Id.';}
else {echo 'CurrentId: ';
echo $currentId;}
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully <br>";
if($_SERVER["REQUEST_METHOD"] == "POST") {
// username and password sent from form
$aCUname = mysqli_real_escape_string($conn,$_POST['CUname']);
$aCUpass = mysqli_real_escape_string($conn,$_POST['CUpass']);
$sql = "UPDATE users SET nickname = '$aCUname', pass = '$aCUpass' WHERE id = '$currentId';";
$result = mysqli_query($conn,$sql);
echo 'Updated successfully.';
}
?>
Thanks for help.
I got a solution. I just had to delete
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
from login.php. Thanks to #Shashikumar Misal !

Logic operation failure in php

I want to do some logic operation before updating the data in MySQL. However, I think there are some problems in my logic operation. I do not know which line causes the problem. Can anyone help?
<?php
session_start();
if ($_POST['meetingid'] > $_SESSION["id"]){
echo "ERROR: Wrong Meeting_ID. Update failed.<br>";
}
else if(empty($_POST['date'])) {
echo "ERROR: No empty data field is allowed. Update failed. (Date field)<br>";
}
else if(empty($POST['committee'])) {
echo "ERROR: No empty data field is allowed. Update failed. (Committee field)<br>";
}
else if(empty($_POST['session'])) {
echo "ERROR: No empty data field is allowed. Update failed. (Session field)<br>";
}
else{
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'admin123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$meetingid = $_POST['meetingid'];
$date = $_POST['date'];
$committee = $_POST['committee'];
$session = $_POST['session'];
$sql = "UPDATE `meeting` SET `Date`='$date' ,`Committee`='$committee' ,`Session`='$session' WHERE `Meeting_ID`='$meetingid'" ;
mysql_select_db('imo resolution v.2');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not update data: ' . mysql_error());
}
else{
echo "Updated data successfully<br>";
}
mysql_close($conn);
}
?>
Here is the code refactored (untested)
Some notes about what has changed:
Changed the initial condition because what would happen if $_POST['meetingid'] was less than $_SESSION['id'] but not equivalent.
Combined the empty() statements together. Your code before would not display correctly if your form had more than 1 empty field.
mysql_ functions are deprecated. Don't use them! Use mysqli_ instead.
Added some basic santisation through mysqli_real_escape_string() function
Removed mysql_select_db() as you can set the database through mysqli_connect()
Updated the code to check whether the INSERT statement was successful
<?php
session_start();
if ($_POST['meetingid'] !== $_SESSION['id']) {
echo 'ERROR: Wrong Meeting ID';
} else if (empty($_POST['date']) || empty($_POST['committee']) || empty($_POST['session'])) {
echo 'Error inserting due to empty field';
print_r($_POST);
} else {
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbdb = 'imo_reslution_v.2';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbdb);
if(! $conn ) {
die('Could not connect: ' . mysqli_error());
}
$meetingid = mysqli_real_escape_string($conn, $_POST['meetingid']);
$date = mysqli_real_escape_string($conn, $_POST['date']);
$committee = mysqli_real_escape_string($conn, $_POST['committee']);
$session = mysqli_real_escape_string($conn, $_POST['session']);
$sql = "UPDATE `meeting` SET `Date`='$date' ,`Committee`='$committee' ,`Session`='$session' WHERE `Meeting_ID`='$meetingid'" ;
$retval = mysqli_query( $sql, $conn );
if( mysqli_infected_rows() == 0 ) {
die('Could not update data: ' . mysqli_error());
}else {
echo "Updated data successfully<br>";
}
mysqli_close($conn);
}
?>
Warning mysql_query, mysql_fetch_array,mysql_connect etc.. extensions were deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0.
Instead, the MySQLi or PDO_MySQL extension should be used.
As per mulqin suggestion (untested)
try to use prepared statement to avoid sql injections
<?php
session_start();
if ($_POST['meetingid'] !== $_SESSION['id']) {
echo 'ERROR: Wrong Meeting ID';
} else if (empty($_POST['date']) || empty($_POST['committee']) || empty($_POST['session'])) {
echo 'Error inserting due to empty field';
print_r($_POST);
} else {
//db connection
global $conn;
$servername = "localhost"; //host name
$username = "root"; //username
$password = "admin123"; //password
//mysqli prepared statement
$conn = mysqli_connect($servername, $username, $password) or die("Connection failed: " . mysqli_connect_error());
mysqli_select_db($conn,`imo_resolution_v.2`) or die("Opps some thing went wrong");
$stmt = $conn->prepare("UPDATE `meeting` SET `Date`=? ,`Committee`=? ,`Session`=? WHERE `Meeting_ID`=? ");
$stmt->bind_param('ssii',$date,$committee,$session,$meetingid);
The argument may be one of four types:
i - integer
d - double
s - string
b - BLOB
//change it by respectively
$stmt->execute();
$row_count= $stmt->affected_rows;
$stmt->close();
$conn->close();
if($row_count>0)
{
echo "Updated data successfully<br>";
}
else
{
echo "Not Updated";
}
}
?>

Every time i refresh page it inserts same user into database

Here is PHP code
<?php
if(isset($_POST['Murad'])){
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$userName=$_POST['username'];
$password=$_POST['pwd1'];
$userName = stripslashes($userName);
$password = stripslashes($password);
$email=$_POST['email'];
$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password = "123";
$mysql_databse = "websiteusers";
$prefix = "";
$bd = mysqli_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Could not connect database");
$sql = "INSERT INTO websiteusers
(fullname,lastname,userName,email,pass)
VALUES ( '$firstname', '$lastname','$userName', '$email','$password')";
mysqli_select_db($bd,'websiteusers');
$retval = mysqli_query($bd,$sql );
if(! $retval )
{
die('Could not enter data: ');
return false;
}
else {echo "Entered data successfully\n";
}
$usernamecheck=mysqli_query($bd,"SELECT `userName` FROM `websiteusers`
WHERE userName='$userName'");
if(mysqli_num_rows($usernamecheck)>=1){
echo $userName." is already taken";
return false;
}header("Location: Main.php");}
?>
User registers then when he is in his profile page as soon as he refreshes it inserts same username again.And also username and email are unique in my dt it cant insert it and gives an error
What you can do is after the form has submitted successfully,
you can reset the form
or
redirect the user to the same page
if(! $retval )
{
die('Could not enter data: ');
return false;
}
else {
echo "Entered data successfully\n";
header("Location:samepagename.php");
}
TO reset the form
this.form.reset();
call this after form has successfully submitted
Try this:
<?php
if(isset($_POST['Murad'])) {
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$userName=$_POST['username'];
$password=$_POST['pwd1'];
$userName = stripslashes($userName);
$password = stripslashes($password);
$email=$_POST['email'];
$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password = "123";
$mysql_databse = "websiteusers";
$prefix = "";
$link = new PDO('mysql:dbhost='.$mysql_hostname.';dbname='.$mysql_database,$mysql_user, $mysql_password);
$unamecheck = ("SELECT userName FROM websiteusers WHERE userName = :uname");
$unamecheck = $link->prepare($unamecheck);
$unamecheck->execute(array(':uname'=>$userName));
if($unamecheck->rowCount() > 0) {
echo "Username taken";
die();
} else {
$add = ("INSERT INTO websiteusers (fullname, lastname, userName, email, pass) VALUES (:fname, :lname, :uname, :pass)");
$add = $link->prepare($add);
$add->execute(array(':fname'=>$firstname, ':lname'=>$lastname, ':uname'=>$userName, ':pass'=>$password));
if($add->rowCount() > 0) {
echo "Registration successful";
header("Location: Main.php");
} else {
echo "Registration failed";
}
}
}
?>
What you are doing right now is you insert a user in the DB and after that you perform a check if the user exists. You'll have to move some code around.
$bd = mysqli_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Could not connect database");
$usernamecheck=mysqli_query($bd,"SELECT `userName` FROM `websiteusers`
WHERE userName='$userName'");
if(mysqli_num_rows($usernamecheck)>=1){
echo $userName." is already taken";
} else {
$sql = "INSERT INTO websiteusers
(fullname,lastname,userName,email,pass)
VALUES ( '$firstname', '$lastname','$userName', '$email','$password')";
mysqli_select_db($bd,'websiteusers');
$retval = mysqli_query($bd,$sql );
if(! $retval )
{
die('Could not enter data: ');
}
else {
echo "Entered data successfully\n";
}
}
}
This way you first check if the user already exists. If does - you kill the script and the code after is not executed. Otherwise you insert a user in the DB

Data already Inserted I want to update the data

I am getting issue in update code.I am able to inserted data in database.I am passing null values in table. I want to update that null values.I am getting the sccessfully message but data is not updating. Please help me....
//Insert code
<?php
// Start the session
session_start();
?>
<?php
// Start the session
session_start();
?>
<?php
try{
$product=$_POST['product'];
/*
$product2=$_POST['product2'];
$product3=$_POST['product3'];
*/
// form data
//database Connection details
$servername = "localhost";
$username = "root";
$password = "";
$database="store";
$error = "";
$conn=mysql_connect($servername, $username, $password) or die('Connection failed: ' . mysql_error());
#mysql_select_db($database, $conn) or die("Could not select your database".mysql_error());
$insertQuery = "Insert into contactus(Id,Product) values('null','$product')";
$result = mysql_query($insertQuery);
if($result){
echo "<script>alert('Thank You. Your Data Received Succefully.');location.href = '../index.html';</script>";
}
else
{
echo "<script>alert('Something went wrong with your data inserted. Please fill the form again.');location.href = '../index.html';</script>";
}
mysql_close($conn);
header('Location: /newstore/contact.html');
}
catch(Exception $e) {
echo ("<script>alert('Something went terribly wrong. Please try again later.');location.href = ''../index.html';</script>");
return false;
}
?>
//Update code
<?php
// Start the session
session_start();
?>
<?php
try{
// form data
$name=$_POST['name'];
$email=$_POST['email'];
$mobile=$_POST['mobile'];
$product=isset($_POST['product']);
//database Connection details
$servername = "localhost";
$username = "root";
$password = "";
$database="store";
$error = "";
$conn=mysql_connect($servername, $username, $password) or die('Connection failed: ' . mysql_error());
#mysql_select_db($database, $conn) or die("Could not select your database".mysql_error());
;if ((strlen($name) < 3) or (strlen($email) < 3) or(strlen($mobile) < 3))
{
echo ("<script>alert('Something went wrong with your data inserted. Please fill the form again.');location.href = '../newstore/index.html';</script>");
}else
{
$UpdateQuery = "update contactus set Name='$name',Email='$email',Mobile='$mobile' where Id='(select count(*) from contactus)' ";
$result = mysql_query($UpdateQuery);
if($result){
echo "<script>alert('Thank You. Your Data Received Succefully.');location.href = '../newstore/index.html';</script>";
}
else
{
echo "<script>alert('Something went wrong with your data inserted. Please fill the form again.');location.href = '../newstore/index.html';</script>";
}
}
mysql_close($conn);
}
catch(Exception $e) {
echo ("<script>alert('Something went terribly wrong. Please try again later.');location.href = ''../newstore/index.html';</script>");
return false;
}
?>
I see no point in doing an Insert and then doing an Update. You already have all the data, so just Insert it all at once.
EDIT AFTER COMMENTS
First Handler:
<?php
start_session();
if(isset($_POST['product'])){
$product=$_POST['product'];
//database Connection details
$servername = "localhost";
$username = "root";
$password = "";
$database="store";
$error = "";
$mysqli = new mysqli($servername, $username, $password, $database);
/* check connection */
if (mysqli_connect_errno()) {
echo "<script>alert('Something went wrong with your data inserted. Please fill the form again. (" . mysqli_connect_error() . ")');location.href = '../newstore/index.html'</script>");
exit();
}
if ($result = $mysqli->query("INSERT INTO contactus (Id,Product) VALUES ('null','$product')")) {
// Grab new ID when INSERT is successfull, add it to Session
$_SESSION['contact_id'] = $mysqli->insert_id;
echo "<script>alert('Thank You. Your Data Received Succefully.');location.href = '../index.html';</script>";
} else {
echo "<script>alert('Something went wrong with your data inserted. Please fill the form again.');location.href = '../index.html';</script>";
$mysqli->close();
exit();
}
$mysqli->close();
}
header('Location: /newstore/contact.html');
?>
Second Handler:
<?php
start_session();
// form data
$name=isset($_POST['name'])?$_POST['name']:"";
$email=isset($_POST['email'])?$_POST['email']:"";
$mobile=$_POST['mobile'];
if ((strlen($name) < 3) || (strlen($email) < 3) || (strlen($mobile) < 3)){
echo "<script>alert('Something went wrong with your data inserted. Please fill the form again.');location.href = '../newstore/index.html';</script>";
exit();
}
//database Connection details
$servername = "localhost";
$username = "root";
$password = "";
$database="store";
$error = "";
$mysqli = new mysqli($servername, $username, $password, $database);
/* check connection */
if (mysqli_connect_errno()) {
echo "<script>alert('Something went wrong with your data inserted. Please fill the form again. (" . mysqli_connect_error() . ")');location.href = '../newstore/index.html'</script>");
exit();
}
if ($stmt = $mysqli->prepare("UPDATE contactus SET `Name`=?, `Email`=?, `Mobile`=?) WHERE `ID`=?")){
/* bind parameters for markers */
$stmt->bind_param("sssi", $name, $email, $mobile, $_SESSION['contact_id']);
/* execute query */
$stmt->execute();
$result = $stmt->get_result();
if($result){
echo "<script>alert('Thank You. Your Data Received Succefully.');location.href = '../newstore/index.html';</script>";
} else {
echo "<script>alert('Something went wrong with your data inserted. Please fill the form again.');location.href = '../newstore/index.html';</script>";
}
$stmt->close();
}
$mysqli->close();
?>

ADMIN panel doesn't operate

This is my admin panel for Add and Delete users from the members table in my database but when I press OK it doesn't operate:
I don't know where the problem is.
I'm not pro in PHP so please provide easy to understand answers.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$user="admin";
$pass="whatever";
$host="localhost";
$db_name="login";
$con=mysqli_connect($host, $user, $pass, $db_name);
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = ($_POST['id']);
$password = md5($_POST['pass']);
$fieldset = ($_POST['fieldset']);
$id = mysqli_real_escape_string($con,$password);
$password = mysqli_real_escape_string($con,$password);
$fieldset = mysqli_real_escape_string($con,$fieldset);
if ($fieldset == "add") {
$sqlcommand="INSERT INTO members (student_id,student_pass) VALUES ('$id','$password')";
} elseif (fieldset == "delete") {
$sqlcommand="DELETE FROM members WHERE student_id LIKE '$id'";
} else {
echo "Your information is incorrect";
}
}
?>
I would guess that the error would be here
$id = mysqli_real_escape_string($con,$password); // <<<<<<
$password = mysqli_real_escape_string($con,$password);
$fieldset = mysqli_real_escape_string($con,$fieldset);
I guess that's supposed to be
$id = mysqli_real_escape_string($con,$id);
And also you're not running any queries, as another person said, you're just setting up SQLs. Basically your script should look like
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$user="admin";
$pass="whatever";
$host="localhost";
$db_name="login";
$con=mysqli_connect($host, $user, $pass, $db_name);
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = ($_POST['id']);
$password = md5($_POST['pass']);
$fieldset = ($_POST['fieldset']);
$id = mysqli_real_escape_string($con,$id);
$password = mysqli_real_escape_string($con,$password);
$fieldset = mysqli_real_escape_string($con,$fieldset);
if ($fieldset == "add") {
$sqlcommand="INSERT INTO members (student_id,student_pass) VALUES ('$id','$password')";
} elseif (fieldset == "delete") {
$sqlcommand="DELETE FROM members WHERE student_id LIKE '$id'";
} else {
$sqlcomand='';
echo "Your information is incorrect";
}
mysqli_query($con,$sqlcommand);
}
You're not actually executing the SQL query anywhere. You need to run mysqli_query($con,$sqlcommand); somewhere.
You are not executing the query; use mysql_query($sql);
Hope it will help you :)

Categories