Database-related data types in PHP and their operation examples
1. Introduction
The database is one of the most important components of the application. It is responsible for storing and managing the data required by the application. . In PHP, we can use a variety of methods to operate databases, such as MySQL, SQLite, Oracle, etc. This article will focus on commonly used database-related data types in PHP and their operation examples.
2. Data type
Sample code:
$username = 'John'; $password = '12345'; $content = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.';
Sample code:
$user_id = 1; $age = 25;
Sample code:
$price = 9.99; $latitude = 37.7749; $longitude = -122.4194;
Sample code:
$is_logged_in = true; $is_purchased = false;
Sample code:
$users = array('John', 'Mary', 'Tom'); $products = array('Apple' => 2.99, 'Banana' => 1.99, 'Orange' => 3.99);
Sample code:
class User { public $name; public $email; public function __construct($name, $email) { $this->name = $name; $this->email = $email; } } $user = new User('John', 'john@example.com');
3. Data operation
Sample code:
$servername = "localhost"; $username = "root"; $password = "password"; $dbname = "my_database"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("连接数据库失败:" . $conn->connect_error); }
Sample code:
$sql = "INSERT INTO users (name, email) VALUES ('John', 'john@example.com')"; if ($conn->query($sql) === TRUE) { echo "数据插入成功"; } else { echo "数据插入失败:" . $conn->error; }
Sample code:
$sql = "SELECT * FROM users"; $result = $conn->query($sql); if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { echo "姓名:" . $row['name'] . ",邮箱:" . $row['email'] . "<br>"; } } else { echo "没有查询到数据"; }
Sample code:
$sql = "UPDATE users SET name = 'Mary' WHERE id = 1"; if ($conn->query($sql) === TRUE) { echo "数据更新成功"; } else { echo "数据更新失败:" . $conn->error; }
Sample code:
$sql = "DELETE FROM users WHERE id = 1"; if ($conn->query($sql) === TRUE) { echo "数据删除成功"; } else { echo "数据删除失败:" . $conn->error; }
IV. Summary
This article introduces common database-related data types in PHP and their operation examples. In actual development, appropriate data types are selected according to specific needs, and corresponding operation methods are used to add, delete, modify, and query the database to meet the needs of the application. Mastering database operations is an indispensable and important skill for PHP development.
The above is the detailed content of Database-related data types and their operation examples in PHP. For more information, please follow other related articles on the PHP Chinese website!