Update query not updating records - php

I am totally confused as to why my update query is not updating the records. There are no errors in inspector console. If I run the query in phpmyadmin substituting the vars with actual values it works fine.
I have tried coding the vars like this in query: '".$name."' and also like i have it now. All field names are correct and all values are being passed to php correctly. I would be grateful if someone could point out my error as it is driving me nuts. Many thanks
<?php
$conn = mysqli_connect("localhost","root","","domain");
if($conn === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$id = mysqli_real_escape_string($conn, $_POST['idcon']);
$company = mysqli_real_escape_string($conn, $_POST['companycon']);
$name = mysqli_real_escape_string($conn, $_POST['namecon']);
$email = mysqli_real_escape_string($conn, $_POST['emailcon']);
$phone = mysqli_real_escape_string($conn, _POST['phonecon']);
$fax = mysqli_real_escape_string($conn, $_POST['faxcon']);
$mobile = mysqli_real_escape_string($conn, $_POST['mobilecon']);
$sql = mysqli_query($conn, "UPDATE contact_con SET idcode_con = '$company', name_con = '$name', email_con = '$email', phone_con = '$phone', fax_con = '$fax', mobile_con = '$mobile' WHERE id_con='$id'");
mysqli_close($conn);
?>

You should be using prepared queries, also you have a typo _POST['phonecon'].
<?php
$conn = mysqli_connect("localhost", "root", "", "domain");
// check connection
if (mysqli_connect_errno()) {
exit("Connect failed: ". mysqli_connect_error());
}
// create a prepared statement
$stmt = $conn->prepare("
UPDATE contact_con
SET idcode_con = ?,
name_con = ?,
email_con = ?,
phone_con = ?,
fax_con = ?,
mobile_con = ?
WHERE id_con= ?
");
if ($stmt) {
// bind parameters for markers
$stmt->bind_param(
"ssssssi",
$_POST['companycon'],
$_POST['namecon'],
$_POST['emailcon'],
$_POST['phonecon'],
$_POST['faxcon'],
$_POST['mobilecon'],
$_POST['idcon']
);
// execute query
$stmt->execute();
// close statement
$stmt->close();
}
// close connection
$conn->close();
?>

Related

PHP: Taking the last row's id number from one mysql table and using it to update a field in the first row of another table

I'm trying to put the 'id' field value of the last row from users_data table to into the first row of the field_num field of the field_numbers table but this is not updating properly. I can verify that $last_id gets set to the most recent id number in the field_numbers table.
The issue with getting the UPDATE line to work near the bottom...
Your help is greatly appreciated!
if ($_SERVER["REQUEST_METHOD"] == "POST") {//Check it is coming from a form
//mysql credentials
$mysql_host = "buythosecarscom.fatcowmysql.com";
$mysql_username = "[secret]";
$mysql_password = "[secret]";
$mysql_database = "buythatcar";
//header("Location: survey_two.html");
$u_q1 = filter_var($_POST["question_1"], FILTER_SANITIZE_STRING); //set PHP variables like this so we can use them anywhere in code below
$u_q2 = filter_var($_POST["question_2"], FILTER_SANITIZE_STRING);
$u_q3 = filter_var($_POST["question_3"], FILTER_SANITIZE_STRING);
$u_q4 = filter_var($_POST["question_4"], FILTER_SANITIZE_STRING);
$u_q4b = filter_var($_POST["question_4b"], FILTER_SANITIZE_STRING);
$u_q5 = filter_var($_POST["question_5"], FILTER_SANITIZE_STRING);
$u_q6 = filter_var($_POST["question_6"], FILTER_SANITIZE_STRING);
$u_q7 = filter_var($_POST["question_7"], FILTER_SANITIZE_STRING);
$u_q8 = filter_var($_POST["question_8"], FILTER_SANITIZE_STRING);
$u_q9 = filter_var($_POST["question_9"], FILTER_SANITIZE_STRING);
$u_q10 = filter_var($_POST["question_10"], FILTER_SANITIZE_STRING);
//Open a new connection to the MySQL server
$mysqli = new mysqli($mysql_host, $mysql_username, $mysql_password, $mysql_database);
//Output any connection error
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
$statement = $mysqli->prepare("INSERT INTO users_data (question_1, question_2, question_3, question_4, question_4b, question_5, question_6, question_7, question_8, question_9, question_10) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); //prepare sql insert query
//bind parameters for markers, where (s = string, i = integer, d = double, b = blob)
$statement->bind_param('sssssssssss', $u_q1, $u_q2, $u_q3, $u_q4, $u_q4b, $u_q5, $u_q6, $u_q7, $u_q8, $u_q9, $u_q10); //bind values and execute insert query
if($statement->execute()){
//This does not work to update the field_num record at id =1 to $last_id's value
$last_id = $mysqli -> insert_id;
$sql = "UPDATE field_numbers SET field_num= '$last_id' WHERE id=1";
//This correctly returns that value of the last_id... so I know it's set right
echo "New record has id: " . $last_id;
print "Hello " . $mysqli-> insert_id . "!, your message has been saved!";
print "Hello $last_id";
}else{
print $mysqli->error; //show mysql error if any
}
}
?>
Looks like you need to execute the $sql query... see the modified code below for how to execute a mysqli sql update query.
<?php
//mysql credentials
$mysql_host = "buythosecarscom.fatcowmysql.com";
$mysql_username = "[secret]";
$mysql_password = "[secret]";
$mysql_database = "buythatcar";
//header("Location: survey_two.html");
$u_q1 = filter_var($_POST["question_1"], FILTER_SANITIZE_STRING); //set PHP variables like this so we can use them anywhere in code below
$u_q2 = filter_var($_POST["question_2"], FILTER_SANITIZE_STRING);
$u_q3 = filter_var($_POST["question_3"], FILTER_SANITIZE_STRING);
$u_q4 = filter_var($_POST["question_4"], FILTER_SANITIZE_STRING);
$u_q4b = filter_var($_POST["question_4b"], FILTER_SANITIZE_STRING);
$u_q5 = filter_var($_POST["question_5"], FILTER_SANITIZE_STRING);
$u_q6 = filter_var($_POST["question_6"], FILTER_SANITIZE_STRING);
$u_q7 = filter_var($_POST["question_7"], FILTER_SANITIZE_STRING);
$u_q8 = filter_var($_POST["question_8"], FILTER_SANITIZE_STRING);
$u_q9 = filter_var($_POST["question_9"], FILTER_SANITIZE_STRING);
$u_q10 = filter_var($_POST["question_10"], FILTER_SANITIZE_STRING);
//Open a new connection to the MySQL server
$mysqli = new mysqli($mysql_host, $mysql_username, $mysql_password, $mysql_database);
//Output any connection error
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
$statement = $mysqli->prepare("INSERT INTO users_data (question_1, question_2, question_3, question_4, question_4b, question_5, question_6, question_7, question_8, question_9, question_10) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); //prepare sql insert query
//bind parameters for markers, where (s = string, i = integer, d = double, b = blob)
$statement->bind_param('sssssssssss', $u_q1, $u_q2, $u_q3, $u_q4, $u_q4b, $u_q5, $u_q6, $u_q7, $u_q8, $u_q9, $u_q10); //bind values and execute insert query
if($statement->execute()){
$last_id = $mysqli -> insert_id;
echo "New record has id: " . $last_id;
print "Hello " . $mysqli-> insert_id . "!, your message has been saved!";
print "Hello $last_id";
$sql = "UPDATE field_numbers SET field_num= '$last_id' WHERE id=1";
if($mysqli->query($sql) === TRUE) {
echo "cool";
}else{
echo "awful: " . $mysqli->error;
}
}else{
print $mysqli->error; //show mysql error if any
}
?>

Having trouble creating a safe way for users to update their data

I am making a way for users to edit their data. My first way I did it worked, but then I remembered that it is very insecure and that I should never insert data directly into the database; at least that's what I was told. I try to make it more secure by doing the VALUES (?,?,?,?,?) thing so that the data is not directly going in, which seemed to work fine in my registration page (which I can include if you want).
To start, here is my original update data page that worked fine but it does not use the (?,?,?,?,?) method:
if(isset($_POST['submit'])) {
$userid=$_SESSION['userid'];
$skype=$_POST['skype'];
$email=$_POST['email'];
$region=$_POST['region'];
$crank=$_POST['league1'];
$drank=$_POST['league2'];
if(empty($skype) || empty($email) || empty($crank) || empty($drank) || empty($region))
{
echo "Cannot leave any field blank";
}
else
{
$host= "localhost";
$dbname = "boost";
$user = "root";
$pwd = "";
$port=3306;
try
{
$mysqli= new mysqli($host, $user, $pwd, $dbname,$port);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}
$query = "UPDATE usertable SET SkypeID = '$skype', Email = '$email', Region = '$region', CRank = '$crank', DRank = '$drank' WHERE UserID = '$userid'";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("sssss",$skype,$email,$region,$crank,$drank);
$stmt->execute();
$iLastInsertId=$mysqli->insert_id;
header('Location: http://localhost/Boost/account.php');
$stmt->close();
$mysqli->close();
} catch (mysqli_sql_exception $e) {
throw $e;
}
}
}
Here is what I tried to do to make it more secure but this doesn't seem to work. Specifically the $query = "UPDATE usertable SET usertable(SkypeID,Email,Region,CRank,DRank) VALUES (?,?,?,?,?) WHERE UserID = '$userid'"; seems to be the issue, though the syntax looks fine to me
if(isset($_POST['submit'])) {
$userid=$_SESSION['userid'];
$skype=$_POST['skype'];
$email=$_POST['email'];
$region=$_POST['region'];
$crank=$_POST['league1'];
$drank=$_POST['league2'];
if(empty($skype) || empty($email) || empty($crank) || empty($drank) || empty($region))
{
echo "Cannot leave any field blank";
}
else
{
$host= "localhost";
$dbname = "boost";
$user = "root";
$pwd = "";
$port=3306;
try
{
$mysqli= new mysqli($host, $user, $pwd, $dbname,$port);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}
$query = "UPDATE usertable SET usertable(SkypeID,Email,Region,CRank,DRank) VALUES (?,?,?,?,?) WHERE UserID = '$userid'";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("sssss",$skype,$email,$region,$crank,$drank);
$stmt->execute();
$iLastInsertId=$mysqli->insert_id;
header('Location: http://localhost/Boost/account.php');
$stmt->close();
$mysqli->close();
} catch (mysqli_sql_exception $e) {
throw $e;
}
}
}
So I am not sure what the problem is. In my experience with PHP, the syntax should be fine but I must be missing something.
It's quite simple actually, you went from
$query = "UPDATE usertable SET SkypeID = '$skype', Email = '$email', Region = '$region', CRank = '$crank', DRank = '$drank' WHERE UserID = '$userid'";
TO
$query = "UPDATE usertable SET usertable(SkypeID,Email,Region,CRank,DRank) VALUES (?,?,?,?,?) WHERE UserID = '$userid'";
It appears you confused an INSERT statement vs. an UPDATE statement when rewriting so to fix you simply use your old statement with the new style...
$query = "UPDATE usertable SET SkypeID = ?, Email = ?, Region = ?, CRank = ?, DRank = ? WHERE UserID = $userid";

MySQL error because of syntax in Custom PHP code

I am trying to enter user's data into a database. I think the commas in the address are causing the error.
<?php
$full_name = $_POST["fullname"];
$email = $_POST["email"];
$password = $_POST["password"];
$full_address = $_POST["address"];
$city = $_POST["city"];
$age = $_POST["age"];
$contact_number = $_POST["number"];
$gender = $_POST["gender"];
$education = $_POST["education"];
?>
<?php
$servername = "hidden";
$username = "hidden";
$password = "hidden";
$dbname = "hidden";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO users (full_name, email, password,full_address,city,age,contact_number,gender,education)
VALUES ($full_name, $email, $password,$full_address,$city,$age,$contact_number,$gender,$education)";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
As others have noted, your code is vulnerable to SQL injections. You should consider using parameterized queries:
$sql = "INSERT INTO users (full_name, email, password, full_address, city, age, contact_number, gender, education)
VALUES (?,?,?,?,?,?,?,?,?)";
$stmt = mysqli_prepare($conn, $sql);
// Bind parameters
$stmt->bind_param("s", $full_name);
$stmt->bind_param("s", $email);
$stmt->bind_param("s", $password);
$stmt->bind_param("s", $full_address);
$stmt->bind_param("s", $city);
$stmt->bind_param("s", $age);
$stmt->bind_param("s", $contact_number);
$stmt->bind_param("s", $gender);
$stmt->bind_param("s", $education);
if ($stmt->execute()) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
For more information refer to the PHP manual on MySQLi prepared statements.
You need to quote string in your SQL statement;
$sql = "INSERT INTO users (full_name, email, password,full_address,city,age,contact_number,gender,education)
VALUES ('$full_name', '$email', '$password','$full_address','$city',$age,'$contact_number','$gender','$education')";
Notice the single quotes around all the variables that contain strings. I might be a bit off because I don't know the values or table structure.
But the just quote all values that are going in to a Date or Text field.
To avoid additional problems and security risks you should be using mysqli_real_escape_string (at a minimum).
In all your assignment statements wrap the values in mysqli_real_escape_string
$full_name = mysqli_real_escape_string($conn, $_POST["fullname"]);
$email = mysqli_real_escape_string($conn, $_POST["email"]);
...
Note this requires setting up your DB connection before the variable assignments, so you'll have to reorganize your code a bit.
rink.attendant.6's answer is the proper way to adapt your code.

PHP, mySQL. saving on more than one different table using php action script

I am working on one php script and would like to insert data to three different tables. How can I do that on php action script.
error_reporting(0);
$datee=$_POST['date'];
$company=$_POST['company'];
$PAddress = $_POST['PAddress'];
$recruiter=$_POST['recruiter'];
$email = $_POST['email'];
$telephone = $_POST['telephone'];
$company=$_POST['company'];
$agents=$_POST['agents'];
$resumes = $_POST['resumes'];
$structure=$_POST['structure'];
$sql = "INSERT INTO job_spec_contact (contact_info_key, datee,company_name,Physical_Address, recruitment_person,email,Telephone)
VALUES('null','$datee','$company','$PAddress','$recruiter','$email','$telephone')";
"INSERT INTO job_company_infor (info_key, company_specialization,no_of_agents,no_of_resumes, org_structure)
VALUES('null','$company','$agents','$resumes','$structure')";
The problem is, it is only saving date on one table.
please assist me as I am new to php.
Thanks in advance.
$link = mysqli_connect("host", "username", "password", "database");
$sql = "INSERT INTO job_spec_contact (contact_info_key, datee,company_name,Physical_Address, recruitment_person,email,Telephone)
VALUES('null','$datee','$company','$PAddress','$recruiter','$email','$telephone') ;";
$sql . = "INSERT INTO job_company_infor (info_key, company_specialization,no_of_agents,no_of_resumes, org_structure)
VALUES('null','$company','$agents','$resumes','$structure')";
mysqli_multi_query($link, $sql);
Sorry for late reply.
If you are using mysql: (Not recommended due to unsecure)
$conn = mysql_connect('localhost','username','password', true, 65536) or die("cannot connect");
mysql_select_db('YourDBName') or die("cannot use database");
if(isset($_POST['Submit'])){
$datee = $_POST['date'];
$company = $_POST['company'];
$PAddress = $_POST['PAddress'];
$recruiter = $_POST['recruiter'];
$email = $_POST['email'];
$telephone = $_POST['telephone'];
$company = $_POST['company'];
$agents = $_POST['agents'];
$resumes = $_POST['resumes'];
$structure = $_POST['structure'];
}
$result = mysql_query("
INSERT INTO job_spec_contact (contact_info_key, datee, company_name, Physical_Address, recruitment_person,email,Telephone)
VALUES('null','$datee','$company','$PAddress','$recruiter','$email','$telephone');
INSERT INTO job_company_infor (info_key, company_specialization,no_of_agents,no_of_resumes, org_structure)
VALUES('null','$company','$agents','$resumes','$structure');
");
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
while ($row = mysql_fetch_assoc($result)) {
echo $row['datee'];
echo $row['company_name'];
......
}
mysql_free_result($result);
?>
If you are using mysqli: (Recommended),
$conn = mysqli_connect('localhost','username','password') or die("cannot connect");
mysqli_select_db($conn, 'YourDBName') or die("cannot use database");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if(isset($_POST['Submit'])){
$datee = $_POST['date'];
$company = $_POST['company'];
$PAddress = $_POST['PAddress'];
$recruiter = $_POST['recruiter'];
$email = $_POST['email'];
$telephone = $_POST['telephone'];
$company = $_POST['company'];
$agents = $_POST['agents'];
$resumes = $_POST['resumes'];
$structure = $_POST['structure'];
}
$query = "INSERT INTO job_spec_contact (contact_info_key, datee, company_name, Physical_Address, recruitment_person, email, Telephone)
VALUES('null','$datee','$company','$PAddress','$recruiter','$email','$telephone')";
$query .= "INSERT INTO job_company_infor (info_key, company_specialization, no_of_agents, no_of_resumes, org_structure)
VALUES('null','$company','$agents','$resumes','$structure')";
if ($mysqli->multi_query($query)) {
do {
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);//test here your values.
//$datee = $row['datee'];
}
$result->free();
}
} while ($mysqli->next_result());
}
/* close connection */
$mysqli->close();
Hope this helps.
Note:
Check always POST is present or not by isset. (assume, input name Submit)
Use MySQLi/PDO instead of MySQL to avoid SQL injection.
Debug code by using echo, print_r, var_dump, etc.,
Try to use field names are in same pattern. For ex, Instead of Physical_Address, use physical_address like other fields. Telephone to telephone. datee to job_contact_date, etc.,
Just execute your queries one by one. And DO NOT write error_reporting(0); or the errors won't show. Plus where is your DB ?
$sql1 = "INSERT INTO job_spec_contact (contact_info_key, datee,company_name,Physical_Address, recruitment_person,email,Telephone)
VALUES('null','$datee','$company','$PAddress','$recruiter','$email','$telephone')";
$sql2 = "INSERT INTO job_company_infor (info_key, company_specialization,no_of_agents,no_of_resumes, org_structure)
VALUES('null','$company','$agents','$resumes','$structure')";
mysqli_query($db,$sql1) or die('error '.$sql1.'<br>'.mysqli_error($db));
mysqli_query($db,$sql2) or die('error '.$sql2.'<br>'.mysqli_error($db));

