I connected mysql with PDO like this:
$servername = 'localhost';
$servername = 'localhost';
$dbname = 'atlas';
$table = 'homepage_pv';
$username = 'root';
$password = 'mysql';
$conn = null;
try {
$conn = new PDO(
"mysql:host=$servername;dbname=$dbname",
$username,
$password,
array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
)
);
}
catch(PDOException $e) {
echo "connect to mysql failed : " . $e->getMessage();
$conn = null;
exit;
}
$result = $conn->query('SELECT * from homepage_pv')->fetchAll(PDO::FETCH_NAMED);
echo "result=" . json_encode($result);
the result is :
result=[{"homepage_pv.id":"1","homepage_pv.datetime":"2019-08-19 22:56:26"},{"homepage_pv.id":"2","homepage_pv.datetime":"2019-08-19 22:56:28"},{"homepage_pv.id":"3","homepage_pv.datetime":"2019-08-19 23:01:58"}]
The keys contain the table name "homepage_pv" , which is not expected;
But where I create PDO like this :
try {
$conn = new PDO(
"mysql:host=$servername;",
...
);
}
...
$result = $conn->query('SELECT * from atlas.homepage_pv')->fetchAll(PDO::FETCH_NAMED);
echo "result=" . json_encode($result);
the keys in the result do not contain tablename any more, like this:
result=[{"id":"1","datetime":"2019-08-19 22:56:26"},{"id":"2","datetime":"2019-08-19 22:56:28"},{"id":"3","datetime":"2019-08-19 23:01:58"},{"id":"4","datetime":"2019-08-19 23:08:48"}]
In case1 , I specified dbname when creating PDO and leaved out it when doing query;
In case2 , it's is on the contrary;
So what cause it? how can I specify dbname when creating PDO without the keys in result containing tablename?
Use PDO::FETCH_ASSOC in fetchAll(). If you use PDO::FETCH_NAMED it will return with alias name. If alias not present then with the table name. Attaching the doc for your further reference.
Related
I have an application that writes it's data to SQLite everyday. I now want to upload this data into my webhost to use. So I have a scheduled sFTP script to upload the .sqlite file to my webhost and then run another scheduled task to run the php code.
I know that I can use SQLite with PDO but all my other data on the host is in MySQL, so I want to keep everything in the MySQL format.
I have tried writing some php code that will read the sqlite file via PDO and then insert into the MySQL table again with PDO. The script will hopefully run on multiple tables to import so using foreach with Key/Values so I do not have to hardcode every single column in each table (about 30 columns per table)
However I have tried various things but just can not seem to find why the above code does not work problem so asking for help from much better minded users. Please view my code.
Thanks
<?php
ini_set('max_execution_time', 480); //480 seconds = 8 minutes
try {
// Connect to MySQL database
$host = '127.0.0.1';
$db = 'coredb';
$user = 'root';
$pass = 'password';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdomysql = new PDO($dsn, $user, $pass, $opt);
// Connect to SQLite database in file
$file_db = new PDO('sqlite:frp.sqlite');
$file_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = 'SELECT * from frp_teamdata';
$stmt = $file_db->prepare($sql);
$stmt->execute();
$sqliteresults = $stmt->fetch(PDO::FETCH_ASSOC);
foreach($sqliteresults as $results){
foreach($results as $key => $value){
$stmt = $pdomysql ->prepare("INSERT INTO frp_teamdata (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $key);
$stmt->bindParam(':value', $value);
$stmt->execute();
}
}
}
catch (PDOException $e) {
print 'Exception : ' . $e->getMessage();
}
?>
Give this a try:
<?php
ini_set('max_execution_time', 480); //480 seconds = 8 minutes
try {
// Connect to MySQL database
$host = '127.0.0.1';
$db = 'coredb';
$user = 'root';
$pass = 'password';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdomysql = new PDO($dsn, $user, $pass, $opt);
// Connect to SQLite database in file
$file_db = new PDO('sqlite:frp.sqlite');
$file_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = 'SELECT * from frp_teamdata';
$stmt = $file_db->prepare($sql);
$stmt->execute();
$sqliteresults = $stmt->fetch(PDO::FETCH_ASSOC);
//Prepare the statement only once!
$stmtmysql = $pdomysql ->prepare("INSERT INTO frp_teamdata (name, value) VALUES (:name, :value)");
//Bind the params only once -- I assume the keys and values are strings
$stmtmysql->bindParam(':name', $key, PDO::PARAM_STR);
$stmtmysql->bindParam(':value', $value, PDO::PARAM_STR);
foreach($sqliteresults as $results){
foreach($results as $key => $value){
$stmtmysql->execute();
}
}
}
catch (PDOException $e) {
print 'Exception : ' . $e->getMessage();
}
?>
Note: I have not tried the code, so let me know if you have any issues.
I try to select data from a database, but I'm unable to get it when I have two parameters after the WHERE.
Code that works:
$conn = null;
$host = 'localhost';
$db = 'database';
$user = 'root';
$pwd = 'root';
$auth = 'EP';
$nr = 2007;
try {
$conn = new \PDO('mysql:host='.$host.';dbname='.$db, $user, $pwd);
$stmt = $conn->prepare('SELECT family FROM table WHERE nr = :nr');
$stmt->execute(array('nr' => $nr));
while($row = $stmt->fetch(PDO :: FETCH_ASSOC)) {
echo '<pre>';
print_r($row);
echo '</pre>';
}
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
but when I use following select it doesn't work:
SELECT family FROM table WHERE auth = :auth AND nr = :nr
I think it's a problem in the line
$stmt->execute(array('nr' => $nr));
When I do the following I have no result on the screen:
$stmt->execute(array('nr' => $nr, 'auth' => $auth));
Has anybody an idea what I'm doing wrong?
CHANGE THIS
stmt->execute(array('nr' => $nr, 'auth' => $auth));
TO
$stmt->execute(array(':nr' => $nr, ':auth' => $auth));
: is a small typo error but PDO is Serious :( and the parameters will be empty.
This Piece Of Code Is Not Working :
$un_name=$_POST[name];
$un_idno=$_POST[idno];
$un_hostel=$_POST[hostel];
$un_mode=$_POST[mode];
$un_date=$_POST[date];
$un_time=$_POST[time];
$un_tfno=$_POST[tfno];
$un_contact=$_POST[contact];
$sa_name=mysql_real_escape_string ($un_name);
$sa_idno=mysql_real_escape_string ($un_idno);
$sa_hostel=mysql_real_escape_string ($un_hostel);
$sa_mode=mysql_real_escape_string ($un_mode);
$sa_date=mysql_real_escape_string ($un_date);
$sa_time=mysql_real_escape_string ($un_time);
$sa_tfno=mysql_real_escape_string ($un_tfno);
$sa_contact=mysql_real_escape_string ($un_contact);
$sql="INSERT INTO cabs (NAME,IDNO,HOSTEL,MODE,DATE,TIME,TFNO,CONTACT)
VALUES
('$sa_name','$sa_idno','$sa_hostel','$sa_mode','$sa_date','$sa_time','$sa_tfno','$sa_contact')";
While the same code when normally inserted works .....
$sql="INSERT INTO cabs (NAME,IDNO,HOSTEL,MODE,DATE,TIME,TFNO,CONTACT)
VALUES
('$_POST[name]','$_POST[idno]','$_POST[hostel]','$_POST[mode]','$_POST[date]','$_POST[time]','$_POST[tfno]','$_POST[contact]')";
I was just trying my first steps to prevent sql injection..but there seems to be some problem....
Note : My host doesnt seem to support mysqli so that's why i had to use msql which is deprecated.
Why not use PDO instead?
$host = "localhost";
$user = "root";
$pass = "";
$dbname = "dbname";
$link = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$foo_var = 3;
$query_result = $link->prepare("SELECT * FROM modules
WHERE id = :foo
LIMIT 1");
$query_result->bindValue(":foo", $foo_var);
$query_result->setFetchMode(PDO::FETCH_ASSOC);
$query_result->execute();
while($row = $query_result->fetch()) {
return $row;
}
Try this
$con=mysql_connect("localhost","username","password","dbname");//connection string
$sa_name=mysql_real_escape_string($con,$un_name);
.
.
.
I have this simple code to make search results depending on relevance:
$stmt = $db->query('SELECT * FROM `apps` WHERE MATCH(appName, appSeller) AGAINST("angry")');
$appCount = $stmt->rowCount();
echo $appCount;
And it's not showing any results!
Thanks in advance for your help,
Marcell
Stackoverflow's usability is below zero.
Because there is no way to make a half-screen banner shown to everyone posting a question under PDO tag:
Enable ERRMODE_EXCEPTION when connecting to PDO before asking a question.
Because it is pointless to ask without an error message, yet error message most likely will render a question unnecessary.
$dsn = 'mysql:host=localhost;dbname=test;charset=utf8';
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
);
$pdo = new PDO($dsn,'root','', $opt);
Try
'SELECT * FROM `apps` WHERE MATCH(appName, appSeller) AGAINST("angry")'
in phpmyadmin and see if it really returns anything.
try this
<?php
// Connection data (server_address, database, name, poassword)
$hostdb = 'localhost';
$namedb = 'tests';
$userdb = 'username';
$passdb = 'password';
try {
// Connect and create the PDO object
$db = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
$db->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8
// Define and perform the SQL SELECT query
$sql = "SELECT * FROM `apps` WHERE MATCH(appName, appSeller) AGAINST("angry")";
$stmt = $db->query($sql);
// If the SQL query is succesfully performed ($stmt not false)
if($stmt !== false) {
$cols = $stmt->columnCount(); // Number of returned columns
echo 'Number of returned columns: '. $cols. '<br />';
// Parse the result set
foreach($stmt as $row) {
echo $row['id']. ' - '. $row['name']. ' - '. $row['category']. ' - '. $row['link']. '<br />';
}
}
$db = null; // Disconnect
}
print_r($sth->errorInfo());
}
?>
enclose your code in try and catch blocks, then you should get a clue to where your going wrong in your SQL syntax:
try {
// your code
} catch ( PDOException £e ) {
echo $e->getMessage();
exit();
}
I find the error: could not find driver in the next script. I'm breaking my head over it now for some time now maybe you see the my fault.
This is my code:
class ConnectStation {
private $host = "localhost";
private $DatabaseType = "mysql";
private $database = array (
1 => "Database_one",
2 => "Database_two",
3 => "Database_true"
);
private $user1 = "MyUsername1";
private $pass1 = "MyPassword1";
private $user2 = "MyUsername2";
private $pass2 = "MyPassword2";
public function ConnectDB($user, $database){
if ($database==""){$database=1;}
try{
switch ($user){
case "ReadOnly":
$connection = new PDO("'".$this->DatabaseType.":host=".$this->host.";dbname=".$this->database[$database]."', '".$this->user1."', '".$this->pass1."'");
$connection->exec('SET CHARACTER SET utf8');
return $connection;
break;
case "Admin":
$connection = new PDO("'".$this->DatabaseType.":host=".$this->host.";dbname=".$this->database[$database]."', '".$this->user2."', '".$this->pass2."'");
$connection->exec('SET CHARACTER SET utf8');
return $connection;
break;
}
}
catch(PDOException $e){
echo $e->getMessage();
}
}
}
Oke so far the connection than the scrip i use for a query to send to the database. the code is like this:
$userCard = new ConnectStation;
$query = "SELECT username FROM users";
foreach ($this->ConnectDB('ReadOnly', 1)->query($query) as $row){
echo $row['username']."<br>";
}
Any help ore advise is welcome?
Your call to the PDO constructor is totally screwed up with unnecessary quotes and weird argument order. Just do:
$dsn = sprintf('%s:host=%s;dbname=%s', $this->DatabaseType, $this->host, $this->database[$database]);
$connection = new PDO($dsn, $this->user1, $this->pass1);