arrays and mysqli insert - arrays

once again thanks for your help in advance im looking to pre fill a mysqli insert statement with data filled from an array and cannot seem to get it to work it just doesnt insert and im kinda stuck and looking for ideas
this is what im chasing as a end result as for code but cannot seem to get it to work
$table_colums= array("db_colum1","db_colum2");
$forms_data = array("form_data1","form_data2");
$sql = INSERT into some_table ($table_colums) VALUES ($forms_data)
obviously if i do it the old fashion way it will work but i need to have it get its values from the arrays because there dynamic and filled from a database
$sql = INSERT into some_table (db_colum1,db_colum2) VALUES ('form_data1','form_data2')

I can suggest you a library I wrote, SafeMysql, which is doing exactly what you want - adding arrays to mysql (among many other wonderful things).
Though you need another kind of array, but I suppose it would be even simpler:
include 'safemysql.class.php';
$db = new safemysql();
$data = array(
"db_colum1" => "form_data1",
"db_colum2" => "form_data2",
);
$db->query("INSERT INTO some_table SET ?u", $data);
Nothing could be easier.

Related

How can I make bulkCopy map the same columns?

Suppose I have a SQL Table that has these columns:
[server_name],[SESSION_ID],[SESSION_SPID]
I am trying to copy values stored in a data table ($dmvResult) to the SQL Table above ($Table)
$dmvResult = DMV_Query 'SELECT [SESSION_ID]
,[SESSION_SPID]
FROM $SYSTEM.DISCOVER_SESSIONS';
$ConnectionString ='Data Source=$server; Database=$database; Trusted_Connection=True;'
$bulkCopy = new-object Data.SqlClient.SqlBulkCopy($ConnectionString)
$bulkCopy.DestinationTableName=$Table
$bulkCopy.WriteToServer($dmvResult)
While the copying is being done successfully, there is an issue: it's copying by position, not by column name match. In other words, the copied columns are not being mapped and copied to the same columns.
[SESSION_ID] is being copied to [server_name] and
[SESSION_SPID] is being copied to [SESSION_ID]
How can I tell bulkCopy to match columns and copy?
The result copy should be [server_name] being empty because it wasn't selected from DMV query.
I found a neat solution in this thread:
https://stackoverflow.com/a/20045505/8397835
but I dont know how to translate it to my powershell code:
var meta = definition.Context.Mapping.GetMetaType(typeof(T));
foreach (var col in meta.DataMembers)
{
copy.ColumnMappings.Add(col.Member.Name, col.MappedName);
}
EDIT: foreach column.ColumnName output
EDIT2:
i tried this:
$dmvResult.Columns |%{$_.Name}
and it doesnt output anything.
before you say $dmvResult data table must be empty then, explain how is it possible that this actually works and copies in data?
$bulkCopy.ColumnMappings.Add('SESSION_ID', 'SESSION_ID')
$bulkCopy.ColumnMappings.Add('SESSION_SPID', 'SESSION_SPID')
$bulkCopy.WriteToServer($dmvResult)
and for some reason, its outputting this to the console as well:
so the data table $dmvResult is clearly populated.
i was hoping instead of defining mapping for every single column like this:
$bulkCopy.ColumnMappings.Add('SESSION_SPID', 'SESSION_SPID')
instead there would be anutomatic option like this:
foreach ($column in $dmvResult.Columns) { $bulkCopy.ColumnMappings.Add($column.ColumnName, $column.ColumnName)}
but that throws exception:
Exception calling "WriteToServer" with "1" argument(s): "The given
ColumnMapping does not match up with any column in the source or
destination."
A very weird solution but I just had to add a comma here before $dataset:
,$dataSet.Tables[0]
in the DMV_Query function
and then i used this foreach loop
foreach ($column in $dmvResult.Columns) { $bulkCopy.ColumnMappings.Add($column.ColumnName, $column.ColumnName) > $null }
and it worked!
it now maps the columns automatically!!

Abusing Query or QueryAsync when used with CUD operations

