可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
I'm quite new to PHP and have an assignment where I have to make a html form, which is fine. I'm required to have the data submitted to a database and stored in a table. This table should allow the user to view edit and delete entries in the table.
I'm not asking for any code or for somebody to do this for me or anything like that, I want to learn the language myself. I would appreciate it greatly if somebody could just outline the steps required?
At the moment I have a simple html form, which is linked to a php document called process.php that echos the inputted values to the screen.
I'm using xampp to create a local php server and using PhpMyAdmin I created a database called my_db and within it I created a table called userProfile.
I know I have to create another php file that connects to the database but after that I'm completely stumped.
EDIT
I'll post my code below, please excuse it as I'm very new to this.
**
My html form:
**
<!Doctype html public>
<body>
Please fill out the following form:
<table border="1" cellpadding="10">
<td>
<h1> Games Console Survey </h1>
<form action="createProfile.php" method = "post">
First Name: <br /> <input type="text" name="firstname" /><br />
<br />
Surname: <br /> <input type="text" name="lastname" /> <br />
<br />
<u>Gender</u>: <br />
<br />
<input type="radio" name="gender" value="Male" /> Male<br />
<input type="radio" name="gender" value="Female" /> Female <br />
<br />
<u>I Have The Following:</u> <br />
<br />
<input type="checkbox" name="Console" value="Playstation 3" /> Playstation 3<br />
<input type="checkbox" name="Console" value="Xbox 360" /> Xbox 360 <br />
<input type="checkbox" name="Console" value="Wii" /> Wii <br />
<br />
<input type="submit" />
</form>
</form>
</td>
</table>
</body>
</html>
process.php
<?php
echo "First Name: ".$_POST['firstname'];
?>
</br>
<?php
echo "Surname: ".$_POST['lastname'];
?>
</br>
<?php
echo "Gender: ".$_POST['gender'];
?>
</br>
<?php
echo "Console: ".$_POST['Console'];
?>
</br>
<?php
require_once 'Connection.php';
?>
**
Connection.php
**
<?php
$host = "localhost";
$username = "root";
$password = "";
$database = "my_db";
$dsn = "mysql:host=$host;dbname=$database";
try {
$conn = new PDO( $dsn, $username, $password );
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//$conn = null;
}
catch (PDOException $e) {
$conn = null;
exit("Connection failed: " . $e->getMessage());
}
?>
createProfile.php
<?php
$firstname = $_Post['firstname'];
$lastname = $_Post['lastname'];
$gender = $_Post['gender'];
$Console = $_Post['Console'];
try {
$host = "localhost";
$username = "root";
$password = "";
$database = "my_db";
$dsn = "mysql:host=$host;dbname=$database";
$conn = new PDO( $dsn, $username, $password );
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO userprofile("
. "firstname, lastname, sex, console"
. " ) VALUES ("
. "'" . $firstname . "',"
. "'" . $lastname . "',"
. "'" . $gender . "',"
. "'" . $Console .")";
$conn->query($sql);
$sql = "SELECT * FROM userdata";
$userdata = $conn-query($sql);
echo '<table>';
echo '<tr>';
echo '<th>First Name</th>
<th>Last Name</th>
<th>Gender</th>
<th>Console</th>';
echo '<tr>';
foreach ($userdata as $userdata) {
echo '<tr>';
echo ' <td>' . $userprofile['firstname'] . '</td>';
echo ' <td>' . $userprofile['lastname'] . '</td>';
echo ' <td>' . $userprofile['gender'] . '</td>';
echo ' <td>' . $userprofile['Console'] . '</td>';
echo ' </tr> ';
}
echo '</table>';
$conn = null;
}
catch (PDOException $e) {
$conn = null;
exit("Connection failed: " . $e->getMessage());
}
?>
<?php
require_once 'Connection.php';
?>
回答1:
If that is just school assignment, and You don't need to worry about security and real world problems with it, then single file will do.
Do an IF statement and check if data is submitted (you can look at $_POST variable),
use isset() and strlen() functions to make sure data is in the arrays
Use PHP PDO object to connect and talk with database see http://www.php.net/manual/en/book.pdo.php, see the example and comments
If there are data submitted, You can save them with $pdo->query('insert ...');,
You will need to learn some basic SQL as well, check http://www.sqlcourse.com/insert.html
at any case, fetch all the data from the database, and display them in a table, with "edit" link.
Let the edit link, target your process.php file, with a param, for example process.php?id=1, ect., the id param should refer to the row id in the database (now You know your rows should have id column)
in Your process.php file, look at the $_GET['id'] param, to see if there is id given. If there is, use $pdo->query("select ... where id = {$_GET['id']}") to fetch the data, check http://www.sqlcourse.com/select.html, and the pdo php manual on how to use it.
if there was an ID, prepopulate Your form with the data, and add extra hidden input in the form, that will contain the ID of row to update.
In process.php, if there is $_POST and it has an ID, update the row with $pdo->query('update ...').
Look at Your IF statements, arrange them in logical flow, You will always need to open database connection, You will always need to check $_POST and $_GET params, so do those things before IFs
Be sure to read the php manual, read the comments as well. Read the MySql docs. It takes time, but it's time well spent.
Play as You code, that's the best way to learn :)
If this is for production, or You want to do things right, use $pdo->quote, to make sure You are not passing something wrong to Your database.
EDIT:
You are on the right track, now combine it.
Look at the following code (You might need to debug it, haven't tested)
<?php
$host = "localhost";
$username = "root";
$password = "";
$database = "my_db";
$dsn = "mysql:host=$host;dbname=$database";
TRY {
$conn = new PDO( $dsn, $username, $password );
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (isset($_POST['submit'])) {
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$gender = $_POST['gender'];
$Console = $_POST['Console'];
if (isset($_POST['id'])) {
//update mode, we have both POST data and ID, update the record
$id = $_POST['id'];
$sql = "UPDATE userprofile SET"
. "firstname=".$conn->quote($firstname)
. ",lastname=".$conn->quote($lastname)
. ",sex=".$conn->quote($gender)
. ",console=".$conn->quote($Console)
. " WHERE id = ".$conn->quote($id);
$userdata = $conn->query($sql);
} else {
// insert mode, there is no ID, but there are data, insert them as new
$sql = "INSERT INTO userprofile("
. "firstname, lastname, sex, console"
. " ) VALUES ("
. $conn->quote($firstname).","
. $conn->quote($lastname).","
. $conn->quote($gender).","
. $conn->quote($Console).")";
$userdata = $conn->query($sql);
}
} elseif (isset($_GET['id'])) {
// edit mode, no POST data, but there is an ID param, prepopulate the form
$userEditDataRows = $conn->query('SELECT * FROM userdata WHERE id ='.$conn->quote($_GET['id']));
if (sizeof($userEditDataRows)>0) {
$row = $userEditDataRows[0];
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$gender = $row['sex'];
$Console = $row['console'];
$id = $_GET['id'];
}
} else {
// set empty data
$firstname = '';
$lastname = '';
$gender = '';
$Console = '';
$id = false;
}
//build the table
$sql = "SELECT * FROM userdata";
$userdata = $conn->query($sql);
$table = '<table>';
$table .= '<tr>';
$table .= '<th>First Name</th>
<th>Last Name</th>
<th>Gender</th>
<th>Console</th>
<th>Edit</th>';
$table .= '</tr>';
foreach ($userdata as $userdata) {
$table .= '<tr>';
$table .= ' <td>' . $userdata['firstname'] . '</td>';
$table .= ' <td>' . $userdata['lastname'] . '</td>';
$table .= ' <td>' . $userdata['gender'] . '</td>';
$table .= ' <td>' . $userdata['Console'] . '</td>';
$table .= ' <td><a href="/process.php?id='.$userdata['id'].'">Edit</a></td>';
$table .= ' </tr> ';
}
$table .= '</table>';
} catch (PDOException $e) {
exit("Connection failed: " . $e->getMessage());
}
?>
<!Doctype html public>
<html>
<body>
Please fill out the following form:
<table border="1" cellpadding="10">
<td>
<h1> Games Console Survey </h1>
<form action="createProfile.php" method = "post">
First Name: <br /> <input type="text" name="firstname" value="<?php $firstname ?>" /><br />
<br />
Surname: <br /> <input type="text" name="lastname" value="<?php $lastname ?>" /> <br />
<br />
<u>Gender</u>: <br />
<br />
<input type="radio" name="gender" value="Male" <?php if($gender == 'Male') echo "checked=checked"; ?> /> Male<br />
<input type="radio" name="gender" value="Female" <?php if($gender == 'Feale') echo "checked=checked"; ?>/> Female <br />
<br />
<u>I Have The Following:</u> <br />
<br />
<input type="checkbox" name="Console" value="Playstation 3" <?php if($Console == 'Playstation 3') echo "checked=checked"; ?> /> Playstation 3<br />
<input type="checkbox" name="Console" value="Xbox 360" <?php if($Console == 'Xbox 360') echo "checked=checked"; ?> /> Xbox 360 <br />
<input type="checkbox" name="Console" value="Wii" <?php if($Console == 'Wii') echo "checked=checked"; ?> /> Wii <br />
<?php if($id !== false):?>
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<?php endif; ?>
<br />
<input type="submit" name="submit"/>
</form>
</td>
</table>
<h1>Current data:</h1>
<?PHP echo $table ?>
</body>
</html>
回答2:
To outline the steps. I would create a database class in PHP to handle all database requests CRUD. For example:
-SELECT
-UPDATE
-INSERT
-DELETE
-QUERY
-OUTPUTQUERY
I would also create an additional class User to get and set all data related to the user.
You should be able to use these two classes to pretty much accomplish everything you want to do. Implement the classes in your current process.php page.
Doing this will keep you organized and will also give you a lot of flexibility when it comes to adding to the project. For example if you are adding multiple pages that will all have access to editing the same table you want to use the same consistent code each time. This way if something breaks you are only going to one class.
I hope this helps. It is hard to explain without giving you the code.
Here is a good resource: http://net.tutsplus.com/tutorials/php/real-world-oop-with-php-and-mysql/
回答3:
First, you have to design your html form.
Second, you have to modify your table 'userProfile'.
Third, change your input 'name' in html form exactly like the field name in table. such as:
<form>
Name:<input name="firstname" type="text">
</form>
Here, "firstname" will be one of your fieldname in the table "userProfile"
回答4:
Sure. First, you'll need to create a Database table. To keep things simple, make 1 column for each form field, plus one for a unique ID.
DISCLAIMER: I'm keeping this basic, for clarity. So, security steps are omitted. Don't run this in a public / production environment, as it could compromise your web server!
Steps to save data:
1) Establish connection w/ MySQL
2) String-build an INSERT INTO statement, using the proper sql syntax
3) Execute your SQL query
Steps to view data:
1) (same) Establish connection w/ MySQL
2) String-build a SELECT statement, using the proper sql syntax
3) Execute your SQL query, loop over the results, & echo them to screen as you wish
Steps to update data:
1) (same) Establish connection w/ MySQL
2) String-build an UPDATE statement, using the proper sql syntax, & feed it your POST data from the form submission
(make sure you pass in the row ID as an input type=hidden, so you can pass the row id into the UPDATE statement)
3) Execute your SQL query
That's pretty much it!
回答5:
You are almost there..now it's just the last mile..the following steps would be
- Make connection to database
- Check that connection was made successfully
- Sanitize values that you get from your form
- Insert those sanitized values into the databse table
- Close your connection
Please feel free to update in case i am missing something..
回答6:
Before you start php mysql_ functions are [being deprecated. You are left with using either mysqli or PDO. You can use either but I would suggest PDO.
As process.php
already echos the inputted values to the screen and created the database you are half way there.