首页 > 解决方案 > 如何将数据保存在同一行中?

问题描述

嗨,我如何将数据保存在数据库的同一行中,我正在使用此代码保存到数据库中,但它保存在不同的两行中,请帮助我,谢谢。这是数据库的屏幕截图。 截屏

<?php

    $users = array("username"=>"Kaleem", "address"=>"abc");

class dbase{

    public function dbinsert($table,$users)
    {
        foreach ($users as $key => $value) 
        {
            $sql = "INSERT INTO $table (`$key`) VALUES ('$value')";
            $success = $this->conn->query($sql);
            if($success)
            {
                echo "Data inserted";
            }
        }
    }


        public function __construct ()
        {

            $this->conn = new mysqli('localhost','root','','dbase');

            if($this->conn)
            {
                echo "Connected<br>";
            }
        }


}

$obj = new dbase;
$obj->dbinsert('users',$users);

标签: phparraysfunction

解决方案


首先,我推荐数组为:

$users = array(array("username"=>"Kaleem", "address"=>"abc"));

这样,每个用户都将是那个大 $users 数组中的一个数组。如果你这样做,你的 php 代码应该是:

<?php

$users = array("username"=>"Kaleem", "address"=>"abc");

class dbase{

public function dbinsert($table,$users)
{
    foreach ($users as $user) //better have descriptive names in variables, and we do not need to know the key! 
    {
        $username = $user['username']; 
        $user_address = $user['addess'];
        $sql = "INSERT INTO $table (`username`, 'addess') VALUES ('$username','$user_address')"; //lets insert both of them in the same row
        $success = $this->conn->query($sql);
        if($success)
        {
            echo "Data inserted";
        }
    }
}


    public function __construct ()
    {

        $this->conn = new mysqli('localhost','root','','dbase');

        if($this->conn)
        {
            echo "Connected<br>";
        }
    }


}
$obj = new dbase;
$obj->dbinsert('users',$users);

我希望这个解释就足够了,您将用户名和地址作为元素进行迭代,并将它们分别插入到不同的行中,而不是在单行中进行。


推荐阅读