我想将php代码中的成员插入到mysql数据库中,它会自动增加,但不会添加任何数据

时间:2022-09-25 19:14:36

I'm Trying to insert users into my database table users (membros) from my PHP page but for some reason it increments the values "membro_id) which is the primary key but no data is added to it. my pages have general header. The main one is:

我试图从我的PHP页面将用户插入我的数据库表用户(membros),但由于某种原因,它增加了值“membro_id”,这是主键,但没有数据添加到它。我的页面有一般标题。主要是:

<?php
define('DB_USER', 'chimasonline');
define('DB_PWD', 'root');
define('DB_NAME', 'chimasonline');
define('DB_HOST', 'localhost');
define('DB_DSN', 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME);

my Members file from model is Member.php (I put the INSERT INTO queries in comment mode to show what I already tried):

我的模型成员文件是Member.php(我在注释模式中放置INSERT INTO查询以显示我已经尝试过的内容):

<?php
// PHP and MySQL Project
// members table data class

class Members
{
    public $debug = TRUE;
    protected $db_pdo;
    public $membersPerPage = 12;
    public $howManyMembers = 0;

    /*
     * Returns array of arrays where each sub-array = 1 database row of Members
     * @param int $offset [optional]
     * @return array $row[] = array('title' => title, 'description' => description, etc.)
     */
    public function getAllMembers($offset = 0)
    {
        $pdo = $this->getPdo();
        $sql = 'SELECT * FROM `membros` ORDER BY `primeironome` LIMIT ' . $this->membersPerPage . ' OFFSET ' . $offset;
        $stmt = $pdo->prepare($sql);
        $stmt->execute();
        $content = array();
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $content[] = $row;
        }
        return $content;
    }
    /*
     * Returns database row for 1 member
     * @param int $id = member ID
     * @return array $row[] = array('title' => title, 'description' => description, etc.)
     */
    public function getDetailsById($id)
    {
        $pdo = $this->getPdo();
        $sql = 'SELECT * FROM `membros` WHERE `produto_id` = ?';
        $stmt = $pdo->prepare($sql);
        $stmt->execute(array($id));
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        return $result;
    }
    /*
     * Returns database row for 1 member
     * @param string $email
     * @return array $row[] = array('title' => title, 'description' => description, etc.)
     */

      public function insertMember($data)
    {
        $pdo = $this->getPdo();


/*      $sql = 'INSERT * INTO `membros`(`nome`, `endereco`, `cidade`, `estado_provincia`, 
       `codigo_postal`, `pais`, `telefone`, `balanco`, `email`, `password`)' . 'VALUES ([value-2],[value-3],
       [value-4],[value-5],[value-6],[value-7],[value-8],[value-9],[value-10],[value-11])';

    /*            $sql = 'INSERT INTO `membros`( `nome`, `endereco`, `cidade`, `estado_provincia`, 
       `codigo_postal`, `pais`, `telefone`, `balanco`, `email`, `password`)' . 'VALUES ([value-2],[value-3],
       [value-4],[value-5],[value-6],[value-7],[value-8],[value-9],[value-10],[value-11])';

  /*             $sql = 'INSERT INTO dbname . `membros`(`nome`, `endereco`, `cidade`, `estado_provincia`, 
       `codigo_postal`, `pais`, `telefone`, `balanco`, `email`, `password`)' . 'VALUES ([value-2],[value-3],
       [value-4],[value-5],[value-6],[value-7],[value-8],[value-9],[value-10],[value-11])';
 */ 
 /*
                $sql = 'INSERT INTO `membros`(`primeironome`, `ultimonome`, `endereco`, `cidade`, 
 `provincia`, `codigopostal`, `pais`, `telefone`, `email`)'
. 'VALUES (:primeironome,:ultimonome,:endereco,:cidade,:provincia,:codigopostal,
 :pais,:telefone,:email)';





    /*             $sql = 'INSERT INTO `chimasonline`.`membros` (`nome`, `endereco`, `cidade`, `estado_provincia`, `codigo_postal`, `pais`, `telefone`, `balanco`, `email`, `password`)'
       . 'VALUES (:pimeironome, :endereco, :cidade, :provincia, :codigopostal, :pais, :telefone, :balanco, :email, :password);';


                 $sql = 'INSERT INTO `membros` (`nome`, `endereco`, `cidade`, `estado_provincia`, `codigo_postal`, `pais`, `telefone`, `balanco`, `email`, `password`)'
       . 'VALUES (:nome, :endereco, :cidade, :estado_provincia, :codigo_postal, :pais, :telefone, :balanco, :email, :password);';


                 $sql = 'INSERT INTO `chimasonline`.`membros` (`nome`, `endereco`, `cidade`, `estado_provincia`, `codigo_postal`, `pais`, `telefone`, `balanco`, `email`, `password`) 
         ' . 'VALUES (primeironome ,endereco ,cidade ,provincia ,codigopostal ,pais , telefone,balanco ,email,password )';

      $sql = 'INSERT INTO `membros`(`nome`, `endereco`, `cidade`, `estado_provincia`, 
     `codigo_postal`, `pais`, `telefone`, `balanco`, `email`, `password`) VALUES = ?';   


  funcionou melhor esses dois tenho que explorar mais  lembrar q n tinha parametro    
        $sql = 'INSERT INTO `chimasonline`.`membros` ( `primeironome`, `ultimonome`, `endereco`, `cidade`, 
            `provincia`, `codigopostal`, `pais`, `email`, `telefone`, `password`) 
  . 'VALUES ( :primeironome ,:ultimonome, :endereco , :cidade , :provincia, :codigopostal , :pais , :email, :telefone, :password)';'  


   $sql = 'INSERT INTO `chimasonline`.`membros` ( `nome`, `endereco`, `cidade`, `estado_provincia`, `codigo_postal`, `pais`, `password`) 
  VALUES ( hdd, f, bll, bgrio, 00000, qrf, password)'; 


       // $sql = 'INSERT INTO `chimasonline`.`membros` (`nome`, `endereco`, `cidade`, `estado_provincia`, `codigo_postal`, `pais`, `telefone`, `balanco`, `email`, `password`) 
         ' . 'VALUES ( )';  

             $sql  = 'INSERT INTO `membros`(`primeironome`, `ultimonome`, `endereco`, `cidade`, `provincia`, 
             `codigopostal`, `pais`, `password`)' . 'VALUES ( ?,?,?,?,?,?,?,?,?,?);';

           */     
        $stmt = $pdo->prepare($sql);


               $stmt->execute(array($data));
        $result = $stmt->fetch(PDO::FETCH_ASSOC);



                 return $result;

    } 
    /*
     * Returns database row for 1 member
     * @param string $email
     * @return array $row[] = array('title' => title, 'description' => description, etc.)
     */




    public function loginByName($email, $password)
    {
        $pdo = $this->getPdo();
        $sql = 'SELECT * FROM `membros` WHERE `email` = ? AND `password` = ?';
        $stmt = $pdo->prepare($sql);
        $stmt->execute(array($email, $password));
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        return $result;
    }
    public function getHowManyMembers()
    {
        if (!$this->howManyMembers) {
            $pdo = $this->getPdo();
            $sql = 'SELECT COUNT(*) FROM `membros`';
            $stmt = $pdo->prepare($sql);
            $stmt->execute();
            // fetches as a numeric array
            $result = $stmt->fetch(PDO::FETCH_NUM);
            $this->howManyMembers = $result[0];
        }   
        return $this->howManyMembers;
    }
    /*
     * Returns array of arrays where each sub-array = 1 database row of Members
     * Searches name, address, city, state_province, country, email
     * @param string $search
     * @return array $row[] = array('title' => title, 'description' => description, etc.)
     */
    public function getMembersByKeyword($search)
    {
        $search = strip_tags($search);
        $search = str_ireplace(array("'",'-','"',';'), '', $search);
        $search = "'%" . $search . "%'";
        $pdo = $this->getPdo();
        $sql = 'SELECT * FROM `membros` WHERE '
              . '`primeironome` LIKE ' . $search . ' OR '
              . '`cidade` LIKE ' . $search . ' OR '
              . '`email` LIKE ' . $search . ' ORDER BY `primeironome`';


        $stmt = $pdo->prepare($sql);
        $stmt->execute();
        $content = array();
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $content[] = $row;
        }
        return $content;
    }
    /*
     * Returns a safely quoted value
     * @param string $value
     * @return string $quotedValue
     */
    public function pdoQuoteValue($value)
    {
        $pdo = $this->getPdo();
        return $pdo->quote($value);
    }
    /*
     * Returns a PDO connection
     * If connection already made, returns that instance
     * @return PDO $pdo
     */
    public function getPdo()
    {
        if (!$this->db_pdo) {
            if ($this->debug) {
                $this->db_pdo = new PDO(DB_DSN, DB_USER, DB_PWD, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
            } else {
                $this->db_pdo = new PDO(DB_DSN, DB_USER, DB_PWD);
            }
        }
        return $this->db_pdo;
    }       

}

