Each time i update the database, it create a new row with the new information i was trying to update and a new customerID each time, is there a way to resolve this.
The update query calls two tables Cus_acct_details and cus_register. The query is meant to change cus_email in both tables, and update all the information in cus_acct_details.
PHP
<?php
//$user = $_SESSION["Cus_Email"];
$Cust_ID = $_SESSION["CustomerID"];
if (isset($_POST['Update'])) {
$UpdateFname = $_POST['fname'];
$UpdateLname = $_POST['Lname'];
$UpdateEmail = $_POST['email'];
$UpdatePhone = $_POST['phone'];
}
$sql = $dbc->query("UPDATE Cus_Register, Cus_acc_details
SET Cus_acc_details.CUS_Fname = ' $UpdateFname',
Cus_acc_details.CUS_Lname = ' $UpdateLname',
Cus_acc_details.CUS_Email = ' $UpdateEmail',
Cus_acc_details.Cus_Phone = ' $UpdatePhone',
Cus_Register.CUS_Email = ' $UpdateEmail',
ON Cus_Register.Cus_Email = Cus_acc_details.Cus_Email
WHERE Cus_Register.CustomerID = '$Cust_ID'
");
print_r($_POST);
header('Location: Cus_Account.php');
?>
HTML
<section class="container">
<form id="myform " class="Form" method="post" action="Cus_Account.php?c_id=<?php echo $c_id ?>" accept-charset="utf-8">
<!-- <div id="first">-->
<input type="text" id="fname" name="fname" value="<?php echo $_SESSION['fname']; ?>" required>
<input type="text" id="lname" name="lname" value="<?php echo $_SESSION['lname']; ?>" required>
<input type="text" id="email" name="email" value="<?php echo $_SESSION['Cus_Email']; ?>" required>
<input type="number" id="phone" name="phone" value="<?php echo $_SESSION['phone']; ?>" required>
<input type="submit" name="Update" value="Update">
<br>
</form>
The $cust_id variable was defined earlier on.
Where have a gone wrong.
An UPDATE statement won't insert a new row. There must be an INSERT statement running. (1)
The syntax of the update statement looks wrong to me, I'd expect that to be throwing an error.
The ON clause is used with the JOIN keyword, but the old-school comma operator is used for the join operation. The SET clause should be the last thing before the WHERE clause.
UPDATE Cus_Register
JOIN Cus_acc_details
ON Cus_Register.Cus_Email = Cus_acc_details.Cus_Email
SET Cus_acc_details.CUS_Fname = ?
, Cus_acc_details.CUS_Lname = ?
, Cus_acc_details.CUS_Email = ?
, Cus_acc_details.Cus_Phone = ?
, Cus_Register.CUS_Email = ?
WHERE Cus_Register.CustomerID = ?
It seems odd that there's an extra space in the string literals.
Assigning the return from a ->query() to a variable is a common pattern. But naming that variable $sql is very strange.
The normative pattern is to assign the SQL text (a string) to a variable named $sql, and then referencing the variable
$sql = 'SELECT foo FROM bar ORDER BY foo LIMIT 1';
$result = $dbc->query($sql);
Then check the return from query, to see if it was successful, or if an error occurred. If you're using PDO, you can configure the connection to throw an exception, and handle it in a catch block.
If your code doesn't do that, it's putting it's pinky finger to the corner of its mouth Dr. Evil style and saying "I'm just going to assume it all goes to plan. What?"
Also, the code appears to be vulnerable to SQL Injection. If any potentially unsafe values are included in the SQL text, those values must be properly escaped before they are included.
The preferred pattern is not even include the values in the SQL text, but to use prepared statements with bind placeholders, and supply the values through the placeholders.
https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
(1.) Of course it's possible to define a BEFORE UPDATE and/or an AFTER UPDATE trigger that performs an INSERT. But it's the INSERT statement that inserts the row, even if the firing of the trigger is "caused" by running an UPDATE.
Set CustomerID to be a key and add an ON DUPLIACTE KEY UPDATE clause
Related
I am trying to build an "admin" section of my website. One where I can update customer status on work orders (or tickets if you prefer the term). I have it where I can input an int in a text field and hit submit to DELETE, but I cannot get my addRow function to work. It is not causing an error, which makes me believe that I am not passing my variables correctly.
Here are the forms on admin.php:
<form name="newRow" METHOD="post" ACTION="q.php">
Status of New Entry: <input type="text" value="Open" name="newStatus" /><br>
Type of Maintenance being completed: <input type="text" value="Software Maintenance" name="maintType" /><br>
<input type="submit" value="Add" name="newEntry" />
</form>
<form name="delRow" METHOD="post" ACTION="q.php">
<input type="text" name="deleteID" />
<input type="submit" value="Delete" name="delEntry"/>
</form>
As for my q.php, here is what I have after I connect to my db (which again, I have no problems using the delEntry/delRow section, so I can't see how a connection/mysqli initialization problem would be the issue:
//prepare statements
$addData = $conn->prepare("INSERT INTO $tname (status, mainttype) VALUES (?, ?)");
$addData->bind_param("s,s", $newStatus, $maintType);
$delData = $conn->prepare("DELETE FROM $tname WHERE id=?");
$delData->bind_param("i", $deleteID);
//end prepared statements
//if New Entry Button is pressed
$newStatus = isset($_POST['newStatus'])
? $_POST['newStatus']
: '';
$maintType = isset($_POST['maintType'])
? $_POST['maintType']
: '';
$addData->execute();
if ( false===$addData ) {
die('prepare() failed: ' . htmlspecialchars($mysqli->error));
}
else{
printf("rows inserted: %d\n", $addData->affected_rows);
}
//if Del Entry Button is pressed
if ( isset( $_POST['delEntry'] ) ) {
$deleteID = $_POST['deleteID'];
$delData->execute();
}
$addData->close();
$delData->close();
$conn->close();
?>
my columns are matching according to phpMyAdmin:
$addData = $conn->prepare("INSERT INTO $tname (status, mainttype) VALUES (?, ?)");
status and mainttype (yes 2 t). my ID (primary) is an auto_incriment so I left it out because I don't want to cause any key duplicate errors by accident. It's auto_incriment has been tested and seems to be working fine.
Too make it more fun, I added an echo $newStatus; after my prepared statement execution, and it comes back with the correct value. I appear to be having a problem with the addition of the new row. Still no error being generated.
printf("rows inserted: %d\n", $addData->affected_rows);
returns with 0 rows affected as well.
Simple comma issue. On:
$addData->bind_param("ss", $newStatus, $maintType);
I had it listed as:
$addData->bind_param("s,s", $newStatus, $maintType);
Hello guys im learning php and just started today. I was on yahoo web hosting and learning DB also for the first time. I was able to post a firstName and LastName into the mysql datatbase. But now i want to be able to query the name and be able to display the names which i searched. My php file isnt working and as i am not able to find the name in the database. Please i need help with it and thanks
Below is my code:
<htmL>
<body>
<p><strong>Query database</strong></p>
<form name="form1" method="post" action="backendfile2.php">
<label><br>
<br>
First Name
<input type="text" name="firstname" id="firstname">
</label>
<p>
<label>Last Name
<input type="text" name="lastname" id="lastname">
</label>
</p>
<p> </p>
<input type="submit" value="Submit">
</form>
<p> </p>
</body>
</html>
php file:
<?php
$con=mysqli_connect("mysql","username","password","207_lab");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$firstname = mysqli_real_escape_string($con,$_POST['firstname']);
$lastname = mysqli_real_escape_string($con,$_POST['lastname']);
$result = mysqli_query($con,"SELECT FirstName, LastName FROM User WHERE
FirstName = $firstname, LastName = $lastname");
echo "Name searched = ";
while($row = mysqli_fetch_array($result)) {
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br>";
}
?>
As per your originally posted code/question since you've made an edit.
Use quotes around your variables since they are strings.
FirstName = '$firstname', LastName = '$lastname'
Checking for errors with
or die(mysqli_error($con)) to mysqli_query() which would have triggered it.
You also need to assign it from POST.
$firstname = mysqli_real_escape_string($con,$_POST['firstname']);
$lastname = mysqli_real_escape_string($con,$_POST['lastname']);
plus
WHERE
FirstName = $firstname, LastName = $lastname"
to, using AND and not a comma
WHERE
FirstName = '$firstname' AND LastName = '$lastname'"
Commas are when you use UPDATE table SET column_x = 'var_1', column_y = 'var_2'
Subsequently, you can replace the AND by OR depending on the query's criteria.
Add error reporting to the top of your file(s) which would have given you an Undefined index... warning for both variables.
error_reporting(E_ALL);
ini_set('display_errors', 1);
Sidenote: Error reporting should only be done in staging, and never production.
and your present method is open to SQL injection. Use prepared statements, or PDO with prepared statements.
Check your SQL syntax also - looks like it should be:
WHERE FirstName = '$firstname' AND LastName = '$lastname'
I need help for my web service project where user create an order when submit the order form, Driver get notification with accept or reject the order and when he accept order details list display to him. these all process done with order form submission. my all coding working fine. I don't understand where from get id of current order list. plz give solution. thx
<?php
if(isset($_POST['order_form']))
{
mysql_connect('localhost','root','');
mysql_select_db('live_help');
$user = $_POST['user'];
$password = $_POST['mobile'];
$password = $_POST['address'];
$password = $_POST['order_item'];
$password = $_POST['price'];
$sql= mysql_query("insert into `json_web`(user,mobile,address,order_item,price) values('$user','$mobile','$address','$order_item','$price')");
if($sql)
{
echo 'Value Saved';
}
}
?>
<form name="order_form" action="" method="post">
<input type="text" name="user">
<input type="text" name="mobile">
<input type="text" name="address">
<input type="text" name="order_item">
<input type="text" name="price">
<input type="submit" name="field1" value="Submit" />
</form>
use mysql_insert_id(); to grap the last insert id. Take a look for more information
mysql_insert_id()
Warning:
mysql_* is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
After your mysql_query(); you can do this:
$id = mysql_insert_id();
mysql_insert_id(); retrieves the ID of the last inserted element to the database.
Use mysqli_insert_id() as from documentation
mysqli::$insert_id -- mysqli_insert_id — Returns the auto generated id used in the last query
In order to use mysql_insert_id() you need to add another field into the database table so you can have distinct order id for each order.
Perhaps you already have it, if not, add it:
ALTER TABLE `json_web` ADD order_id INT(10) NOT NULL AUTOINCREMENT;
Then just select from database, use mysql_insert_id()
Cheers
I just got assignment to make html form with php that will store information in mysql database. It is not making table and I can't figure out why. Here is html code(btw I dont care about sql injection becouse this is just for school)
<?php
#$ime = $_POST['ime'];
#$prezime = $_POST['prezime'];
#$email = $_POST['email'];
#$adresa = $_POST['adresa'];
#$misljenje = $_POST['misljenje'];
$conn = mysqli_connect("localhost","root","");
mysqli_query($conn,"create database baza_podataka");
mysqli_select_db($conn,"baza_podataka");
mysqli_query($conn,"create table 'podatci' (id int primary key auto_increment, ime varchar(10), prezime varchar(10), email varchar(20), adresa varchar(20), misljenje varchar(100))");
mysqli_query($conn,"INSTERT INTO `podatci` VALUES ('$ime','$prezime','$email','$adresa','$misljenje')");
?>
and html
<form name="forma" action="obrada.php" method="post">
<label>Ime :</label>
<input type="text" id="ime" size="20"/><br><br>
<label>Prezime :</label>
<input type="text" id="prezime" size="20"/><br><br>
<label>E-mail :</label>
<input type="text" id="email" size="20"/><br><br>
<label>Adresa :</label>
<input type="text" id="adresa" size="40"/><br><br>
<label>Vase misljenje :</label><br><br>
<textarea name="misljenje" id="misljenje"></textarea>
</label><input type="submit" id="submit" name="submit"/>
You have lot of problems..
Remove the error suppression operator. #$ime = $_POST['ime']; Remove the # from all the variables.
You are creating the database each and every time whenever this script is called. [which is totally wrong]
It is INSERT not INSTERT on your query.
You are passing the $_POST parameters directly onto your query which makes you 100% vulnerable to SQL Injection. Switch to Prepared Statements to overcome this.
First of all I don't see a </form> on your HTML code.
Try using $_REQUEST['htmlvariablename'];
ime = $_REQUEST['ime'];
$prezime = $_REQUEST['prezime'];
$email = $_REQUEST['email'];
$adresa = $_REQUEST['adresa'];
$misljenje = $_REQUEST['misljenje'];
...And as stated earlier you are vulnerable to SQL injection.
1) Use INSERT instead of INSTERT
mysqli_query($conn,"INSERT INTO `podatci` VALUES ('$ime','$prezime','$email','$adresa','$misljenje')");
2) Escape all of your data using mysqli_real_escape_string
3) Never use error suppressor on your code #, instead use isset() to check if it is set or not.
$conn = mysqli_connect("localhost","root","");
$ime = isset($_POST['ime']) : mysqli_real_escape_string($conn, $_POST['ime']) ? '';
$prezime = isset($_POST['prezime']) : mysqli_real_escape_string($conn, $_POST['prezime']) ? '';
$email = isset($_POST['email']) : mysqli_real_escape_string($conn, $_POST['email']) ? '';
$adresa = isset($_POST['adresa']) : mysqli_real_escape_string($conn, $_POST['adresa']) ? '';
$misljenje = isset($_POST['misljenje']) : mysqli_real_escape_string($conn, $_POST['misljenje']) ? '';
4) Finally, there is no need to create the database and/or table every load, you should only do it once.
I have a question, I am new to PHP and I have been working on some exercises. The one I am currently working on is to create a simple form that will search a database (first name, last name). The returned results should then be populated into another form. This way, if I want to update the record, all I have to do is change the value of the populated form and hit Update. I have create the database no problem.
The following is the code. (Please don't laugh, I'm very new...I am sure there are much more efficient ways of doing this, but I'm just playing around right now)
Here is the form:
<form action="" method="post">
<strong>Search for name</strong><br>
<label for="fname">First Name</label>
<input type="text" name="fname">
<label for="lname">Last Name</label>
<input type="text" name="lname">
<input type="submit" name="submit" value="Search">
</form>
And here is the PHP:
if( isset( $_POST['submit'] ) ){
$first_name = $_POST['fname'];
$last_name = $_POST['lname'];
if ( $first_name == NULL || $last_name == NULL ) {
echo "please enter search record";
}
else {
$query = "SELECT first_name, last_name FROM formdata WHERE first_name LIKE '%$first_name%' OR last_name LIKE '%$last_name%'";
$result = mysqli_query( $conn, $query );
$result_array = mysqli_fetch_row( $result );
$fname_value = $result_array[0];
$lname_value = $result_array[1];
echo "
<form action='' method='post'>\n
<label for='fname_u'>First Name</label>\n
<input type='text' name='fname_u' value='$fname_value'>\n
<label for='lname_u'>Last Name</label>\n
<input type='text' name='lname_u' value='$lname_value'>\n
<input type='submit' name='update' value='Update'>\n
</form>";
}
}
if( isset( $_POST['update'] ) ) {
$first_name_u = ( $_POST['fname_u'] );
$last_name_u = ( $_POST['lname_u'] );
$query_update = "UPDATE formdata SET first_name = '$first_name_u', last_name = '$last_name_u' WHERE first_name = '$fname_value';";
echo $query_update; // this is just for testing
}
This code seems to work and do what I want, all the way up to when I submit the updated information. I can't figure out how to carry over the value of the $fname_value variable to the if( isset( $_POST['update'] ) ) conditional. I am thinking I can't because they are two different POSTS? I really don't know...I just need to find a way to get value of the retrieved form data and use for the WHERE clause.
Again, I'm very new and just getting my feet wet with this kind of stuff ... Any help would be great
Thanks
I think you have a typo in your code. Your POST data is saved to the variable $first_name, but when you query SQL you are using $first_name_r instead of $first_name.
I'm thinking the typo is the answer, but I have to point out one deadly mistake you've made, and that is that you're piping user-supplied input directly into an SQL query. This opens your code to a slew of malicious attacks called SQL injection attacks. I'm not trying to be preachy, but it's very important that you read and understand that article, especially the part about Mitigation at the bottom.
I would suggest you use something like this instead:
$query = 'SELECT first_name, last_name '.
'FROM formdata WHERE first_name LIKE ? OR last_name LIKE ?;';
$sth = mysqli_prepare($dbh, $query);
mysqli_stmt_bind_param($sth, "s", '%'.$first_name.'%');
mysqli_stmt_bind_param($sth, "s", '%'.$last_name.'%');
$result = mysqli_execute($sth);
I know it's a bit longer and more complicated, but trust me, it will save you a world of headache. The sooner you learn about this and get it deeply ingrained in your psyche that you can never, ever, ever write a query that passes unsanitized input straight to the database, the happier we all will be (and the longer you will get to keep your job eventually. ;).
Sorry if I'm coming on strong, but in my opinion, the single most important lesson you need to pick up early in developing database-driven web sites is that you really need to be proficient at spotting injection vulnerabilities to the point where it's automatic and when you see it, you think, "Ooh! Noooo! Don't do that!!!"
Above answer found your isssue, but on a sidenote:
$first_name = $_POST['fname'];
$last_name = $_POST['lname'];
Do not do this. That my friend is the most common security vulnerability for php applications.
The most 2 most important things to remember when scripting is
Filter input, and
2: Escape output.
See this write-up for more details ..
In your case, the input values are not filtered, or checked for malicious/improper values.
Here is another primer on this page to see a few tips and how to address filtering.
Keep it up, those exercises are a fine way of picking up chops.
Happy coding friend.
Okay, re-reading your post, I think I see what you're trying to do and where you're having difficulty. Normally, you won't have two separate pages for one identical form like this. Typically, you'll code it more along these lines, and please keep in mind that I'm winging this off the top of my head, not actually testing it, so minor corrections and/or tweakage may be required:
<?php
$fname_value = '';
$lname_value = '';
if (isset($_POST['submit']) && $_POST['submit'] === 'Search') {
if (isset($_POST['fname']) && isset($_POST['lname'])) {
// We are processing a submitted form, not displaying a brand new one
// from scratch. Code any post-validation steps.
// Fetch the user information from the database. You'll need to define
// the $host, $user, $password, and $dbname variables above, or
// substitute literal strings with real information in here.
$dbh = new mysqli($host, $user, $password, $dbname);
$sql = 'SELECT first_name, last_name'.
'FROM formdata WHERE first_name LIKE ? OR last_name LIKE ?;';
$sth = $dbh->prepare($sql); // Use parameters to avoid injection!
$sth->bind_param('s', $_POST['fname']);
$sth->bind_param('s', $_POST['lname']);
if ($sth->execute()) {
$result = $sth->get_result();
if (($row = $result->fetch_assoc()) != NULL) {
// Set the default values displayed in the text edit fields.
$fname_value = $row['first_name'];
$lname_value = $row['last_name'];
}
}
// Whatever other processing you want to do if this is a submitted
// form instead of displaying the page from scratch.
}
}
?>
<html>
<body>
<form action="<?= $_SERVER['PHP_SELF'] ?>" method="POST">
<strong>Search for name</strong><br />
<label for="fname">First Name</label>
<input type="text" name="fname" value="<?= htmlentities($fname_value) ?>">
<label for="lname">Last Name</label>
<input type="text" name="lname" value="<?= htmlentities($lname_value) ?>">
<input type="submit" name="submit" value="Search">
</form>
</body>
</html>