用户将记录添加到数据库PDO

时间:2015-07-22 11:12:05

标签: php mysql pdo

  

我希望让用户将记录添加到空数据库表中。事实上,我有一个数据库和一个空表,必须使用表单填写    第一个文件处理数据库连接(我使用 PDO )返回一个空页面和一个名为add的链接,该链接转到表单



<?php
error_reporting(-1);
ini_set('display_errors', 'On');
?>
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxxx";

try {
    $dbh = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	echo 'Connected to database<br />';
    }
catch(PDOException $e)
    {
    echo "Connection failed: " . $e->getMessage();
    }
?>
<html>
 <head>
    <meta charset="UTF-8">
    <title>Tages database</title>
	<style type="text/css">
	th { background-color: #999;}
	.odd_row { background-color: #EEE; }
	.even_row { background-color: #FFF; }
	</style>
 </head>
 <body>
    <table style="width: 100%;">
		    <tr>
			    <th colspan="2">Tages <a href="./tages.php?action=add"> [ADD]</a></th>
			</tr>
 <?php
**EDIT** 
>I have just replaced the `query` statement with prepare`      
$sth = $dbh->prepare("SELECT * FROM tagesroma"); 

 
 $odd = true;
 while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
	 echo ($odd == true) ? '<tr class="odd_row">' : '<tr class="even_row">';
	 $odd = !$odd;
	 echo '<td style="width:75%;">';
	 echo $row['nome'];
	 echo '</td><td>';
	 echo ' <a href="tages.php?action=edit&id=' . $row['id'] . '">
[EDIT]</a>';
     echo ' <a href="delete.php?type=tages&id=' . $row['id'] . '">
[DELETE]</a>';
     echo '<td></tr>';
 }
 ?>
 </table>
 </body>
 </html>
&#13;
&#13;
&#13;

  

第二页加载一个表单,该表单一次填充点到第三页和最后一页,使用户确保一切顺利

&#13;
&#13;
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
?>
<?php
$servername = "localhost";
$username = "xxxx";
$password = "xxxxx";
$dbname = "xxxx";

try {
    $dbh = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	echo 'Connected to database<br />';
    }
catch(PDOException $e)
    {
    echo "Connection failed: " . $e->getMessage();
    }
?>
<?php
if ($_GET['action'] == 'edit') {
    //retrieve the record's information 
     **EDIT**
     I have just replaced `query` statement with `prepare`

    $sth = $dbh->prepare = 'SELECT
            nome, cognome, indirizzo, civico, citta,
            prov
        FROM
            tagesroma
        WHERE
            id = ' . $_GET['id'];
    $result = $sth->fetch(PDO::FETCH_ASSOC);
} else {
    //set values to blank
    $nome = '';
    $cognome = '';
    $indirizzo = '';
    $civico = 0;
    $citta = '';
    $prov = '';
}
?>
<html>
	<head>
	    <meta charset="UTF-8">
		<title><?php echo ucfirst($_GET['action']); ?> Tages</title>
		<style type="text/css">
		<!--
		#error { background-color: #600; border: 1px solid #FF0; color: #FFF;
		 text-align: center; margin: 10px; padding: 10px; }
		-->
		</style>
	</head>
	<body>
		<?php
			if (isset($_GET['error']) && $_GET['error'] != '') {
				echo '<div id="error">' . $_GET['error'] . '</div>';
			}
		?>
		<form action="commit.php?action=<?php echo $_GET['action']; ?>&type=tages"
		   method="post" accept-charset="UTF-8">
> I have edited the form fields adding `value` to every `input`. The `value` echoes a variable that corresponds to the name of the `input` `label`
			<table>
				<tr>
					<td>Nome</td>
				<td><input type="text" name="nome" value="<?php echo $nome; ?>"/></td>
			</tr><tr>
				<td>Cognome</td>
				<td><input type="text" name="cognome" value="<?php echo $cognome; ?>"/></td>
			</tr><tr>
				<td>Indirizzo</td>
				<td><input type="text" name="indirizzo" value="<?php echo $indirizzo; ?>"/></td>
			</tr><tr>
				<td>Civico</td>
				<td><input type="text" name="civico" value="<?php echo $civico; ?>"/></td>
			</tr><tr>
				<td>Citta</td>
				<td><input type="text" name="citta" value="<?php echo $citta; ?>"/></td>
			</tr><tr>
				<td>Prov</td>
				<td><input type="text" name="prov" value="<?php echo $prov; ?>"/></td> 
				</tr><tr>
					<td colspan="2" style="text-align: center;">
					<?php
						if ($_GET['action'] == 'edit') {
							echo '<input type="hidden" value="' . $_GET['id'] . '" name="id" />';
						}
					?>
					<input type="submit" name="submit"
                    value="<?php echo ucfirst($_GET['action']); ?>" />
					</td>
				</tr>
			</table>
		</form>
	</body>
</html>
&#13;
&#13;
&#13;

  

第三个是一个确认页面,上面检查是否发生错误,如果在第一页中一切顺利,你应该看到刚刚加入的记录

&#13;
&#13;
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
?>
<?php
$servername = "localhost";
$username = "xxxx";
$password = "xxxxx";
$dbname = "xxxx";

try {
    $dbh = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	echo 'Connected to database<br />';
    }
catch(PDOException $e)
    {
    echo "Connection failed: " . $e->getMessage();
    }
	> **EDIT** I have just replaced the `query` statement with `prepare`
    $dbh->prepare("use accessibilita"); 

?>
<?php
switch ($_GET['action']) {
case 'add':
    switch ($_GET['type']) {
    case 'tages':
        $error = array();
        $nome = isset($_POST['nome']) ?
            trim($_POST['nome']) : '';
        if (empty($nome)) {
            $error[] = urlencode('Si prega di inserire un nome.');
        }
        $cognome = isset($_POST['cognome']) ?
            trim($_POST['cognome']) : '';
        if (empty($cognome)) {
            $error[] = urlencode('Si prega di inserire un cognome.');
        }
        $indirizzo = isset($_POST['indirizzo']) ?
            trim($_POST['indirizzo']) : '';
        if (empty($indirizzo)) {
            $error[] = urlencode('Si prega di inserire un indirizzo.');
        }
        $civico = isset($_POST['civico']) ?
            trim($_POST['civico']) : '';
        if (empty($civico)) {
            $error[] = urlencode('Si prega di inserire un numero civico.');
        }
        $citta = isset($_POST['citta']) ?
        trim($_POST['citta']) : '';
    if (empty($citta)) {
        $error[] = urlencode('Si prega di inserire una citta.'); //citta just added
    }
        $prov = isset($_POST['prov']) ?
            trim($_POST['prov']) : '';
        if (empty($prov)) {
            $error[] = urlencode('Si prega di inserire una provincia.');
        }
        if (empty($error)) {
            > **EDIT** I have just replaced the `query` statement with `prepare`    
          $prepare= 'INSERT INTO 
                tagesroma
                    (nome, cognome, indirizzo, civico,
                    citta, prov)
                VALUES
                    ("' . $nome . '",
                     ' . $cognome . ',
                     ' . $indirizzo . ',
                     ' . $civico . ',
                     ' . $citta . ',
                     ' . $prov . ')';
        } else {
          header('Location:tages.php?action=add' .
              '&error=' . join($error, urlencode('<br/>')));
        }
        break;
    }
    break;
case 'edit':
    switch ($_GET['type']) {
    case 'tages':
        $error = array();
        $nome = isset($_POST['nome']) ?
            trim($_POST['nome']) : '';
        if (empty($nome)) {
            $error[] = urlencode('Si prega di inserire un nome.');
        }
        $cognome = isset($_POST['cognome']) ?
            trim($_POST['cognome']) : '';
        if (empty($cognome)) {
            $error[] = urlencode('Si prega di inserire un cognome.');
        }
        $indirizzo = isset($_POST['indirizzo']) ?
            trim($_POST['indirizzo']) : '';
        if (empty($indirizzo)) {
            $error[] = urlencode('Si prega di inserire un indirizzo.');
        }
        $civico = isset($_POST['civico']) ?
            trim($_POST['civico']) : '';
        if (empty($civico)) {
            $error[] = urlencode('Si prega di inserire un numero civico.');
        }
         $citta= isset($_POST['citta']) ?
        trim($_POST['citta']) : '';
    if (empty($citta)) {
        $error[] = urlencode('Si prega di inserire una citta.'); //citta just added
    }
        $prov = isset($_POST['prov']) ?
            trim($_POST['prov']) : '';
        if (empty($prov)) {
            $error[] = urlencode('Si prega di inserire una provincia.');
        }
        if (empty($error)) {
            > **EDIT** I have just replaced the `query` statement with `prepare` 
               $prepare= 'UPDATE
                    tagesroma
                SET 
                    nome = "' . $nome . '",
                    cognome = ' . $cognome . ',
                    indirizzo = ' . $indirizzo . ',
                    civico = ' . $civico . ',
                    citta = ' . $citta . ',
                    prov = ' . $prov . ' //variable replacement 
                WHERE
                    id = ' . $_POST['id'];
        } else {
          header('Location:tages.php?action=edit&id=' . $_POST['id'] .
              '&error=' . join($error, urlencode('<br/>')));
        }
        break;
    }
    break;
}
?>

<html>
 <head>
  <title>Commit</title>
  <meta charset="UTF-8">
 </head>
 <body>
  <p>Done!</p>
 </body>
</html>
&#13;
&#13;
&#13;

  

在每个页面中error reporting已启用但未返回错误,我无法将记录添加到我的表中   在第三页中,我创建了一个array命名错误,用于处理表单字段的验证。每当我尝试插入所需数据以填写表单时,验证返回我需要插入name以便转到最后一步commit.php(检查输入数据是否为正确,如果是,则将新记录添加到主页admin.php)。我已修复验证问题,现在返回的错误如下:Notice: Undefined variable: citta commit.php(third page) on line 64   我刚刚能够定义variable: citta但仍然没有成功添加记录

0 个答案:

没有答案
相关问题