Trying to insert multiple form data into multiple tables to the database, no error given but not working

When I run my code, I get no errors and nothings being sent to the database as well and I can't seem to figure out what the problem could be here ?
I am new to this forum and mysql and php as well and Im not really sure if this is the right way of inserting the datas when you have multiple tables to fill in
or it could be something to do with the incorrect html input attributes?
$db = mysql_connect($dbhost, $dbusername, $dbpass);
$db_select = mysql_select_db($dbdatabase, $db);
if (!$db_select) {
die ("Unable to select database: " . mysql_error());
}
$query = "SELECT * FROM members, login, skills, indivoffers";
$result = mysql_query($query);
if (isset($_POST['mrmrs'],$_POST['fname'],$_POST['lname'],$_POST['gender'],$_POST['addr1'],
$_POST['addr2'],$_POST['city'],$_POST['postcode'],$_POST['hometel'],$_POST['mobtel'],
$_POST['email'],$_POST['job'],$_POST['user'],$_POST['pass'],$_POST['skill1'],
$_POST['skill2'],$_POST['skill3'],$_POST['skill4'],$_POST['skill5'],$_POST['skill6'],
$_POST['skill7'],$_POST['skill8'],$_POST['skill9'],$_POST['ortitle'],$_POST['message'],
$_POST['offereq'],$_POST['cost'],$_POST['pay'])){
$title = $_POST['mrmrs'];
$name = $_POST['fname'];
$name2 = $_POST['lname'];
$gender = $_POST['gender'];
$address1 = $_POST['addr1'];
$address2 = $_POST['addr2'];
$city = $_POST['city'];
$pc = $_POST['postcode'];
$telhome = $_POST['hometel'];
$telmob = $_POST['mobtel'];
$email = $_POST['email'];
$job = $_POST['job'];
$username = $_POST['user'];
$password = $_POST['pass'];
$skill1 = $_POST['skill1'];
$skill2 = $_POST['skill2'];
$skill3 = $_POST['skill3'];
$skill4 = $_POST['skill4'];
$skill5 = $_POST['skill5'];
$skill6 = $_POST['skill6'];
$skill7 = $_POST['skill7'];
$skill8 = $_POST['skill8'];
$skill9 = $_POST['skill9'];
$titleor = $_POST['ortitle'];
$mess = $_POST['message'];
$offerequest = $_POST['offereq'];
$cost = $_POST['cost'];
$pay = $_POST['pay'];
$sql = "INSERT INTO members (Mr/Mrs, fname, lname, gender, DOB, addr1, addr2, city, postcode, telnohome, telnomob, email, job)
VALUES ('$title','$name','$name2', '$gender', '$address1', '$address2', '$city', '$pc', '$telhome', '$telmob', '$email', '$job')";
$letsid = mysql_insert_id( $db);
$sql = "INSERT INTO login (letsID,username, password)
VALUES (letsID),'$username','$password')";
$letsid = mysql_insert_id( $db);
$sql = "INSERT INTO skills (letsID, skill1, skill2, skill3, skill4, skill5, skill6, skill7, skill8, skill9)
VALUES (letsID,'$skill1', '$skill2', '$skill3', '$skill4', '$skill5', '$skill6', '$skill7', '$skill8','$skill9')";
$letsid = mysql_insert_id( $db);
$sql = "INSERT INTO indivoffers (letsID, title, message, offer/request, cost, pay)
VALUES (letsID,'$titleor','$mess', '$offerequest', '$cost', '$pay')";
$letsid = mysql_insert_id( $db);
}
?>
You are creating the querys correctly but you aren't actually executing them.
So instead of doing <?php $sql = "INSERT INTO ..."; ?> you can do something like this
<?php $sql = mysql_query("INSERT INTO ..."); ?>
Setting the variable to a mysql query will execute the query so therefore this should run your querys now.

Categories