Insert data / update if already exists - php

This code works. I can't figure out how to insert data into db If user pressed "SAVE" button for the first time or update data.
The php side
<?php
require '../../core/includes/common.php';
$name=filter($_POST['name'], $db);
$title=filter($_POST['title'], $db);
$parentcheck=filter($_POST['parentcheck'],$db);
if(isset ($_POST['parent'])) $parent=filter($_POST['parent'],$db);
else $parent=$parentcheck;
$menu=filter($_POST['menu'], $db);
$content = $db->escape_string($_POST['content']);
$result=$db->query("INSERT INTO menu (parent, name, showinmenu) VALUES ('$parent', '$name', '$menu')") or die($db->error);
$new_id = $db->insert_id;
$result2=$db->query("INSERT INTO pages (id, title, content) VALUES ('$new_id', '$title', '$content')") or die($db->error);
if ($new_id>0){
echo "{";
echo '"msg": "success" ';
echo "}";
}else{
echo "{";
echo
'"err": "error"';
echo "}";
}
?>
UPDATE
Thanks to #jmlsteeke i found the way
Place this piece of code in html part
<?php
$result=$db->query("INSERT INTO menu (parent, name, showinmenu) VALUES ('555', 'new', '0')") or die($db->error);
$new_id = $db->insert_id;
$result2=$db->query("INSERT INTO pages (id, title, content) VALUES ('$new_id', 'new', 'new')") or die($db->error);
?>
And added following code into form
<input type="hidden" name="id" value="<?=$new_id?>"/>
In serverside script used
$result=$db->query("UPDATE pages AS p, menu AS m SET m.parent='$parent', m.name='$name', m.showinmenu='$menu', p.id='$id', p.title='$title', p.content='$content' WHERE m.id='$id' AND p.id=m.id") or die($db->error);
Thank you #jmlsteeke