My addmember file (adicionarmembro.php) is:

我的addmember文件(adicionarmembro.php)是:

?php
// assign defaults
//$result='';
$mailStatus = '';
$data = array('email'       => 'email', 
              'primeironome'    => 'primeironome', 
              'ultimonome'  => 'ultimonome', 
              'endereco'    => 'endereco', 
              'cidade'      => 'cidade', 
              'provincia'       => 'provincia', 
                          'codigopostal'    => 'codigopostal', 
                          'pais'        => 'pais',    
              'telefone'    => 'telefone',
                 // 'password'  => 'password',
                          //'password_confirmacao'  => 'password_confirmacao',
             // 'dnano'     => 0,
             // 'dnmes' => 0,
            //  'dndia'     => 0,
                 // 'dn'        => 0,
);
$error = array('email'    => '', 
              'primeironome' => '', 
              'ultimonome'  => '', 
              'endereco'      => '', 
              'cidade'    => '', 
                  'provincia'     => '',
              'codigopostal'  => '', 
                          'pais'      => '', 
              'telefone' => '', 
              'dn'        => '',
);
if (isset($_POST['data'])) {
    $data = $_POST['data'];
    foreach ($data as $key => $value) {
        $data[$key] = strip_tags($value);
    }
    if (isset($data['dnano']) && isset($data['dnmes']) && isset($data['dndia'])) {
        try {
            $bdateString = sprintf('%4d-%02d-%02d', $data['dnano'], $data['dnmes'], $data['dndia']);
            $bdate = new DateTime($bdateString);
            $today = new DateTime();
            $interval16 = new DateInterval('P16Y');
            $bdate16 = $today->sub($interval16);
            if ($bdate > $bdate16) $error['dn'] = '<b class="error">Tem que ter pelo menos 16 anos!</b>';
        } catch (Exception $e) {
            $error['dn'] = '<b class="error">Data invalida</b>';
            echo $e->getMessage();
            exit;
        }

    } else {
        $error['dn'] = '<b class="error">Data invalida</b>';
    }
    if (!preg_match('/^[a-z][a-z0-9._-]+@(\w+\.)+[a-z]{2,6}$/i', $data['email'])) {
        $error['email'] = '<b class="error">endereco de email Invalido</b>';
    }
    if (!preg_match('/^[a-z0-9,. ]+$/i', $data['primeironome'])) {
        $error['primeironome'] = '<b class="error">O nome deve apenas conter letras, numeros, espacos "," ou "."</b>';
    }
    if (!preg_match('/[a-z0-9,. ]/i', $data['ultimonome'])) {
        $error['ultimonome'] = '<b class="error">O nome deve apenas conter letras, numeros, espacos "," or "."</b>';
    }
    if (!preg_match('/[a-z0-9,. ]/i', $data['endereco'])) {
        $error['endereco'] = '<b class="error">O endereco deve apenas conter letras, numeros, espacos "," ou "."</b>';
    }
    if (!preg_match('/[a-z0-9,. ]/i', $data['cidade'])) {
        $error['cidade'] = '<b class="error">A cidade deve apenas conter letras, numeros, espacos "," ou "."</b>';
    }
        if (!preg_match('/[a-z0-9,. ]/i', $data['provincia'])) {
        $error['provincia'] = '<b class="error">A provincia deve apenas conter letras, numeros, espacos "," ou "."</b>';
    }
    if (!preg_match('/^[a-z][0-9][a-z] [0-9][a-z][0-9]$|^\d{5}(-\d{4})?$/i', $data['codigopostal'])) {
        $error['codigopostal'] = '<b class="error"> codigo postal de Canada: A9A 9A9 <br />codigo postal de US: 99999 or 99999-9999<br />Se seu pais nao tem codigo postal digite 00000</b>';
        }
    if (!preg_match('/[a-z0-9,. ]/i', $data['pais'])) {
        $error['pais'] = '<b class="error">O pais deve apenas conter letras, numeros, espacos "," ou "."</b>';
    }
    if (!preg_match('/^\+[0-9]{1,3} \d{3}-\d{3}-\d{4}/', $data['telefone'])) {
        $error['telefone'] = '<b class="error">O numero do telephone deve star no formato +CC AAA-CCC-DDDD</b>';
    }
    // Verifica se o formulario e valido
    $isValid = TRUE;
    foreach ($error as $value) {
        if ($value) {
            $isValid = FALSE;
            break;
        }
    }

                  if ($isValid) {
        require_once('PHPMailer/class.phpmailer.php');
                require './Model/Members.php';
                  $memberTable = new Members();
        $address = "****@****.com";
        $newName = $data['primeironome'] . ' ' . $data['ultimonome'];
        $mail = new PHPMailer(); // defaults to using php "mail()"
        $body = 'Seja bemvindo a Chimas Online ' . $newName . '!'
              . '<br />Para confirmar o seu email, apenas responde a este email e nos faremos o resto...'
              . '<br />Desfrute!'
                          . '<br /> Clique em <a href = www.irenejovem.com> e continue a explorar os nossos produtos www.irenejovem.com';
        $mail->AddReplyTo($address,"ChimasOnline");
        $mail->SetFrom($address,"ChimasOnline");
        $mail->AddAddress($data['email'], $newName);
        $mail->Subject = 'Confirmacao de novo membro da ChimasOnline';
        $mail->AltBody = "Para ver a mensagem, use por favor um visualizador de email HTML compativel!"; // optional, comment out and test
        $mail->MsgHTML($body);
        if(!$mail->Send()) {
          $mailStatus = 'Erro ao enviar o email: ' . $mail->ErrorInfo;
        } else {
          $mailStatus = 'Email de confirmacao Enviado! Verifique o seu email e clique no link de confirmacao para efectivar o seu registro!';


                  $result = $memberTable->insertMember($data);


                }
    }
}
?>
    <div class="content">
    <br/>
    <div class="product-list">

        <h2>Cadastre-se na nossa pagina</h2>
        <br/>

        <b>Por favor, preencha a sua informacao.</b>
        <br/>
        <br/>
        <?php if ($mailStatus) echo '<br /><b class="confirm">', $mailStatus, '</b><br />'; ?>
        <br />
        <form action="?page=adicionarmembro" method="POST">
            <p>
                <label>Data de Nascimento: </label>
                <select name="data[dnano]">
                    <?php if ($data['dnano']) { echo '<option>', $data['dnano'], '</option>'; } ?>
                    <?php $year = date('Y'); ?>
                    <?php for($x = $year; $x > ($year - 120); $x--) { ?>
                        <option><?php echo $x; ?></option>
                    <?php }     ?>
                </select>
                <select name="data[dnmes]">
                    <?php   
                    $month = array(1 => 'Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez');
                    if ($data['dnmes']) { 
                        printf('<option value="%02d">%s</option>', 
                               $data['dnmes'], $month[(int) $data['dnmes']]);
                    } 
                    for($x = 1; $x <= 12; $x++) {
                        printf('<option value="%02d">%s</option>', $x, $month[$x]);
                        echo PHP_EOL;
                    }       
                    ?>
                </select>
                <select name="data[dndia]">
                    <?php if ($data['dndia']) { echo '<option>', $data['dndia'], '</option>'; } ?>
                    <?php for($x = 1; $x < 32; $x++) { ?>
                        <option><?php echo $x; ?></option>
                    <?php }     ?>
                </select> 

                <?php if ($error['dn']) echo '<p>', $error['dn']; ?>
            <p>
                <label>Email: </label>
                <input type="text" name="data[email]" value="<?php echo htmlspecialchars($data['email']); ?>" />
                <?php if ($error['email']) echo '<p>', $error['email']; ?>
            <p>
            <p>
                <label>Primeiro Nome: </label>
                <input type="text" name="data[primeironome]" value="<?php echo $data['primeironome']; ?>" />
                <?php if ($error['primeironome']) echo '<p>', $error['primeironome']; ?>
            <p>
            <p>
                <label>Ultimo Nome: </label>
                <input type="text" name="data[ultimonome]" value="<?php echo $data['ultimonome']; ?>" />
                <?php if ($error['ultimonome']) echo '<p>', $error['ultimonome']; ?>
            <p>
            <p>
                <label>Endereco: </label>
                <input type="text" name="data[endereco]" value="<?php echo $data['endereco']; ?>" />
                <?php if ($error['endereco']) echo '<p>', $error['endereco']; ?>
            <p>
            <p>
                <label>Cidade: </label>
                <input type="text" name="data[cidade]" value="<?php echo $data['cidade']; ?>" />
                <?php if ($error['cidade']) echo '<p>', $error['cidade']; ?>
            <p>
            <p>
                            <label>Provincia: </label>
                <input type="text" name="data[provincia]" value="<?php echo $data['provincia']; ?>" />
                <?php if ($error['provincia']) echo '<p>', $error['provincia']; ?>
            <p>
            <p>
                <label>Codigo Postal: </label>
                <input type="text" name="data[codigopostal]" value="<?php echo $data['codigopostal']; ?>" />
                <?php if ($error['codigopostal']) echo '<p>', $error['codigopostal']; ?>
            <p>
            <p>
                            <label>Pais: </label>
                <input type="text" name="data[pais]" value="<?php echo $data['pais']; ?>" />
                <?php if ($error['pais']) echo '<p>', $error['pais']; ?>
            <p>
            <p>
                <label>Telefone: </label>
                <input type="text" name="data[telefone]" value="<?php echo $data['telefone']; ?>" />
                <?php if ($error['telefone']) echo '<p>', $error['telefone']; ?>
            <p>
            <p>
                <input type="reset" name="data[clear]" value="Clear" class="button"/>
                <input type="submit" name="data[submit]" value="Submit" class="button marL10"/>
            <p>
        </form>
    </div><!-- product-list -->
