Home  >  Article  >  Database  >  How to convert array into MySQL query statement in php

How to convert array into MySQL query statement in php

WBOY
WBOYforward
2023-06-01 23:11:25638browse

  1. Convert an array into an INSERT statement

First, let us consider how to convert an array into INSERT statement. Suppose we have an array named $person, which contains the following key-value pairs:

$person = array(
   'name' => 'John',
   'age' => 30,
   'gender' => 'Male'
);

In order to convert this array into a MySQL INSERT statement, we will need to iterate through the array and store its keys and values As part of the SQL statement. The following is a code example that demonstrates how to convert the $person array into a MySQL INSERT statement:

$sql = "INSERT INTO persons (name, age, gender) VALUES ('" . $person['name'] . "', " . $person['age'] . ", '" . $person['gender'] . "')";

We first save the basic structure of the INSERT statement into the variable $sql. We will then replace each key and value in the reference array $person. Note that we need to enclose these values ​​in quotes since the quote brackets may contain spaces or special characters.

  1. Convert array into UPDATE statement

In PHP programming, we often need to update rows in database tables data. We can use the UPDATE statement to update an array that already contains updated values. The following code example demonstrates how to convert an array into a MySQL UPDATE statement:

$person = array(
   'id' => 100,
   'name' => 'John Doe',
   'age' => 35,
   'gender' => 'Male'
);

$sql = "UPDATE persons SET name='" . $person['name'] . "', age=" . $person['age'] . ", gender='" . $person['gender'] . "' WHERE id=" . $person['id'];

We use the UPDATE statement to update the database table named persons. We use the id key in the $person array to determine which row to update. We use the SET clause to specify the columns to be updated, and the WHERE clause to limit the rows to be updated.

  1. Convert an array into a SELECT statement

Now, let us consider how to convert an array into a SELECT statement. Generally, we use the SELECT statement to query data from database tables. The following is a code example for converting an array into a MySQL SELECT statement:

$person = array(
   'id' => 100,
   'name' => 'John'
);

$sql = "SELECT * FROM persons WHERE id=" . $person['id'] . " AND name='" . $person['name'] . "'";

We use the id and name keys in the $person array to restrict as the basis for this example. Use the wildcard character * to indicate that we want to retrieve all columns in the table named persons. We use the AND operator to connect multiple matching conditions.

The above is the detailed content of How to convert array into MySQL query statement in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete