this code keeps saying that the "Record has been Added", yet it's no where to be seen on phpmyadmin...Any thoughts?
phpmyadmin: localhost>summative>Data
$con = mysql_connect("localhost", "root", "") or die(mysql_error());
if(!$con)(die("could not connect " . mysql_error()));
mysql_select_db("summative") or die(mysql_error());
mysql_query("INSERT INTO Data(First Assister) VALUES('$_GET[assist1]')");
if("INSERT INTO Data(First Assister) VALUES('$_GET[assist1]'");
{
echo "Record Added";
}
?>
1.) mysql is now deprecated use mysqli... from http://us2.php.net/manual/en/intro.mysql.php
This extension is deprecated as of PHP 5.5.0, and is not recommended
for writing new code as it will be removed in the future. Instead,
either the mysqli or PDO_MySQL extension should be used. See also the
MySQL API Overview for further help while choosing a MySQL API.
2.) Are you seriously setting $_GET data into your database?
3.) Are you seriously setting $_GET data into your database without escaping it? ALWAYS escape user provided data when putting it into your databse unless you enjoy getting hacked by Chinese government sponsored hackers (or Russian, or Netherlands, or Brazil... or lesser common countries, but those are the most common as far as I've been hack attempted)
See the docs for mysqli_real_escape_string: http://us2.php.net/manual/en/mysqli.real-escape-string.php
2.) Where are you getting that INSERT format from? In MySQL the format is:
INSERT INTO table_name VALUES (value1, value2, value3,...)
From: http://www.w3schools.com/php/php_mysql_insert.asp
Personally, I prefer the other INSERT format:
INSERT [LOW_PRIORITY |
DELAYED | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name
[PARTITION (partition_name,...)]
SET col_name={expr | DEFAULT}, ...
[ ON DUPLICATE KEY UPDATE
col_name=expr
[, col_name=expr] ... ]
4.) What is your table name? I see a DB name, and I THINK a column name, and then a value...
So I'd change your INSERT statement to this:
$value = mysqli_real_escape_string($_GET['param']);
$sql = 'INSERT INTO `table_name` SET `column`="'.$value.'";';
$result = mysqli_query($sql);
Related
I have a access database with a lot of information, I am not that good with access database and I am still a newbie when it comes to powershell. I have been trying to automate the insertion of data from the csv files into the access database as they are done weekly.
after researching I found a powershell code that allows insertion of CSV into databases, However I have not been able to make it work with my current acccess database and CSV file.
write-host "current path is $PSSCriptRoot"
$datafile="$PSScriptRoot\Input.csv" #trying to import this file into the databse
$dbfile="$PSScriptRoot\database.accdb" #this is the test access database
$connectionString="Provider=Microsoft.Ace.OLEDB.12.0; Data Source=$dbfile" #general info I found researc
$conn = New-Object System.Data.OleDb.OleDbConnection($connectionString)
$conn.Open()
$cmd = $Conn.CreateCommand()
Import-Csv $dataFile |
ForEach{
$cmd.CommandText = "INSERT into [MyTable1]([Name],[First Data Set],[Description],[Enabled],[Last Date,Creation Date],[Modification Date],[Day of The year],[ID type],[ID Date],[Street Address],[date],[type])
VALUES('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}', '{8}', '{9}', '{10}', '{11}', '{12}')" -f #(
$_.Name,
$_.'First Data Set',
$_.Description,
$_.Enabled,
if ($_.'Last Logon Date') { ([datetime]$_.'Last Logon Date').ToString('M/d/yyyy H:mm') } else {[System.DBNull]::Value }
if ($_.'Creation Date') { ([datetime]$_.'Creation Date').ToString('M/d/yyyy H:mm') } else { [System.DBNull]::Value}
if ($_.'Modification Date') { ([datetime]$_.'Modification Date').ToString('M/d/yyyy H:mm') } else { [System.DBNull]::Value}
$_.'Day of The year',
$_.'ID type',
if ($_.'ID Date') { ([datetime]$_.'Modification Date').ToString('M/d/yyyy H:mm') } else { [System.DBNull]::Value },
$_.'Street Address',
if ($_.date) { ([datetime]$_.date).ToString('M/d/yyyy H:mm') } else { [System.DBNull]::Value}
$_.Type
)
$cmd.ExecuteNonQuery()
}
$conn.Close()
The access database has the corresponding table with the corresponding rows from the csv, so what should happen is that the data from the csv would be inserted into the table.
the input and database files are recognized with the $PSScriptRoot command as they point to the path of the script which is in the same folder.
The error I am getting is the following:
"Exception calling "ExecuteNonQuery" with "0" argument(s): "Syntax error in INSERT INTO statement."
At C:\1 - database paths\Database1\database.accdb "
yes that is the current testing path, it has spaces and a couple of special characters, this cannot be changed and as other scripts work fine, this should also work fine.
Since I have little knowledge about accdb I am having a hard time finding why is the error, for what it says it seems my syntax for the insert command is not correct, yet I cant find an example of another type of syntax used for that command. I used the -f as rows contain spaces and there is an issue with quotes on powershell. I can not change the path name nor the row names at all.
edit: now I have another problem, where the columns with date time cannot accept a null value, I tried going around it by asetting a DBNull value but this does not work. I need to see those blank values on my database for statistic purposes , is there a way to import those empty values ?
i had to format each value into adata type as powershell passes them a strings, .
I use DB::setDatabaseName(<database name>) to reset the databasename, then I use DB::table(<table name>)->get() to retrieve data. However laravel does not change to new database.
This is my error message:
Illuminate/Database/QueryException with message 'SQLSTATE[42P01]:
Undefined table: 7 ERROR: relation "t" does not exist LINE 1: select
* from "t" ^ (SQL: select * from "t")'
The table t is in another database. I think when I use DB::setDatabaseName(<database name>) it would work.
Thank you for your help!
I don't know your database of detail information, but this help you to check database have changed.
// current database is 'db_1'
echo DB::getDatabaseName(); // return db_1
// Set database to 'db_2'
DB::setDatabaseName('db_2');
// If success, should return 'db_2' now.
echo DB::getDatabaseName();
// Check database tables.
DB::select('show tables');
I was facing a similar issue.
But changing the database solely might not always work.
You could use config->set() like so
config()->set('database.connections.mysql', $database_name);
But in my case I had to reconnect the database to change it dynamically.
So maybe this one works for the OP.
\DB::disconnect();
config()->set('database.pgsql.database', $database_name); // psgl = Postgress
\DB::reconnect();
You'll find more info here Laravel 6 config()->get('database.connections.mysql') not matching DB:connection()
Hope it helps
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.
Im learning DB2 and I had a problem while testing some options in my db.
I have 2 tables like this:
Country
=========
IdCountry -- PK
Name
State
=========
IdState -- PK
IdCountry -- FK to Country.IdCountry
Name
Code
And I am using queries like:
SELECT IdState, Name
FROM Tables.State
WHERE IdCountry = ?
Where ? is any working IdCountry, and everything worked fine.
Then I used set integrity in my db2 control center using the default info in the options and the process was successful but now my query isn't giving me any results.
I tried using :
SELECT *
FROM Tables.State
Where IdCountry = ?
and it gives me back results.
While making tests to the table I try adding new States and they appear in the query using column names instead of *, but old records still missing.
I have no clue about what's happening, does anyone have an idea?.
Thanks in advance, and sorry for my poor English.
I'm assuming here that you're on Linux/Unix/Windows DB2, since z/OS doesn't have a SET INTEGRITY command, and I couldn't find anything about it with a quick search on the iSeries Info Center.
It's possible that your table is still in "set integrity pending" state (previously known as CHECK PENDING). You could test this theory by checking SYSCAT.TABLES using this query:
SELECT TRIM(TABSCHEMA) || '.' || TRIM(TABNAME) AS tbl,
CASE STATUS
WHEN 'C' THEN 'Integrity Check Pending'
WHEN 'N' THEN 'Normal'
WHEN 'X' THEN 'Inoperative'
END As TblStatus
FROM SYSCAT.TABLES
WHERE TABSCHEMA NOT LIKE 'SYS%'
If your table shows up, you will need to use the SET INTEGRITY command to bring your table into checked status:
SET INTEGRITY FOR Tables.State IMMEDIATE CHECKED
I am facing this problem perl DBD::ODBC rollback ineffective with AutoCommit enabled at and while looking at the problem , I found that a very basic thing is failing with Perl::DBI using DBD::ODBC on sql server. But i am not sure if this wont happen with any other driver.
The problem is that when I create a #temp table using $dbh->do and when i try to access the same #temp table using another $dbh->do , i am getting the below error. Also this does not happen all the time , but only intermittently.
Invalid object name '#temp'
$dbh->do("SELECT ... INTO #temp FROM ...");
$dbh->do("INSERT INTO ... SELECT ... FROM #temp");
The second do fails with 'Invalid object name '#temp''
Kindly help me with the problem.
Not that it answers your question but it might help. The following works for me.
#
# To access temporary tables in MS SQL Server they need to be created via
# SQLExecDirect
#
use strict;
use warnings;
use DBI;
my $h = DBI->connect();
eval {
$h->do(q{drop table martin});
$h->do(q{drop table martin2});
};
$h->do(q{create table martin (a int)});
$h->do(q{create table martin2 (a int)});
$h->do('insert into martin values(1)');
my $s;
# this long winded way works:
#$s = $h->prepare('select * into #tmp from martin',
# { odbc_exec_direct => 1}
#);
#$s->execute;
# and this works too:
$h->do('select * into #tmp from martin');
# but a prepare without odbc_exec_direct would not work
print "NUM_OF_FIELDS: " . DBI::neat($s->{NUM_OF_FIELDS}), "\n";
$s = $h->selectall_arrayref(q{select * from #tmp});
use Data::Dumper;
print Dumper($s), "\n";
$h->do(q/insert into martin2 select * from #tmp/);
$s = $h->selectall_arrayref(q{select * from martin2});
print Dumper($s), "\n";
I was having this problem as well. I tried all of the above but it didnt matter. I stumbled upon this http://bytes.com/topic/sql-server/answers/80443-creating-temporary-table-select-into which solved my problem.
What's happening is that ADO is opening a second connection behind
your back. This has really not anything to do with how you created the
table.
The reason that ADO opens an extra connection, is because there are
rows waiting to be fetched on the first connection, so ADO cannot
submit a query on that connection.
I assume that Perl DBI is doing the same, so based on this assumption, here's what I did and it worked perfectly fine:
my $sth = $dbh->prepare('Select name into #temp from NameTable');
$sth->execute();
$sth->fetchall_arrayref();
$sth = $dbh->prepare('Select a.name, b.age from #temp a, AgeTable b where a.name = name');
$sth->execute();
my ($name,$age)
$sth->bind_columns(\$name,\$age);
while ( $sth->fetch())
{
# processing
}