</div>

my users table is

我的用户表是

users table structure

用户表结构

but it shows like: users table after the INSERT command

但它显示如下:INSERT命令后的users表

Please help, I'm desperated.

请帮忙,我很绝望。

1 个解决方案

#1


0  

It seems most of the queries you made were pretty close. I would use this one:
INSERT INTO `membros` (`primeironome`, `ultimonome`, `endereco`, `cidade`, `provincia`, `codigopostal`, `pais`, `telefone`, `email`) VALUES (:primeironome, :ultimonome, :endereco, :cidade, :provincia, :codigopostal, :pais, :telefone, :email);
or this one:
INSERT INTO `membros` SET `primeironome` = :primeironome, `ultimonome` = :ultimonome, `endereco` = :endereco, `cidade` = :cidade, `provincia` = :provincia, `codigopostal` = :codigopostal, `pais` = :pais, `telefone` = :telefone, `email` = :email;

看来你提出的大多数查询都非常接近。我会用这个:INSERT INTO`membros`(`primeironome`,`ultimonome`,`endereco`,`cidade`,`provincia`,`codigopostal`,`pais`,`telefone`,`email`)VALUES( :primeironome,:ultimonome,:endereco,:cidade,:provincia,:codigopostal,:pais,:telefone,:email);或者这个:插入`membros` SET`pimironome` =:primeironome,`ultimonome` =:ultimonome,`endereco` =:endereco,`cidade` =:cidade,`provincia` =:provincia,`codigopostal` =: codigopostal,`pais` =:pais,`telefone` =:telefone,`email` =:email;