I'm trying to implement a repository with Dapper as ORM, I want inserted or updated entities to be returned back. This is what I came up with, it works just fine but I'm wondering if this is abusing the default Query and QueryAsync methods?
public async Task<Models.TestTable> Insert(Models.TestTable inputObject)
{
IEnumerable<Models.TestTable> output;
output = await _connection.QueryAsync<Models.TestTable>(
sql: string.Format("INSERT INTO TestTable (FirstName, LastName) OUTPUT INSERTED.* VALUES (#FirstName, #LastName)"),
param: inputObject);
return output.SingleOrDefault();
}
The only actual problem I can see there is the unnecessary string.Format.
Personally I might have been tempted to just update the Id (or whatever) in the existing object, but your OUTPUT INSERTED.* works fine too. I might be very tempted to move the local declaration inline via var output = ..., and of course once I've done that it makes it tempting to make the entire thing inline:
public async Task<Models.TestTable> Insert(Models.TestTable inputObject)
=> (await _connection.QueryAsync<Models.TestTable>(
"INSERT INTO TestTable (FirstName, LastName) OUTPUT INSERTED.* VALUES (#FirstName, #LastName)",
inputObject)).SingleOrDefault();
but most of that is trivia and subjective. Heck, even the string.Format is just unnecessary rather than problematic.
One other thing to check: did we (and I can't remember!) add a QuerySingleOrDefaultAsync method? I know we added QuerySingleOrDefault - I just can't remember about the *Async twin.

using WPDB to display external database-data inside a WP-shortcode

I'm trying to figure out a way to use WPDB to load a whole row or single cells/fields from another table (not the Wordpress-DB) and displaying them in a shortcode. I have a bunch of weatherdata-values, I need the latest row (each column is another data-type (temp, wind, humidity, etc) of the database for a start.
Sadly, the plugin that would do everything that I need, SQL Shortcode, doesn't work anymore. I found this now:
https://de.wordpress.org/plugins/shortcode-variables/
Though I still need to use some PHP/PDO-foo to get the data from the database.
By heavy copy&pasting I came up with this:
<?php
$hostname='localhost';
$username='root';
$password='';
$dbname='sensordata';
$result = $db->prepare(SELECT * FROM `daten` WHERE id=(SELECT MAX(id) FROM `daten`););
$result->execute();
while ($row = $result->fetch(PDO::FETCH_ASSOC))
{
$data = $row['*'];
}
echo $data;
?>
But obviously it's not working. What I need to get it done with WPDB?
kind regards :)
Just in case anyone else needs this in the future. I used this now:
//connect to the database
<?php
$dbh = new PDO('mysql:host=localhost;dbname=databasename', 'dbuser',
'dbpasswort');
//query the database "databasename", selecting "columnname" from table "tablename", checking that said column has no NULL entry, sort it by column "id" (autoincrementing numeric ID), newest first and just fetch the last one
$sth = $dbh->query("SELECT `columnname` FROM `tablename` WHERE `columnname` IS NOT NULL order by id desc limit 1")->fetchColumn(0);
//print the value/number
print_r($sth);
?>
By using "SELECT colum1, colum2,... FROM" You should get all the columns, could be that fetchColumn needs to be replaced with something different though.

To insert a user info to another wp site using $wpdb

I want to insert a user from another wordpress site. I used the bellow code for this. But i got a error.
Call to a member function query() on a non-object
My code for insert the user table
global $mydb;
$mydb = new wpdb(My DB information here...);
$rows = $mydb->get_results("select user_nicename from wp_users");
$sql = "INSERT INTO wp_users (user_login,user_pass,user_pass,user_nicename,user_email,user_url,display_name)
VALUES ('$fields[username]','$fields[password]','$fields[user_nicename]','$fields[user_email]','$fields[wpmem_reg_url]','$fields[wpmem_reg_url]','$fields[display_name]')";
$wpdb->query($sql);
Why cant i insert the data and get the error. Please help me.
You are declaring $mydb as global connection object and executing query with $wpdb
change it to
$sql = "INSERT INTO wp_users (user_login,user_pass,user_nicename,user_email,user_url,display_name)
VALUES ('$fields[username]','$fields[password]','$fields[user_nicename]','$fields[user_email]','$fields[wpmem_reg_url]','$fields[display_name]')";
$mydb->query($sql);

How to delete multiple rows?

So I can delete one row using:
$this->db->delete($tableName,array("id"=>4));
...but I can't figure out how to delete multiple rows. I tried:
$this->db->delete($tableName,array("id"=>4,"id"=5));
as well as:
$this->db->delete($tableName,array(array("id"=>4),array("id"=5)));
...but they both don't work. I feel like this should be pretty easy. Any answers?
Have you tried this ?
$names = array(4,5);
$this->db->where_in('id', $names);
$this->db->delete('mytable');
not need of associative array.
$ids[] = 1;
$ids[] = 2;
$this->db->where_in( id, $ids );
$this->db->delete('Table_Name');
write custom query for it
$this->db->query("DELETE FROM `TABLE_NAME` WHERE `id` IN(1,2,3,4,5)");
it is not work
$names = array(4,5);
$this->db->where_in('id', $names);
$this->db->delete('mytable');
DELETE FROM table_name WHERE id IN ('4,5')
notice one thing not single string/digit ('4,5') we should be dived each and every id with single quotation like this ('4','5')
The best and good way
//$ids = 1,2,3.....
$ids_exp = explode(',',$ids);
$this->db->where_in('id',$ids_exp);//
$this->db->delete('table_name')
return $this->db->affected_rows();
the above query will be work enjoy..........
To delete a single use row:
$this->db->delete('TABLE_NAME', array('id' => 5));
Have you tried doing this? I'm pretty sure it should work.
$this->db->delete('TABLE_NAME', array(array('id' => 5), array('id' => 3), ...));
This is an old question, but I'll answer it since I had to research the same question 8 years later.
I checked the source code of $wpdb->delete(), and it will basically only delete 1 row. It works by matching 1 col to 1 val, and then joining with AND. So if you do array("id"=>4,"id"=>5), it will read it as row with (id==4 AND id==5). No rows will match that condition.
So to delete multiple rows, the only way (as far as i've seen) is to use a custom query:
$wpdb->query("DELETE FROM `TABLE_NAME` WHERE `id` IN(1,2,3,4,5)");

Resources