Suppose I have a table like the following:
id| name | family
---+------+---------
1 | iman | marashi
2 | mike | ...
3 | john | ...
4 | |
and I also have an Json object to insert to the table like the following:
{"name ":"will","family":"smith"}
How can I insert together an Json object to a table given that the fields of the table and the keys of the Json object are the same?
Without having to parsing the Json object.
I don't want to use this method:
$name = $data["name"];
$family = $data["family"];
If you're using PDO, you can provide an associative array to fill in the parameters of a query.
$query = $conn->prepare("INSERT INTO yourTable (name, family) VALUES (:name, :family)");
$data = json_decode($json_object, true);
$query->execute($data);
I think that Barmar provided the correct answer if you are running PDO.
For the sake a completeness, you could also do this purely with MySQL, using json_extract() to read directly from the json string given as parameter:
insert into mytable (name, family) values(
json_unquote(json_extract(:js, '$.name')),
json_unquote(json_extract(:js, '$.family'))
);
Demo on DB Fiddle:
create table mytable (
id int auto_increment primary key,
name varchar(50),
family varchar(50)
):
insert into mytable (name, family) values(
json_unquote(json_extract('{"name":"will","family":"smith"}', '$.name')),
json_unquote(json_extract('{"name":"will","family":"smith"}', '$.family'))
);
select * from mytable;
id | name | family
-: | :--- | :-----
1 | will | smith
Related
I have searched that there is already a way in inserting avoiding the duplicate error
ref: MySQL: Insert record if not exists in table
INSERT INTO table_listnames (name, address, tele)
SELECT * FROM (SELECT 'Unknown' AS name, 'Unknown' AS address, '022' AS tele) AS tmp
WHERE NOT EXISTS (
SELECT name FROM table_listnames WHERE name = 'Unknown'
) LIMIT 1;
Query OK, 1 row affected (0.00 sec)
Records: 1 Duplicates: 0 Warnings: 0
SELECT * FROM `table_listnames`;
+----+---------+-----------+------+
| id | name | address | tele |
+----+---------+-----------+------+
| 1 | Rupert | Somewhere | 022 |
| 2 | John | Doe | 022 |
| 3 | Unknown | Unknown | 022 |
+----+---------+-----------+------+
is there a way for this to do in batch?
or how is the format in adding data as a batch
ref: insert multiple rows via a php array into mysql
Planning to integrate this one
$sql = array();
foreach( $data as $row ) {
$sql[] = '("'.mysql_real_escape_string($row['text']).'", '.$row['category_id'].')';
}
mysql_query('INSERT INTO table (text, category) VALUES '.implode(',', $sql));
is there a way?
I would suggest using the ON DUPLICATE KEY syntax for this. This will simplify the query, and allow the use of the VALUES() statement, which is handy to pass parameters from your application.
For this to work, you need a unique (or primary key) constraint on colum name. Create it if it does not exist:
create unique index idx_table_listnames on table_listnames(name);
Then, you can do:
insert into table_listnames(name, address, tele)
values('Unknown', 'Unknown', '022')
on duplicate key update name = values(name)
The conflict clause traps violations on the unique index, and performs a no-op update.
Side note: use parameterized queries to pass data from your application to the query; escaping input is not enough to make your query safe.
I have a string, I need to put this information into a database.
I'm not sure of the best way to manipulate the string to use with an insert script. my skill level is very low. I've read a bit about looping but dont know how or where to begin.
Is there a better way to manipulate the string to make db insert easier?
Many thanks
<?php
$date = $_SESSION['date'];
$string="UnAllocated,SUSY MCGRANAHAN,R,null,null;
UnAllocated,BERNADINE WASHER,A,null,null;
UnAllocated,DAVID KEHRER,R,null,null";
/*
I have been trying to break it down in the following way.
$new = preg_split("[;]", $string);
$x1=(explode(',', $new[1]));
$x2=(explode(',', $new[2]));
I would like to insert it into the following table
INSERT INTO table ("date, team, name, driver, car
values
('$date' ,'$x1[0]', '$x1[1]', '$x1[2]', '$x1[3]'),
('$date' ,'$x2[0]', '$x2[1]', '$x2[2]', '$x2[3]')");
*/
Table
| date | team | name | driver | car |
---------------------------------------------------------
| cur | unallocated | SUSY.. | A | null |
| cur | unallocated | BERN...| R | null |
You can use below code to insert into your database table.
<?php
$string="UnAllocated,SUSY MCGRANAHAN,R,null,null;
UnAllocated,BERNADINE WASHER,A,null,null;
UnAllocated,DAVID KEHRER,R,null,null";
$arr = explode(';', $string);
foreach($arr as $row){
$arr_row = explode(',', trim($row)); // Converting each line to array which can be used as values.
print_r($arr_row);
// Write your insert statement into your database.
// e.g INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...);
}
Now you can use $arr_row[0], $arr_row[1] ... and so on to build your sql.
I've got a txt file with many rows. I insert data from every row into db.
foreach (... => ...) {
...
$types = new QueryTypes();
$types->query_type = $prepared_data_from_file;
$types->save();
$logs = new Logs();
$logs->query_type = ...
...
}
-----------------------------------------------------
| LOGS |
-----------------------------------------------------
| log_id (PK) | query_type (FK from query_type_id) |
-----------------------------------------------------
---------------------------------
| QUERYTYPES |
---------------------------------
|query_type_id (PK)| query_type |
---------------------------------
I need something like
INSERT INTO LOGS(query_type) VALUES (SELECT query_type_id FROM QUERYTYPES)
How could I insert column query_type_id from QUERYTYPES into column query_type in LOGS in yii2?
You use a SELECT query instead of VALUES
INSERT INTO LOGS (query_type)
SELECT query_type_id
FROM QUERYTYPES
Do you mean something like this ? :
INSERT INTO LOGS VALUES(NULL, (SELECT query_type_id FROM QUERYTYPES WHERE query_type = 'your_query_type_here'))
Table_A
+--------+-----------+---------+
| id | name | views |
+--------+-----------++--------+
| num | text | int |
+--------+-----------+---------+
| 1 | Video 1 | 10 |
| NULL | NULL | 0 |
| NULL | NULL | 0 |
| NULL | NULL | 0 |
| NULL | NULL | 0 |
+--------+-----------+---------+
<a href="video.php?id=video1&idtitle=Hello%20Video1">
<a href="video.php?id=video2&idtitle=Hello%20Video2">
<a href="video.php?id=video3&idtitle=Hello%20Video3">
I'm trying to make the script do something like this.
1.User click on link
2.User is on video.php?id=video1
3.Mysql then add a +1 to my id column #1
4.then take the video title from $videoName
5.Mysql take the title inside of $videoname and store it on name column #2
6.Mysql then add +1 to Views everytime ID 1 is view
7.Mysql is now finish with Row 1
8.Now Mysql will repeat that same step if video.php?id=video2 and so on,
How can i make this happen?
$id = $_GET['id'];
$videoName = $_GET['idtitle'];
$pdo = new PDO('mysql:localhost;dbname=videocount', 'root', '');
$userip = $_SERVER["REMOTE_ADDR"];
if($userip){
$pdo->query("UPDATE Table_A SET (`id`, `name`, `views`)
VALUES (NULL,$videoName, views+1)");
}
I also try the code below but still no luck.
if($userip){
$pdo->query("INSERT INTO `videocount`.`Table_A` (`id`, `name`, `views`)
VALUES (NULL, '$videoname', 'views'+1)");
}
UPDATE instead of UPDATED, VALUES instead of VALUE. In addition you have to add a WHERE condition to your query to select record to update.
This is another correct syntax:
$pdo->query( "UPDATE `Table_A` SET `views`=`views`+1 WHERE `id`='$id'" );
Edit:
To update also the video name you can perform this query:
$pdo->query( "UPDATE `Table_A` SET `name`='{$videoName}', `views`=`views`+1 WHERE `id`='$id'" );
On the border, you should bind the variable values to avoid errors with titles special characters.
See more about binding and MySQL UPDATE syntax
I think there is a little confusion about data view logic.
First of all, you need to save all data into database, then list them for user.
When the use click the link to view this video, the column of views need to be updated.
I have Database table of Questions. I use the integer variable Id to sort all the elements of the table.
What do I want?
Whenever, a new question is added. It is assigned a new id, which is 1 greated than the ID of the last question in my database.
Here is what I do:
include('dbconnect.php');
$ids = $connection->prepare('SELECT * FROM question ORDER BY id ASC');
$ids->execute(array());
$result = $ids->fetchAll(PDO::FETCH_ASSOC);
$new_id = end($result['id']); //Error in this line.
$new_id = $new_id + 1;
But, I always get the error
Warning: end() expects parameter 1 to be array, null given in /Applications/MAMP/htdocs/question/submit.php on line 20
I am using the FetchAll statement so I feel, that an array should be returned. Can anyone figure out where is the error.
Each New Question, which is added to the database gets an ID of 1.
As documented under Using AUTO_INCREMENT:
The AUTO_INCREMENT attribute can be used to generate a unique identity for new rows:
CREATE TABLE animals (
id MEDIUMINT NOT NULL AUTO_INCREMENT,
name CHAR(30) NOT NULL,
PRIMARY KEY (id)
);
INSERT INTO animals (name) VALUES
('dog'),('cat'),('penguin'),
('lax'),('whale'),('ostrich');
SELECT * FROM animals;
Which returns:
+----+---------+
| id | name |
+----+---------+
| 1 | dog |
| 2 | cat |
| 3 | penguin |
| 4 | lax |
| 5 | whale |
| 6 | ostrich |
+----+---------+
No value was specified for the AUTO_INCREMENT column, so MySQL assigned sequence numbers automatically. You can also explicitly assign NULL or 0 to the column to generate sequence numbers.