php - 如何将数据保存在同一行中?
问题描述
嗨,我如何将数据保存在数据库的同一行中,我正在使用此代码保存到数据库中,但它保存在不同的两行中,请帮助我,谢谢。这是数据库的屏幕截图。
<?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);
解决方案
首先,我推荐数组为:
$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);
我希望这个解释就足够了,您将用户名和地址作为元素进行迭代,并将它们分别插入到不同的行中,而不是在单行中进行。
推荐阅读
- javascript - 本地存储更改事件 + 反应
- arrays - 对子字段进行排序并存储在数组 awk 中
- javascript - 循环生成带有 1 个 JQuery 函数的按钮,这可能吗?
- python - 基于全局变量值django中间件更新模型
- javascript - 未捕获的 SyntaxError:意外的令牌导出 - popper.js 错误
- java - 这段代码的哪一部分减慢了我的程序
- c - 使用 C 中的指针创建无空格字符串
- java - 使用 AsyncTask 显示输入流文件读取进度
- java - Appium:有没有办法在没有 IPA 的情况下自动化应用程序?
- c# - 如何在 C# 中将数组转换为字典