Call prepare() with that, and then make sure the array you pass to execute() looks like this (replace [...] with the actual value):
["primeironome" => [...], "ultimonome" => [...], "endereco" => [...], "cidade" => [...], "provincia" => [...], "codigopostal" => [...], "pais" => [...], "telefone" => [...], "email" => [...] ]

使用它调用prepare(),然后确保传递给execute()的数组看起来像这样(用实际值替换[...]):[“primeironome”=> [...],“ultimonome” => [...],“endereco”=> [...],“cidade”=> [...],“provincia”=> [...],“codigopostal”=> [... ],“pais”=> [...],“telefone”=> [...],“email”=> [...]]

That should work just fine. If it doesn't, the problem is either in the column names (check the spelling) or in the actual values you're passing to the function (for example, passing an array would not go well).

这应该工作得很好。如果没有,问题是列名(检查拼写)或您传递给函数的实际值(例如,传递数组不会很好)。

EDIT - doing this in the comments was awkward

Ok, so I'm trying to recreate your situation now. I created a table with the following CREATE code:

好的,所以我现在正试图重现你的情况。我创建了一个包含以下CREATE代码的表:

CREATE TABLE `membros` (
    `membro_id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
    `primeironome` VARCHAR(15) NOT NULL,
    `ultimonome` VARCHAR(15) NOT NULL,
    `endereco` VARCHAR(256) NOT NULL,
    `cidade` VARCHAR(64) NOT NULL,
    `provincia` CHAR(32) NULL DEFAULT NULL,
    `codigopostal` CHAR(10) NOT NULL,
    `pais` CHAR(3) NOT NULL,
    `datanascimento` DATE NULL DEFAULT NULL,
    `telefone` CHAR(16) NULL DEFAULT NULL,
    `balanco` DECIMAL(10,2) UNSIGNED NULL DEFAULT NULL,
    `email` VARCHAR(250) NOT NULL,
    `password` VARCHAR(16) NULL DEFAULT NULL,
    PRIMARY KEY (`membro_id`)
)
ENGINE=MyISAM;

First off some notes: the first and last name columns are too short I think (only 15 chars, I'd personally use 30 for first and 50 for last). Also, from your password column being only 16 characters I deduce 2 things: your max password length is too short (this makes brute-force attacks easier), and you store your passwords unhashed. NEVER, NEVER store your passwords unhashed!

首先注意一些注意事项:我认为名字和姓氏的名字太短了(只有15个字符,我个人首先使用30个字符,最后使用50个字符)。此外,从您的密码列只有16个字符,我推断了两件事:您的最大密码长度太短(这使得暴力攻击更容易),并且您的密码保存完好无损。永远,永远不要存储你的密码!

Moving on to your actual problem: I literally executed the following code, and it works. All you have to do is make sure the $data array you ultimately pass to your query looks the same (with different values, but with exactly the same keys).

继续你的实际问题:我真的执行了以下代码,它的工作原理。您所要做的就是确保最终传递给查询的$ data数组看起来相同(使用不同的值,但使用完全相同的键)。

//I assume you have a working database connection, mine is the variable $connection
$data = ["primeironome" => "mi nome", "ultimonome" => "mi ultimo nome", "endereco" => "test 12345", "cidade" => "rio de janeiro", "provincia" => "no se", "codigopostal" => "12345 abc", "pais" => "BRA", "telefone" => "0123456789", "email" => "test@example.com"];
$prepStatement = $connection->prepare("INSERT INTO `membros` (`primeironome`, `ultimonome`, `endereco`, `cidade`, `provincia`, `codigopostal`, `pais`, `telefone`, `email`) VALUES (:primeironome, :ultimonome, :endereco, :cidade, :provincia, :codigopostal, :pais, :telefone, :email);");
$prepStatement->execute($data);

I also noted a bug in your original code while looking at this: your $data variable is already an array when you get it, but you pass it as $stmt->execute(array($data));. This should be $stmt->execute($data);. You also try to fetch() results afterwards: an INSERT query does not return results, so there is nothing to fetch. If you want to know if it was successful, do this:

我还注意到你的原始代码中存在一个错误:你的$ data变量在你得到它时已经是一个数组,但是你把它传递给$ stmt-> execute(array($ data));.这应该是$ stmt-> execute($ data);.您还尝试在之后获取()结果:INSERT查询不返回结果,因此无需获取任何内容。如果您想知道它是否成功,请执行以下操作:

$status = $stmt->execute($data);

The $status variable will then contain TRUE, FALSE or NULL.

然后$ status变量将包含TRUE,FALSE或NULL。

As a final point, this is what I recommended earlier for your foreach loop to parse the post data:

最后一点,这是我之前为foreach循环推荐的解析帖子数据的内容:

//make the default data array (with empty values, this is just to make sure the keys exist)
$data = ["primeironome" => "", "ultimonome" => "", "endereco" => "", "cidade" => "", "provincia" => "", "codigopostal" => "", "pais" => "", "telefone" => "", "email" => ""];

//REMOVE THIS LINE ->
//$data = $_POST['data'];

//now add your values from the $_POST array
foreach ($data as $key => $value)
{
    if (isset($_POST[$key]))
    {
        $data[$key] = strip_tags($_POST[$key]);
    }
}

Now you only have the keys you defined in your $data array at the top of your file, and any which were not present in $_POST are still the default you set there.

现在,您只在文件顶部的$ data数组中定义了键,而$ _POST中不存在的键仍然是您在那里设置的默认键。

#1


0  

It seems most of the queries you made were pretty close. I would use this one:
INSERT INTO `membros` (`primeironome`, `ultimonome`, `endereco`, `cidade`, `provincia`, `codigopostal`, `pais`, `telefone`, `email`) VALUES (:primeironome, :ultimonome, :endereco, :cidade, :provincia, :codigopostal, :pais, :telefone, :email);
or this one:
INSERT INTO `membros` SET `primeironome` = :primeironome, `ultimonome` = :ultimonome, `endereco` = :endereco, `cidade` = :cidade, `provincia` = :provincia, `codigopostal` = :codigopostal, `pais` = :pais, `telefone` = :telefone, `email` = :email;

看来你提出的大多数查询都非常接近。我会用这个:INSERT INTO`membros`(`primeironome`,`ultimonome`,`endereco`,`cidade`,`provincia`,`codigopostal`,`pais`,`telefone`,`email`)VALUES( :primeironome,:ultimonome,:endereco,:cidade,:provincia,:codigopostal,:pais,:telefone,:email);或者这个:插入`membros` SET`pimironome` =:primeironome,`ultimonome` =:ultimonome,`endereco` =:endereco,`cidade` =:cidade,`provincia` =:provincia,`codigopostal` =: codigopostal,`pais` =:pais,`telefone` =:telefone,`email` =:email;

Call prepare() with that, and then make sure the array you pass to execute() looks like this (replace [...] with the actual value):
["primeironome" => [...], "ultimonome" => [...], "endereco" => [...], "cidade" => [...], "provincia" => [...], "codigopostal" => [...], "pais" => [...], "telefone" => [...], "email" => [...] ]

使用它调用prepare(),然后确保传递给execute()的数组看起来像这样(用实际值替换[...]):[“primeironome”=> [...],“ultimonome” => [...],“endereco”=> [...],“cidade”=> [...],“provincia”=> [...],“codigopostal”=> [... ],“pais”=> [...],“telefone”=> [...],“email”=> [...]]

That should work just fine. If it doesn't, the problem is either in the column names (check the spelling) or in the actual values you're passing to the function (for example, passing an array would not go well).

这应该工作得很好。如果没有,问题是列名(检查拼写)或您传递给函数的实际值(例如,传递数组不会很好)。

EDIT - doing this in the comments was awkward

Ok, so I'm trying to recreate your situation now. I created a table with the following CREATE code:

好的,所以我现在正试图重现你的情况。我创建了一个包含以下CREATE代码的表:

CREATE TABLE `membros` (
    `membro_id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
    `primeironome` VARCHAR(15) NOT NULL,
    `ultimonome` VARCHAR(15) NOT NULL,
    `endereco` VARCHAR(256) NOT NULL,
    `cidade` VARCHAR(64) NOT NULL,
    `provincia` CHAR(32) NULL DEFAULT NULL,
    `codigopostal` CHAR(10) NOT NULL,
    `pais` CHAR(3) NOT NULL,
    `datanascimento` DATE NULL DEFAULT NULL,
    `telefone` CHAR(16) NULL DEFAULT NULL,
    `balanco` DECIMAL(10,2) UNSIGNED NULL DEFAULT NULL,
    `email` VARCHAR(250) NOT NULL,
    `password` VARCHAR(16) NULL DEFAULT NULL,
    PRIMARY KEY (`membro_id`)
)
ENGINE=MyISAM;

