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();
?>
Related
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";
}
}
?>
Hey guys I have created A delete page, It does not work when I just submit the form and the URL is http://localhost/delete-session.php but once I change the URL to http://localhost/delete-session.php?id=1 it works, What am I missing In my code to make it work?
<h1>Delete Page</h1>
<h3>Enter the booking number of the session you would like to delete!</h3>
<form action ="delete-session.php" method="post">
Booking ID:(Refer To Database):<input type="text" name="booking">
This is the php
if(isset($_GET['booking'])){
$id=$_GET['booking'];
if(!is_numeric($id)){
echo "sorry, there appears to have been an error.";
exit;
}
} else {
echo "sorry, there appears to have been an error.";
exit;
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "olympics";
$conn = mysqli_connect($servername, $username, $password, $dbname);
$id=$_GET['id'];
if(!is_numeric($id)){
echo "Sorry, there is an error";
exit;
}
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql="DELETE from olympiics where booking='$id'";
echo $sql;
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
I'm going to take a crack at this.
I'm guessing it's because when you go to http://localhost/delete-session.php?id=1 you're passing the id=1 via GET, so when you retrieve the GET input from in your code it succeeds with $id=1, but in your HTML your form is send via POST.
As a fix try using $id=$_POST['booking'];
Bench test your code.
It starts getting $id=$_GET['booking']; which does not exist because you have set the method="post" in your <form> tag.
So use $id=$_POST['booking'];
Then later on it does $id=$_GET['id']; overwriting the value you already attempted to get from above.
This would explain why it requires the extra id paramter on http://localhost/delete-session.php?id=1 as using the querystring to send data will send the id parameter in the $_GET['id'] array, and I dont see why you would want to do this anyway as it has been done at the top of your code by getting this id value from $id=$_POST['booking']
It also makes code so much easier to read and more importantly debug if you adopt an indentation standard in your script like below.
Try this out for size, without adding the id=1 to the querystring
if(isset($_POST['booking'])){
$id=$_POST['booking'];
if(!is_numeric($id)){
echo "sorry, there appears to have been an error. Booking must be numeric";
exit;
}
} else {
echo "sorry, there appears to have been an error.";
exit;
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "olympics";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql="DELETE from olympiics where booking='$id'";
$res = mysqli_query($conn, $sql);
if ($res !== FALSE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
As you are using the mysqli extension, you should also be using parameterized queries to prevent SQL Injection.
if(isset($_POST['booking'])){
$id=$_POST['booking'];
if(!is_numeric($id)){
echo "sorry, there appears to have been an error. Booking must be numeric";
exit;
}
} else {
echo "sorry, there appears to have been an error.";
exit;
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "olympics";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql="DELETE from olympiics where booking=?";
$stmt = mysqli_prepare($conn, $sql);
if ( $stmt === FALSE ) {
echo mysqli_error($conn);
exit;
}
mysqli_stmt_bind_param($stmt, 'i', $id);
$res = mysqli_stmt_execute($stmt);
if ($res !== FALSE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
Change form method to get, or use $_REQUEST instead of $_GET
I have a script that updates/creates user from an iOS device. Now i want to have the script also check if the user already exists in the database. I am going to restrict this to username for now, so no more than ONE unique username may exist. I have an if-statement in my PHP but i cannot get it to work - help please :).
<?php
header('Content-type: application/json');
if($_POST) {
$username = $_POST['username'];
$password = $_POST['password'];
if($username && $password) {
$db_name = 'dbname';
$db_user = 'dbuser';
$db_password = 'dbpass';
$server_url = 'localhost';
$mysqli = new mysqli('localhost', $db_user, $db_password, $db_name);
$userexists = mysql_query("SELECT * FROM users WHERE username='$username'");
/* check connection */
if (mysqli_connect_errno()) {
error_log("Connect failed: " . mysqli_connect_error());
echo '{"success":0,"error_message":"' . mysqli_connect_error() . '"}';
}
if(mysql_num_rows($userexists) != 0) {
echo '{"success":0,"error_message":"Username Exist."}';
}
else {
$stmt = $mysqli->prepare("INSERT INTO users (username, password, email) VALUES (?, ?, ?)");
$password = md5($password);
$stmt->bind_param('sss', $username, $password, $email);
/* execute prepared statement */
$stmt->execute();
if ($stmt->error) {error_log("Error: " . $stmt->error); }
$success = $stmt->affected_rows;
/* close statement and connection */
$stmt->close();
/* close connection */
$mysqli->close();
error_log("Success: $success");
if ($success > 0) {
error_log("User '$username' created.");
echo '{"success":1}';
}
else {
echo '{"success":0,"error_message":"Username Exist."}';
}
}
}
else {
echo '{"success":0,"error_message":"Passwords does not match."}';
}
}
else {
echo '{"success":0,"error_message":"Invalid Username."}';
}
}
else {
echo '{"success":0,"error_message":"Invalid Data."}';
}
?>
You could SELECTthe table before trying to insert username. If it already exists (= you have a result) you dont simply insert.
Better yet, use ON DUPLICATE IGNORE or something like that.
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;
}
?>
I am creating a website where it sends values from a JavaScript object into a MySQL database via PHP
Here is the code:
<!DOCTYPE html>
<html>
<body>
<p>Creating a JavaScript Object.</p>
<p id="demo"></p>
<script>
var person = {
firstName : "John",
lastName : "Doe",
age : 50,
eyeColor : "blue"
};
</script>
</body>
</html>
Overall, my question is how to send the objects data to the MySQL using PHP?
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
If I type the code in before it prints out:
connect_error) {die("Connection failed: " . $conn->connect_error);} echo "Connected successfully";?>
It sounds to me like you are trying to jump from not knowing how to work with PHP and MySQL to also adding JavaScript.
First let me give you an example of how to work with all of those things.
Here is the repo with all of these files: https://github.com/Goddard/simplelogin-example.
This is what connects you to the database:
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
define("__DB_NAME__", 'job');
define("__DB_DSN__", 'mysql:dbname=' . __DB_NAME__ . ';host=127.0.0.1');
define("__DB_USERNAME__", 'root');
define("__DB_PASSWORD__", '');
if(session_id() == '') {
session_start();
}
if(!isset($_SESSION['username']))
{
$_SESSION['username'] = NULL;
}
//database setup
try {
$db = new PDO ( __DB_DSN__, __DB_USERNAME__, __DB_PASSWORD__ );
$db->query ( "use " . __DB_NAME__);
}
catch ( PDOException $e ) {
echo 'Could not connect : ' . $e->getMessage ();
}
?>
This is what works with the database information:
<?php
include("db.php");
if(trim(htmlentities(addslashes(filter_input(INPUT_GET, 'type')), ENT_QUOTES)) === "loginUser")
{
try {
$username = trim(filter_input(INPUT_GET, 'username'));
$password = trim(filter_input(INPUT_GET, 'password'));
$fetch = $db->prepare("SELECT * FROM `users` WHERE user_name = :username");
$fetch->bindParam(':username', $username, PDO::PARAM_STR);
$fetch->execute();
$result = $fetch->fetch(PDO::FETCH_OBJ);
if($result)
{
if(password_verify($password, $result->password_hash))
{
$currentDateTime = date('Y-m-d H:i:s');
$update = $db->prepare("UPDATE `users` SET `last_login` = :lastlogin WHERE `client_id` = :clientid");
$update->bindParam(':lastlogin', $currentDateTime);
$update->bindParam(':clientid', $result->client_id);
$loginUpdate = $update->execute();
$resultArray['error'] = 0;
$resultArray['errorMessage'] = "None";
$resultArray['userName'] = $result->user_name;
$_SESSION['username'] = $result->user_name;
echo json_encode($resultArray);
}
else
{
$resultArray['error'] = 1;
$resultArray['errorMessage'] = "Incorrect Password";
echo json_encode($resultArray);
}
}
else
{
$resultArray['error'] = 1;
$resultArray['errorMessage'] = "Incorrect Username";
echo json_encode($resultArray);
}
} catch (PDOException $e) {
$resultArray['error'] = 1;
$resultArray['errorMessage'] = $e->getMessage();
echo json_encode($resultArray);
}
}