A common way would be to store the id as a hidden field when you are editing the page. This way when the user submits the page, if there is an id present, you issue the UPDATE commands, and if there isn't one present, you know it's a new page, and issue the INSERT commands.
If you need me to be more thorough let me know.
Edit: Being More Thorough
I'll make a simple, complete, example of what I mean.
Form.php pseudo code
//set default values for fields
//print form tag
if (isset($'id',$_GET)) {
//fetch data from database
//print hidden id field
//override default values for fields
}
//print rest of fields using default values (possibly overridden)
DoForm.php pseudo code
//Sanitize user input
if (isset('id',$_POST)) {
//UPDATE database with user input
} else {
//INSERT new rows into table with user input
}
Let's say you have a php file called Form.php which is responsible for displaying the form, and another php script called DoForm.php which is responsible for handling the form.
If a user visits Form.php with no ID specified (http://example.com/Form.php) then it will display the following form:
<form method="post" action="DoForm.php">
<input type="text" name="name" value="" />
<input type="text" name="title" value="" />
... other stuff ...
</form>
The user will add some information, click on the submit button and DoForm will get the following POST variables:
"name" => "NewPageName"
"title" => "My First Webpag" [intetional typo, see later]
... other stuff ...
DoForm will check to see if $_POST['id'] exists. Since it doesn't DoForm issues the INSERT commands to add a new page.
Later on, the user realises the made a typo, and goes to fix it. The user clicks on the "Edit Page" control for "NewPageName" which will be http://example.com/Form.php?id=1
Form.php see's that id is set, so the form it prints out is as follows:
<form method="post" action="DoForm.php">
<input type="hidden" name="id" value="1"
<input type="text" name="name" value="NewPageName" />
<input type="text" name="title" value="My First Webpag" />
... other stuff ...
</form>
The user fixes their type, changing Webpag to Webpage, and hits submit. DoForm gets the following Post variables
"id" => 1
"name" => "NewPageName"
"title" => "My First Webpage"
... other stuff ...
DoForm sees that id is set, and so uses UPDATE instead of INSERT.
Any more clear?

MySQL has an INSERT ... ON DUPLICATE KEY UPDATE feature that will let you try to insert a row, or fall back to an update if it discovers a duplicate key (i.e. the row already exists).

Related

Pass foreign key via $_GET

I have an online courses CRUD application. It has, among other pages, an instructor BIO page.
First, the instructors are added, in an users table, with basic data: first_name, last_name, and email; then a BIO can be added, optionally, for any instructor. There is a second database table, called "bios", to serve this purpose.
I need to pass $user_id into the courses table, (as foreign KEY) an for that purpose i use $_GET:
<?php
$user_id = $_GET['id'];
if(isset($_POST['submit-btn'])) {
$no_courses = $_POST['no_courses'];
$years_exp = $_POST['years_exp'];
$fav_lang = $_POST['fav_lang'];
$courses = $_POST['courses'];
$sql = "INSERT INTO courses (user_id, no_courses, years_exp, fav_lang, courses) VALUES ('$user_id', '$no_courses', '$years_exp', '$fav_lang', '$courses')";
if (mysqli_query($con, $sql)) {
echo("<p>Instructor bio was added.</p>");
} else {
echo "Error: " . mysqli_error($con);
}
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="add_bio">
...
</form>
Using $_GET seems convenient because in a table with a lot of rows, containing instructors, on the right most cell/column, I have a set of link buttons for CRUD operations, "Add bio" being one of those buttons.
<a title="Add bio" href="add_bio.php?id=<?php echo $arr['id']?>"><span class="glyphicon glyphicon-plus-sign"></span></a>`
But instead of passing the $user_id variable so that the bio can be added, the server throws these errors:
Notice: Undefined index: id in E:\xampp\htdocs\courses\add_bio.php on line 7
Error: Cannot add or update a child row: a foreign key constraint fails
How can I pass the user's id if I want to keep the CRUD links mentioned above?
Thank you!
You may have some issues with the content being submitted.
A great troubleshooting approach would be to:
print_r($_GET);
or
print_r($_POST);
Another option is to also:
echo print_r($_GET, true);
The Second argument (True) tells the print_r function to return as a string instead of output to the browser.
Review that output and verify you are actually getting an "ID" value in your GET and POST variables.
Also, some security concerns, any data you take in from GET or POST or REQUEST or COOKIE should be "cleaned" you can look at:
mysqli_real_escape_string
Additionally, Never use PHP_SELF. In almost all cases, it can be manipulated to execute a Cross Site Scripting Attack, and that is bad news. if you want to submit the form to the current script, you can leave the "action" attribute as an empty string.
action=""
Hope this helps!!!
The form was missing this line, right above the submit button:
<input type="hidden" name="id" value="<?php $user_id;?>">

PHP work with dropdown values from mySQL-db

so I've finally figured out how I can get values from my mySQL-db into a dropdown form in PHP. My problem is, how can I use/work with the option that was selected by the user?
My goal is a functioning email-signature generator. I want the user to be able to insert unique data like their name, and select the office where they work from the dropdown form. After they hit the submit button, they should then be lead to the next site that displays their name with the signature for the selected office.
The name is no problem, that is only a simple html-form with a post method, I know how I can retrieve and access that.
But how can I work with the option that was selected by the user in the dropdown?
After selecting an option and hitting submit, the whole "row" in the mySQL-db should be displayed, in formated form.
My current situation is that the dropdown shows the correct values from the mySQL-db, and the two name fields, that are also working as they should.
The name of the mySQL database is "firmen", the name of the column I use is "niederlassung".
I'm happy to provide more information if needed.
My code:
[...]
<form action="php-verarbeitung.php" method="post">
<div>
<label for="1">Vorname: </label>
<input type="text" name="vorname" id="1" value=""><br><br>
</div>
<div>
<label for="2">Nachname: </label>
<input type="text" name="name" id="2" value=""><br><br>
</div>
<input type = "submit" name = "button" value = "Senden"><br><br>
<?php
// Establish mySQL PDO Connection
$server='mysql:host=*****.com.mysql;dbname=*****'; // Host and DB-Name
$user="******"; // Username
$password="*****"; // Password
$pdo=new PDO($server, $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Write out the query
$query = "SELECT niederlassung FROM firmen";
// Execute it, or let it throw an error message if there's a problem
$stmt = $pdo->query($query);
$dropdown = "<SELECT name='firmen'>";
foreach ($stmt as $row) {
$dropdown .= "\r\n<option value='{$row['niederlassung']}'>{$row['niederlassung']}</option>";
}
$dropdown .= "\r\n</select>";
echo $dropdown;
?>
</form>
</body>
</html>
Thanks for any help in advance!
you are passing the variables through the form to php-verarbeitung.php. On that page you can load the content based on the $_POST variables that are sent through the form. so you can query the DB again on the second page to get the info you need, and present formated html using the values from the form passed through the post array, in your case
$_POST['vorname'], $_POST['name'] and $_POST['firmen'] should all be accessible when the php-verarbeitung.php page is called using your script above.

How to restrict update or insert more than once by navigating back to referring page in php?

I am developing a web application where I want to restrict update or insert more than once by navigating back to referring page. Let me present you three model files in the order of flow so that I can raise the zone where I am stuck.
register.html
<html>
...
<form id="form1" name="form1" method="post" action="process.php">
<label for="textfield">Name</label>
<input type="text" name="name" id="name" />
<input type="submit" name="Submit" value="Submit" />
</form>
...
</html>
process.php
<?php
echo "Welcome ".$_GET['para'];
?>
success.php
<?php
if(isset($_POST['Submit']))
{
$name = $_POST['name'];
// some database update here ...
echo "<a href='success.php?para=$name'>Done. Click to go next</a>";
unset($_POST['Submit']);
}else{
echo "Error in submission";
}
?>
The above three files are very simple. Here the update part has nothing to do when the user hits the back button after landing on page success.php because of unset($_POST['Submit']);. But when the user goes back further by hitting the back button again it reaches register.html and can again come up with the $_POST['Submit'] set and may do the update part which is sometimes vulnerable. I know there is Post/Redirect/Get to solve this issue, but I want some other alternatives so that the part gatekeepering the update part may be made so efficient that it would not allow the same anymore by clicking the back button.
If you are getting duplicate records inserted.
You may try INSERT IGNORE
ADD UNIQUE INDEX to your table to prevent this happening
you may choose any one of INSERT IGNORE and REPLACE according to the duplicate-handling behavior
Refer https://dev.mysql.com/doc/refman/5.5/en/insert-on-duplicate.html
Lastly you may like simple php with mysqli_num_rows()
$sql = "SELECT id FROM table-name WHERE column-name1 = ? AND column-name2 = ? ;
$mq = mysqli_query($sql);
if (mysqli_num_rows($mq) < 1) {
$sql = "UPDATE table-name SET (colum-names) VALUES (...)";
mysqli_query($sql);
else {
echo "Record already updated";
}
}

Pass PHP fetch variable to another page

I have a form that submits to firstpage.php, this page includes the code to insert all form values into the database and check for duplicate entries, if the entry is a duplicate , display the duplicate entry using the following php code
$checkstudentID = mysqli_query
($dbcon, "SELECT studentid from courses WHERE studentid = '$studentid'");
if(mysqli_num_rows($checkstudentID) > 0){
if ($stmt = mysqli_prepare($dbcon, "SELECT ckb from courses WHERE studentid = ?")) {
mysqli_stmt_bind_param($stmt,"s",$studentid);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $ckb);
mysqli_stmt_fetch($stmt);
printf("<br /><center><h1>Your Student ID is</h1> <h2>%s.</h2><h1> Subjects Registered : %s\n </h1>", $studentid, $ckb );
mysqli_stmt_close($stmt);
}
mysqli_close($dbcon);
die(" <p> The Student ID <strong>$studentid </strong>already exists. Update</p>");
the page update.html includes an update form that submits to update.php
how can I pass the the single fetched row variable (subjects registered/$ckb) to update.html ?
I tried the following so far:
at the firstpage.php I started a session
session_start();
$_SESSION['subjects'] = '$ckb';
and at the update.html > renamed to update2.php and added the following at the top of the page
<?php
session_start();
echo $_SESSION['sujects'];
?>
and at the input field the value="<?php echo $ckb;?>"
What am I missing ?
Please note, that the variable I want to pass is the subjects registered related to the student id checked in firstpage.php file meaning this :
printf("<br /><center><h1>Your Student ID is</h1> <h2>%s.</h2><h1> Subjects Registered : **%s**\n </h1>", $studentid, $ckb );
but its either completely wrong or I'm just passing the wrong variable
Remove quotes in:
$_SESSION['subjects'] = '$ckb';
So it will be:
$_SESSION['subjects'] = $ckb;
And update 2nd file to this:
<?php
session_start();
$ckb = $_SESSION['subjects'];
?>
....
<input type='text' value="<?php echo $ckb;?>" />
Note: also, you wrote sujects in second file, its ok in my code example.
In answer to my question I found an easy and effective by passing the variables through the url.
Meaning...
In my firstpage.php, the href links to my update2.php page became as follows:
Update
The $studentid and $cc variables are previously defined in my code where I "get" them from the input fields of the form.
In update2.php, the page which I would like to pass the variables to I inserted the following code
<?php
$studentid= $_GET['studentid'];
$cc = $_GET['ckb'];
?>
Which allowed me to use the variables throughout the rest of the php code, where for my case I wanted them to be the "values" of a new form input field, as shown below :
<input name="newcourses" type="text" id="newcourses" maxlength="70" value="<?php echo $cc?>"" />
I recommend anyone who wants a more clear idea and read more about other methods to pass variables across php pages to check this out >> Pass PHP fetch variable...

Editting data by ADMIN

I am new to PHP and working on small local webpage and database that takes user information and database stores the same user information .If i Login with ADMIN it shows all data. My requirement is that the loggined user is an admin, then he has a right to edit all the informtion of the users that i stored in the database.And this is to be done using GET method . How it will be working?
Heres some example code purely to demonstrate how to update a table using a GET method form. The code doesn't have any kind of error checking and assumes you already know how to connect to your database (and that its MySQL).
Assuming you've landed on a page which invites you to edit data, which record you're editing is referenced by an 'id' variable on the URL which matches a numerical primary key in your database table.
<?php
$SQL = "SELECT myField1,myField2 FROM myTable WHERE myKeyField = '".intval($_GET['id'])."'";
$QRY = mysql_query($SQL);
$DATA = mysql_fetch_assoc($QRY);
?>
<form method='get' action='pageThatStoresData.php'>
<input type='hidden' name='key' value='<?php echo $_GET['id']; ?>' />
<input type='text' name='myField1' value="<?php echo $DATA['myField1']; ?>" />
<input type='text' name='myField2' value="<?php echo $DATA['myField2']; ?>" />
<button type='submit'>Submit</button>
</form>
So, this will give you a page that takes the data out of your table, displays it in a form with pre-filled values and on submit, will go to a URL like:
http://mydomain.com/pageThatStoresData.php?key=1&myField1=someData&myField2=someMoreData
In that page, you can access variables 'key', 'myField1', 'myField2' via the $_GET method.
Then you just need to update your table within that page:
$SQL = "UPDATE myTable
SET myField1 = '".mysql_real_escape_string($_GET['myField1'])."',
myField2 = ".mysql_real_escape_string($_GET['myField1'])."
WHERE key = '".intval($_GET['key'])."'
";
$QRY = mysql_query($SQL);
PLEASE NOTE: The code above is unsuitable for a straight copy/paste as it doesn't do any error checking etc, its purely a functional example (and typed straight in here so I apologise if there are any typos!).

Categories