First off some notes: the first and last name columns are too short I think (only 15 chars, I'd personally use 30 for first and 50 for last). Also, from your password column being only 16 characters I deduce 2 things: your max password length is too short (this makes brute-force attacks easier), and you store your passwords unhashed. NEVER, NEVER store your passwords unhashed!

首先注意一些注意事项:我认为名字和姓氏的名字太短了(只有15个字符,我个人首先使用30个字符,最后使用50个字符)。此外,从您的密码列只有16个字符,我推断了两件事:您的最大密码长度太短(这使得暴力攻击更容易),并且您的密码保存完好无损。永远,永远不要存储你的密码!

Moving on to your actual problem: I literally executed the following code, and it works. All you have to do is make sure the $data array you ultimately pass to your query looks the same (with different values, but with exactly the same keys).

继续你的实际问题:我真的执行了以下代码,它的工作原理。您所要做的就是确保最终传递给查询的$ data数组看起来相同(使用不同的值,但使用完全相同的键)。

//I assume you have a working database connection, mine is the variable $connection
$data = ["primeironome" => "mi nome", "ultimonome" => "mi ultimo nome", "endereco" => "test 12345", "cidade" => "rio de janeiro", "provincia" => "no se", "codigopostal" => "12345 abc", "pais" => "BRA", "telefone" => "0123456789", "email" => "test@example.com"];
$prepStatement = $connection->prepare("INSERT INTO `membros` (`primeironome`, `ultimonome`, `endereco`, `cidade`, `provincia`, `codigopostal`, `pais`, `telefone`, `email`) VALUES (:primeironome, :ultimonome, :endereco, :cidade, :provincia, :codigopostal, :pais, :telefone, :email);");
$prepStatement->execute($data);

I also noted a bug in your original code while looking at this: your $data variable is already an array when you get it, but you pass it as $stmt->execute(array($data));. This should be $stmt->execute($data);. You also try to fetch() results afterwards: an INSERT query does not return results, so there is nothing to fetch. If you want to know if it was successful, do this:

我还注意到你的原始代码中存在一个错误:你的$ data变量在你得到它时已经是一个数组,但是你把它传递给$ stmt-> execute(array($ data));.这应该是$ stmt-> execute($ data);.您还尝试在之后获取()结果:INSERT查询不返回结果,因此无需获取任何内容。如果您想知道它是否成功,请执行以下操作:

$status = $stmt->execute($data);

The $status variable will then contain TRUE, FALSE or NULL.

然后$ status变量将包含TRUE,FALSE或NULL。

As a final point, this is what I recommended earlier for your foreach loop to parse the post data:

最后一点,这是我之前为foreach循环推荐的解析帖子数据的内容:

//make the default data array (with empty values, this is just to make sure the keys exist)
$data = ["primeironome" => "", "ultimonome" => "", "endereco" => "", "cidade" => "", "provincia" => "", "codigopostal" => "", "pais" => "", "telefone" => "", "email" => ""];

//REMOVE THIS LINE ->
//$data = $_POST['data'];

//now add your values from the $_POST array
foreach ($data as $key => $value)
{
    if (isset($_POST[$key]))
    {
        $data[$key] = strip_tags($_POST[$key]);
    }
}

Now you only have the keys you defined in your $data array at the top of your file, and any which were not present in $_POST are still the default you set there.

现在,您只在文件顶部的$ data数组中定义了键,而$ _POST中不存在的键仍然是您在那里设置的默认键。