mysql insert into a value of a another query - mysql

Im new to PDO and trying to insert the result of a query into a table.
$statement_count_laeufer = $dbh->query('SELECT COUNT(Laeufer_Nachname)+1 FROM tbl_Laeufer;');
$result_count_laeufer = $statement_count_laeufer->fetchALL(PDO::FETCH_CLASS);
This is my query that counts the entries of a column in a table and now i want to use the result into a INSERT INTO query
$statement = $dbh->prepare("INSERT INTO tbl_Lauf (FK_ID_Veranstaltung, FK_ID_Laeufer) VALUES (".$_POST[event].", ".$result_count_laeufer." )
When I print/echo $statement_count_laeufer it shows me
Array ( [0] => stdClass Object ( [COUNT(Laeufer_Nachname)+1] => 2203 ) )
But i just want to use the 2203.
Thanks for help in advance.

You should be able to do this;
$statement = $dbh->prepare("INSERT INTO tbl_Lauf (FK_ID_Veranstaltung, FK_ID_Laeufer) VALUES (".$_POST[event].", (SELECT COUNT(Laeufer_Nachname)+1 FROM tbl_Laeufer)";
Mysql allows you use a select query result in an insert query

Related

INSERT INTO table name with both variables and SELECT FROM

I'm trying to insert an item into a table using both posted variables and something from another table. I'm not quite sure where I am going wrong because nothing is being added to the table. I'm super confused. Here is my code:
$stmt = $conn->prepare("INSERT INTO Student_Choices (Username,T1_Choice,T2_Choice,T3_Choice,Current_DB)
VALUES (:username,:t1choice,:t2choice,:t3choice, db.DB)
SELECT DB FROM Current_DB as db
");
$stmt->bindParam(':username', $_SESSION['username']);
$stmt->bindParam(':t1choice', $_POST["term1sport"]);
$stmt->bindParam(':t2choice', $_POST["term2sport"]);
$stmt->bindParam(':t3choice', $_POST["term3sport"]);
$stmt->execute();
The SELECT DB FROM Current_DB as db is not valid inside the INSERT sentence. Just execute this query first, then get the DB value into a variable, and finally use it with bindParam() as you do with the other parameters: Something like this:
/* Get the database name. */
$stmt = $conn->prepare("SELECT DB FROM DB_Year");
$stmt->execute();
$res = $stmt->fetchAll();
$db = $res[0]['DB'];
/* Execute the insert statement. */
$stmt = $conn->prepare(
"INSERT INTO Student_Choices (Username, T1_Choice, T2_Choice, T3_Choice, Current_DB)
VALUES (:username, :t1choice, :t2choice, :t3choice, :db)"
);
$stmt->bindParam(':username', $_SESSION['username']);
$stmt->bindParam(':t1choice', $_POST["term1sport"]);
$stmt->bindParam(':t2choice', $_POST["term2sport"]);
$stmt->bindParam(':t3choice', $_POST["term3sport"]);
$stmt->bindParam(':db', $db);
$stmt->execute();
To design this INSERT query, start by using SELECT to create the result set you want to insert.
SELECT :username AS Username,
:t1choice AS t1choice,
:t2choice AS t2choice,
:t3choice AS t3Choice,
DB
FROM Current_DB
Then use that result set as the data source for your insert.
INSERT INTO Student_Choices
(Username,T1_Choice,T2_Choice,T3_Choice,Current_DB)
SELECT :username AS Username,
:t1choice AS t1choice,
:t2choice AS t2choice,
:t3choice AS t3Choice,
DB
FROM Current_DB
Notice how the SELECT operation replaces the VALUES() clause.
(Careful, unless you put an appropriate WHERE clause on the SELECT, you may get lots of rows inserted, one for each row in Current_DB.)

Get results from WPDB

I have this scenario that I can't figure out:
Inside table wp_comment I need to list all user_id (not duplicate) with comment_type=complete.
I tried this:
$results = $GLOBALS['wpdb']->get_results( "SELECT * FROM wp_comments WHERE comment_type='sensei_course_status' AND comment_approved='complete'", ARRAY_A );
$corsisti = $results[user_id];
// I need to print only ids to put this array in
get_users( include=> '$corsisti' )
The database screenshot:
You can use the wpdb::get_col() method to retrieve an array with values from a single column:
$corsisti = $GLOBALS['wpdb']->get_col( "SELECT `user_id` FROM wp_comments WHERE comment_type='sensei_course_status' AND comment_approved='complete'");
Then simply use the result in get_users (you do not need the quotes):
$users = get_users( include=> $corsisti );

Bulk update mysql with where statement

How to update mysql data in bulk ?
How to define something like this :
UPDATE `table`
WHERE `column1` = somevalues
SET `column2` = othervalues
with somevalues like :
VALUES
('160009'),
('160010'),
('160011');
and othervalues :
VALUES
('val1'),
('val2'),
('val3');
maybe it's impossible with mysql ?
a php script ?
The easiest solution in your case is to use ON DUPLICATE KEY UPDATE construction. It works really fast, and does the job in easy way.
INSERT into `table` (id, fruit)
VALUES (1, 'apple'), (2, 'orange'), (3, 'peach')
ON DUPLICATE KEY UPDATE fruit = VALUES(fruit);
or to use CASE construction
UPDATE table
SET column2 = (CASE column1 WHEN 1 THEN 'val1'
WHEN 2 THEN 'val2'
WHEN 3 THEN 'val3'
END)
WHERE column1 IN(1, 2 ,3);
If the "bulk" data you have is dynamic and is coming from PHP (you did tag it, after all), then the query would look something like this:
INSERT INTO `foo` (id, bar)
VALUES
(1, 'pineapple'),
(2, 'asian pear'),
(5, 'peach')
ON DUPLICATE KEY UPDATE bar = VALUES(bar);
and the PHP to generate this from an existing array (assuming the array is of a format like:
$array = (
somevalues_key => othervalues_value
);
) would look something like this (by no means the best (doesn't address escaping or sanitizing the values, for instance), just an quick example):
$pairs = array();
foreach ($array as $key => $value) {
$pairs[] = "($key, '$value')";
}
$query = "INSERT INTO `foo` (id, bar) VALUES " . implode(', ', $pairs) . " ON DUPLICATE KEY UPDATE bar = VALUES(bar)";
You could try an UPDATE with JOIN as below:
UPDATE table
INNER JOIN (
SELECT 1 column1, 2 column2, 10 new_v1, 20 new_v2, 30 new_v3
UNION ALL SELECT 4 column1, 5 column2, 40 new_v1, 50 new_v2, 60 new_v3
) updates
ON table.column1 = updates.column1
AND table.column2 = updates.column2
SET
table.column1 = updates.new_v1,
table.column2 = updates.new_v2,
table.column3 = updates.new_v3;
As long as you can craft the inner SELECT statements from the updates subquery you would get the benefit of running all these updates in a single statement (which should give you some performance boost on InnoDB depending on your table size).
If you are using a drag & drop tableView or collectionView to sort datas in your app, like allowing users to arrange their photos by drag and drop functionality, send a comma seperated list of ordered ids to the backend after user edits finish.
In your backend, explode ids to the an array like
$new_ranks = array();
$supplied_orders = explode(",", $_POST["supplied_new_order"]); //52,11,6,54,2 etc
$start_order = 99999;
foreach ($supplied_orders as $supplied_row_id) {
//your all validations... make sure supplied_row_id belongs to that user or not etc..
$new_ranks[intval($supplied_row_id)] = $start_order--;
}
now, you can update all new ranks like #Farside recommendation 2.
if (count($new_ranks) > 0) {
$case_sqls = array();
foreach ($new_ranks as $id => $rank) {
$case_sqls[] = "WHEN ".intval($id)." THEN ".intval($rank)."";
}
$case_sql = implode(" ", $case_sqls);
$this->db->query("
UPDATE
service_user_medias
SET
rank = (CASE id ".$case_sql." END)
WHERE
id IN(".implode(",", array_keys($new_ranks)).");
");
}
If you have data in array format then try this
and your query is like "UPDATE table WHERE column1 = ? SET column2 = ?"
then set it like below
foreach($data as $key => $value) {
$query->bind_param('ss', $key, $value);
$query->execute();
}
hope it'll work.
Reference from this.

How to Get ID of the First Query and Use it to the 3rd Query?

I have a problem regarding SQL Query. I have 3 Insert queries in my code.
the first query is with auto-increment ID.
INSERT INTO master_tbl
The second Insert will get the ID from 1st query using LAST_INSERT_ID()function.
INSERT INTO process (id_ref, process_id, hot_cold, temp)
VALUES (LAST_INSERT_ID(), '4', '-', '12')
My problem is, I have third query which needed to use the ID generated in the 1st query as its id_ref also.
When I use the LAST_INSERT_ID(), the ID it gets was the ID of the second query.
Any suggestions on how can I still get the ID in the 1st query to use on 3rd?
You can declare the variable and store the first queries id in that variable and then use it wherever you want.
After first query as you mentioned you are using the separate queries you can try using select to set the `Last insert id` into the variable and then use that variable as below,
select #valuetoUse := LAST_INSERT_ID()
Or Other way is use select the to get the value in your code and then pass that value to insert as all other values. For getting value you can directly fire select
SELECT LAST_INSERT_ID()
then in second query
INSERT INTO process (id_ref, process_id, hot_cold, temp)
VALUES (valuetoUse , '4', '-', '12')
then again in the third query
INSERT INTO thirdtable (id_ref, process_id, hot_cold, temp)
VALUES (valuetoUse , '4', '-', '12')
For more info on how to use user defined variables see here.
Functionality is same as told by #Coder of Code But with PHP
Try This
Create Connection
$conn = new mysqli($servername, $username, $password, $dbname);
First Insert into Table 1
INSERT INTO master_tbl
Then do
$sql = "SELECT MAX(id) as id from master_tbl";
$result = $conn->query($sql);
$row = $result->fetch_array(MYSQLI_NUM);
$latest_id=$row[0];
$sql = "INSERT INTO process (id_ref, process_id, hot_cold, temp)
VALUES ($latest_id,'4','-','12')";
if ($conn->query($sql) === TRUE)
{
echo "New record created successfully";
}
$sql = "INSERT INTO table3 (id_ref , columns list)
VALUES ($latest_id,other fields)";
if ($conn->query($sql) === TRUE)
{
echo "New record created successfully";
}

Query to return tables from mysql database not listed in a column in a table in the database

I have a number of tables in my wordpress database(gooda814_bilby01). I want a function to compare the tables in the database with the values in a column in a table in the database so that the function will then create any table not on the list. I have a php solution that is inelegant:
$fdc_tables = $wpdb->get_results('SELECT distinct `fdc_form` FROM `fdc_tables`', ARRAY_A);
$wp_tables = $wpdb->get_results('show tables from gooda814_bilby01', ARRAY_A);
foreach( $fdc_tables as $fkey => $fvalue ) { $fdc[$fkey] = $fvalue['fdc_form']; }
foreach( $wp_tables as $wkey => $wvalue ) { $wpt[$wkey] = $wvalue['Tables_in_gooda814_bilby01']; }
$required tables = (array_values((array_diff($fdc, $wpt))));
but I thought there might be a neat mysql join like:
select distinct fdc_forms from
join show tables on Tables_in_gooda814_bilby01 = fdc_tables.fdc_forms
However, this of course returns an error #1064
Use a Sub-Query instead of a JOIN.
Try this SQL
SELECT fdc_form
FROM fdc_tables
WHERE fdc_form NOT IN (
SELECT T.TABLE_NAME
FROM information_schema.TABLES T
WHERE T.TABLE_SCHEMA='gooda814_bilby01'
);