After writing a whole lot of much more complicated code that works beautifully, THIS is the code that is giving me issues.
Simple form
<form action="res/scripts/editsubscriber.php" method="post">
<label for="name">Name: </label>
<input name="name" type="text" value="<?php echo $name; ?>">
...etc, etc...
</form>
Submits to this script:
include('appvars.php');
if(isset($_POST['submit'])){
$id = $_POST['id'];
$name = $_POST['name'];
$email = $_POST['email'];
$month = $_POST['month'];
$day = $_POST['day'];
$year = $_POST['year'];
$date = $_POST['date'];
$time = substr($date, 0, (stripos($date, " ")+1));
$time = str_replace($time, '', $date);
$created = $year.'-'.$month.'-'.$day.' '.$time;
$query = "UPDATE newslettersubscribers SET name = '$name', email = '$email', created = '$created' WHERE id = $id)";
mysqli_query($dbc, $query);
}
It posts, I've echoed all of the variables, they change just fine, but it still won't update the database. Someone please tell me what i'm missing...
remove extra ) on your update statement
read article to avoid SQL Injection
Best way to prevent SQL injection in PHP?
You got a strange trailing ) in your SQL query. Have you executed it in a SQL client ?
Do you have an ID form input?
<input name="id" type="text" value="<?php echo $id; ?>">
Also, you're not escaping sql/html.
This code will compromise your database's security severely. Since none of the parameters are sanitized before being included in the query, anyone with basic security knowledge can take over your application in seconds.
To address the security issues and your bug, you may want to look into
http://php.net/manual/en/pdo.prepared-statements.php
Related
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
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.
When I type don't, it save don\'t to database. I tested the code on wamp offline server and it save don't. But when I test the code on online hosting, it save don\'t. How to make online hosting don't use excape string?
Codes :
<?php
if (isset($_POST['btn_edit'])) {
$description = $_POST['description'];
}
$sql = "UPDATE expense
SET description=?
WHERE spender_id=?";
$q = $conn->prepare($sql);
$result = $q->execute(array($description, $_SESSION['user_id']));
?>
<input type="text" name="description" size="70" value="" />
Sounds like your host has Magic Quotes activated. See the manual on how to disable them: http://php.net/magic_quotes
disable magic_qoutes or change this statement
$description = $_POST['description'];
as
$description = stripslashes($_POST['description']);
In one of my scripts, the php $_POST is declaring properly into a variable. When I echo the variable, it displays correctly, however, when I check the database it does not insert correctly. It appears blank. So my guess is that it isn't a problem with the variable, because it is being called back properly. I do not know what the problem is when it inserts.
If needed this is a twilio app, so the application is pulling the recording url from the twilio app, and I am passing a value from the form in which you record. I am just stating this for those who are familiar with twilio Apps.
$sayid = $_SESSION['id'];
$hearid = "01";
$sayurl = $_REQUEST['RecordingUrl'];
$topic = $_POST['topic'];
mysql_query("INSERT INTO says (say, hear, sid, time_sent, happy)
VALUES('$sayid', '$hearid', '$sayurl.mp3', now(), '$topic' )");
echo $topic;
I am open to suggestions, I will try them, and tell you if they work or now.
EDIT if I change the vaiable $topic to = "whatever" it will post "whatever" to the database properly, but once I change it to $_POST['topic'] it begins to post a blank value again. But If I echo $topic anywhere it will post the correct $_POST value
EDIT #2 okay new update, so I changed the variable declaring to $sayid = "20"; $hearid = "01"; $topic = $_POST['topic']; $sayurl = $_REQUEST['RecordingUrl']; instead of $sayid = "20"; $hearid = "01"; $sayurl = $_REQUEST['RecordingUrl']; $topic = $_POST['topic']; and I am now getting an output of the php script CREATING 2 NEW RECORDS, one of them has everything on it except for the $topic, and the other has just the $topic, so they are apparently posting all fields, but in two different rows! lol wow what the hell is going on
Use:
$sayid = mysql_real_escape_string($_SESSION['id']);
$hearid = "01";
$sayurl = mysql_real_escape_string($_REQUEST['RecordingUrl']);
$topic = mysql_real_escape_string($_POST['topic']);
$topic2 = mysql_real_escape_string($_POST['topic']);
$query = "INSERT INTO says
(say, hear, sid, time_sent, happy, sad)
VALUES
('$sayid', '$hearid', '$sayurl.mp3', now(), '$topic', '')";
if (!mysql_query($query)) {
// Handle error here
// e.g.
// echo "Oh no! The query failed! Error: ".mysql_error();
}
This will probably fix the problem, and will prevent SQL injection attacks.
You're missing the value for "sad". You can see if there was an error executing the previous SQL statement using mysql_error().
Does
<form action="test.php" type="post">
<input type="text" name="topic" />
</form>
and
<?php
$input = $_POST['topic'];
echo $input;
mysql_query("INSERT INTO balbal VALUES ('".$input."')") or die (mysql_error());
?>
work for you?
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>