convert from mysql php script to pdo - php

I am actually new to PDO
Here I am trying to fetch data from mysql and show in xml.
I have done it using mysql, but I could not be able to done it using PDO.
Here is my PHP code
<?php
error_reporting(E_ALL);
$host = "localhost";
$user = "root";
$pass = "root";
$database = "my_db";
// replace by a real *.xsl file, e.g.
// $xslt_file = "exam.xsl";
$xslt_file = FALSE;
// If true, will output XML without XSLT
$raw = TRUE;
$SQL_query = "SELECT * FROM `battery` order by waste asc";
$DB_link = mysql_connect($host, $user, $pass) or die("Could not connect to host.");
mysql_select_db($database, $DB_link) or die ("Could not find or access the database.");
$result = mysql_query ($SQL_query, $DB_link) or die ("Data not found. Your SQL query didn't work... ");
$left = "<";
$right = ">";
if ($xslt_file or $raw) {
// we produce XML
header("Content-type: text/xml");
$XML = "<?xml version=\"1.0\"?>\n";
if (!$raw) $XML .= "<?xml-stylesheet href=\"$xslt_file\" type=\"text/xsl\" ?>";
}
else {
// we produce HTML. All XML tags are replaced by printable entities
$XML = "Don't forget to create an XSLT file .... <p>";
$XML .= "<pre>\n";
$left = "<";
$right = ">";
}
// root node
$XML .= $left . "result" . $right . "\n";
// rows
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$XML .= "\t" . $left. "row" . $right . "\n"; // creates either "<row>" or "<row>"
$i = 0;
// cells
foreach ($row as $cell) {
// Escaping illegal characters
$cell = str_replace("&", "&", $cell);
$cell = str_replace("<", "<", $cell);
$cell = str_replace(">", ">", $cell);
$cell = str_replace("\"", """, $cell);
$col_name = mysql_field_name($result,$i);
// creates the "<tag>contents</tag>" representing the column, either as XML or for display in HTML
$XML .= "\t\t" . $left . $col_name . $right . $cell . $left . "/" . $col_name . $right ."\n";
$i++;
}
$XML .= "\t" . $left. "/row" . $right . "\n";
}
$XML .= $left . "/result" . $right . "\n";
echo $XML;
if (!$xslt_file && !$raw) echo "</pre>";
?>
I am trying a lot, but i could not be able to done it using PDO
Please i need some help.
Any Help will be appreciated.
My PDO code that i tried is
<?php
$dbtype = "mysql";
$dbhost = "localhost";
$dbname = "my_db";
$dbuser = "root";
$dbpass = "root";
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$xslt_file = FALSE;
$raw = TRUE;
$SQL_query = "SELECT * FROM `battery` order by waste asc";
$result = $conn->query($SQL_query);
$left = "<";
$right = ">";
if ($xslt_file or $raw) {
header("Content-type: text/xml");
$XML = "<?xml version=\"1.0\"?>\n";
if (!$raw) $XML .= "<?xml-stylesheet href=\"$xslt_file\" type=\"text/xsl\" ?>";
}
else {
$XML = "Don't forget to create an XSLT file .... <p>";
$XML .= "<pre>\n";
$left = "<";
$right = ">";
}
$XML .= $left . "result" . $right . "\n";
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
$XML .= "\t" . $left. "row" . $right . "\n"; // creates either "<row>" or "<row>"
$i = 0;
// cells
foreach ($row as $cell) {
// Escaping illegal characters
$cell = str_replace("&", "&", $cell);
$cell = str_replace("<", "<", $cell);
$cell = str_replace(">", ">", $cell);
$cell = str_replace("\"", """, $cell);
$col_name = $result->fetchAll(PDO::FETCH_COLUMN);
// creates the "<tag>contents</tag>" representing the column, either as XML or for display in HTML
$XML .= "\t\t" . $left . $col_name . $right . $cell . $left . "/" . $col_name . $right ."\n";
$i++;
}
$XML .= "\t" . $left. "/row" . $right . "\n";
}
$XML .= $left . "/result" . $right . "\n";
echo $XML;
if (!$xslt_file && !$raw) echo "</pre>";
?>
But it shows nothing

The correct way to fetch column names is
$q = $dbh->prepare("DESCRIBE tablename");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);
however as you are fetching an assoc you could just change your foreach loop to this:
foreach ($row as $col_name => $cell) {
There may be other issues, have you tried using print_r on the result of each PDO function call to check at what point it is failing?

you connect to the database like this :
$dbhost = "localhost";
$dbname = "testcreate";
$dbuser = "root";
$dbpass = "mysql";
try {
$db = new PDO('mysql:host='.$dbhost.';dbname='.$dbname.';charset=utf-8', ''.$dbuser.'', ''.$dbpass.'');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Error : <br>' . $e->getMessage();
}
PS: You dont need the try and the catch, but we used to get the error and handle it in a nice way as we want to
and next we query like this :
$db->query(SELECT * FROM node WHERE node_name='$nodename'");
and we fetch it like this :
$query = $db->query(SELECT * FROM node WHERE node_name='$nodename'");
$row = $query->fetch(PDO::FETCH_OBJ);
and now you use $row->name for example
here is more about PDO::FETCH
PDO::FETCH_ASSOC: returns an array indexed by column name as returned in your result set
PDO::FETCH_BOTH (default): returns an array indexed by both column name and 0-indexed column number as returned in your result set
PDO::FETCH_BOUND: returns TRUE and assigns the values of the columns in your result set to the PHP variables to which they were
bound with the PDOStatement::bindColumn() method
PDO::FETCH_CLASS: returns a new instance of the requested class, mapping the columns of the result set to named properties in the
class. If fetch_style includes PDO::FETCH_CLASSTYPE (e.g.
PDO::FETCH_CLASS | PDO::FETCH_CLASSTYPE) then the name of the class
is determined from a value of the first column.
PDO::FETCH_INTO: updates an existing instance of the requested class, mapping the columns of the result set to named properties in
the class
PDO::FETCH_LAZY: combines PDO::FETCH_BOTH and PDO::FETCH_OBJ, creating the object variable names as they are accessed
PDO::FETCH_NUM: returns an array indexed by column number as returned in your result set, starting at column 0
PDO::FETCH_OBJ: returns an anonymous object with property names that correspond to the column names returned in your result set

Related

Json data getting read but not inserting into mysql using php

Im trying to insert json data using php into mysql,
I get success msg, but no records are inserted.
My json data is :
jsondata.json:
{"users": { "bert":6.44, "earnie":0.25, "bigbird":34.45 }}
My php code:
<?php
//First: read data
$fo=fopen("data.json","r");
$fr=fread($fo,filesize("data.json"));
$array=json_decode($fr,true);
//Second: create $values
$rows = array();
foreach ($array['users'] as $key => $value)
$rows[] = "('" . $key . "', '" . $value . "')";
$values = implode(",", $rows);
//To display all values from JSON file
echo '<pre>';print_r($array);
//Save to DB
$hostname = 'localhost';
$username = 'root';
$password = '';
try
{
$dbh = new PDO("mysql:host=$hostname;dbname=nodejs", $username, $password);
echo 'Connected to database<br />';
//$count = $dbh->exec("INSERT INTO USERSAMOUNTS(USERNAME, AMOUNT) VALUES " . $values) or die(print_r($dbh->errorInfo(), true));
$count = $dbh->exec("INSERT INTO json(firstName) VALUES " . $values) or die(print_r($dbh->errorInfo(), true));
echo $count;// echo the number of affected rows
$dbh = null;// close the database connection
echo 'Success<br />';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
I believe the problem could be the order in which the actions are performed.
<?php
//First: read data
$fo = fopen("jsondata.json", "r");
$fr = fread($fo, filesize("jsondata.json"));
$array = json_decode($fr, true);
//Second: create $values
$rows = array();
foreach ($array['users'] as $key => $value)
$rows[] = "('" . $key . "', '" . $value . "')";
$values = implode(",", $rows);
//Third: display
echo '<pre>';
print_r($array);
//Fourth: save to db
$hostname = 'localhost';
$username = 'root';
$password = '';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=nodejs", $username, $password);
echo 'Connected to database<br />'; // echo a message saying we have connected
$count = $dbh->exec("INSERT INTO USERAMOUNTS(USERNAME, AMOUNT) VALUES " . $values);
echo $count; // echo the number of affected rows
$dbh = null; // close the database connection
echo 'Success<br />';
} catch (PDOException $e) {
echo $e->getMessage();
}
?>
Enables or disables emulation of prepared statements. Some drivers do not support native prepared statements or have limited support for them for more info please check - http://php.net/manual/en/pdo.setattribute.php
$dbh = new PDO("mysql:host=$hostname;dbname=nodejs", $username, $password);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$count = $dbh->exec("INSERT INTO USERAMOUNTS(USERNAME, AMOUNT) VALUES " . $values);
Hope this help.
The issue is with how your are trying to insert data. I'm surprised you're not getting an error.
You should use a prepared statement. See the following... https://stackoverflow.com/a/4629088/2033178
Some things are funky here.
At first it looks like you're expecting the data to come magically from $data (unless that is passed somewhere?)
$array = json_decode($data, true);
$rows = array();
foreach($array['users'] as $key => $value)
$rows[] = "('" . $key . "', '" . $value . "')";
$values = implode(",", $rows);
And then it looks like you're opening a file and parsing the JSON (but not doing the above magic with $rows[])
$fo=fopen("jsondata.json","r");
$fr=fread($fo,filesize("jsondata.json"));
$array=json_decode($fr,true);
Why not insert on the for each loop?
$fo=fopen("jsondata.json","r");
$fr=fread($fo,filesize("jsondata.json"));
$array=json_decode($fr,true);
$count = 0;
$dbh = new PDO("mysql:host=$hostname;dbname=nodejs", $username, $password);
try {
foreach($array['users'] as $key => $value)
$count = $count + $dbh->exec("INSERT INTO USERAMOUNTS(USERNAME, AMOUNT) VALUES " . $key . " " . $value . ")";
} catch ...

Php script to export mysql table data to a csv, escaping data from certain columns and mapping strings to arrays?

I need to migrate data within our old bug tracker (Zentrack) to our new one and the only import method I can use is to import from CSV. To do so I need the data from two tables, tickets and logs so I wrote the script below in php.
<?php
error_reporting(E_ALL);
$host = "localhost";
$user = "dbuser";
$pass = "dbpass";
$db = "zentrk";
$users[1] = 'john';
$users[4] = 'sally';
$users[5] = 'nick';
$users[6] = 'ralph';
$r = mysql_connect($host, $user, $pass);
if (!$r) {
echo "Could not connect to server\n";
trigger_error(mysql_error(), E_USER_ERROR);
}
echo mysql_get_server_info() . "\n";
$r2 = mysql_select_db($db);
if (!$r2) {
echo "Cannot select database\n";
trigger_error(mysql_error(), E_USER_ERROR);
}
$query_tickets = "select ZENTRACK_TICKETS.id, ZENTRACK_TICKETS.title, ZENTRACK_TICKETS.priority, ZENTRACK_TICKETS.status, ZENTRACK_TICKETS.description, ZENTRACK_TICKETS.otime,
ZENTRACK_TICKETS.type_id, ZENTRACK_TICKETS.user_id, ZENTRACK_TICKETS.system_id, ZENTRACK_TICKETS.creator_id, ZENTRACK_TICKETS.proj_key
from ZENTRACK_TICKETS
where ZENTRACK_TICKETS.status = 'OPEN'
and ZENTRACK_TICKETS.system_id in ('18', '3', '6', '1', '16', '7', '9', '4', '20')
and ZENTRACK_TICKETS.type_id not in ('1', '10', '5')";
$rs = mysql_query($query_tickets);
if (!$rs) {
echo "Could not execute query: $query";
trigger_error(mysql_error(), E_USER_ERROR);
} else {
echo "Query: $query executed\n";
}
$export = array();
$export[] = 'id,title,created date,priority,type,assigned,description,system,creator,project key,log1,log2,log3,log4,log5,log6,log7,log8,log9,log10
';
while ($row = mysql_fetch_assoc($rs)) {
$line = '';
$count = 0;
$line .= $row['id'] . "," . $row['title'] . "," . date('d-M-y h:m a',$row['otime']) . "," . $row['priority'] . "," . $row['type_id'] . "," . $row['user_id'] . "," . $row['description'] . "," . $row['system_id'] . "," . $row['creator_id'] . "," . $row['proj_key'] . ",";
$logs = find_logs($id = $row['id']);
foreach($logs as $log_entry) {
$line .= $log_entry.",";
$count++;
}
while($count < 10) {
$line .= ",";
$count++;
}
$export[] = $line.'
';
}
mysql_close();
// print_r($export);
$file = 'tickets.csv';
file_put_contents($file, $export);
function find_logs($ticket) {
$content = array();
$query = "select ZENTRACK_LOGS.created, ZENTRACK_LOGS.user_id, ZENTRACK_LOGS.entry
from ZENTRACK_LOGS
where ZENTRACK_LOGS.ticket_id = $ticket
and ZENTRACK_LOGS.action <> 'EDIT' ";
$rs = mysql_query($query);
if (!$rs) {
echo "Could not execute query: $query";
trigger_error(mysql_error(), E_USER_ERROR);
}
while ($row = mysql_fetch_assoc($rs)) {
$date = date('d-M-y h:m a',$row['created']);
$content[] = $date . ";" . $row['user_id'] . ";" . $row['entry'];
}
return $content;
}
?>
I'm running into two problems with this script, that I'm sure are due to me being new to PHP.
1) I need to escape out the data in $row['description'] as it contains both carriage returns and , in the text that is incorrectly breaking the output into new rows when saved to CSV. I need to save the contents of this row within " " but I'm not sure how to do so.
2) The data returned in $row['user_id'], $row['creator_id'] and $row['user_id'] within the find_logs function returns a number, which I need to find that number and replace with the corresponding string in the $users array. What's the best way to do this?
When dealing with csv files use fgetcsv and fputcsv, provide it with an array and it will handle the escaping for you.

how to split the data into array?

I have stored the data in a mysql database, I want to know how I can split the data in each different array before output them in php?
<?php
define('DB_HOST', 'localhost');
define('DB_USER', 'myusername');
define('DB_PASSWORD', 'mypassword');
define('DB_DATABASE', 'mydbname');
$errmsg_arr = array();
$errflag = false;
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link)
{
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if(!$db)
{
die("Unable to select database");
}
if($errflag)
{
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
echo implode('<br />',$errmsg_arr);
}
else
{
$qrytable1="SELECT id, mydata FROM mydb ";
$result1=mysql_query($qrytable1) or die('Error:<br />' . $qry . '<br />' . mysql_error());
while ($row = mysql_fetch_array($result1))
{
echo "<tr><td>".$row['mydata']."</td></tr>";
}
}
?>
On my PHP page it show something like this:
<tr><td>my data 1</td></tr><tr><td>my data 2</td></tr><tr><td>my data 3</td></tr><tr><td>my data 4</td></tr>
I want to split them up by turn into array and output them with each different array to something like this:
mydata1
mydata2
mydata3
mydata4
How I can split the data into array before I could output them in my php?
Are you looking for something like this?
(consider it as an example, but, as #BenM, consider using PDO)
$sql = 'SELECT * FROM country';
$query = mysql_query($sql);
$countries = array();
while ($country = mysql_fetch_assoc($query)){ $countries[] = $country; }
This will allow you to use
foreach ($countries as $country) {
echo $country['name'];
}
Your data is already in an array. That's what this line does:
while ($row = mysql_fetch_array($result1))
{
echo "<tr><td>".$row['mydata']."</td></tr>";
}
If you need to access the array outside of the while loop you could do this..
$myArray = array();
while ($row = mysql_fetch_array($result1)){
echo "<tr><td>".$row['mydata']."</td></tr>";
foreach($row as $key=>$val){
$myArray[$key] = $val;
}
}
actually.. assuming your query returns multiple rows it would be a multidimensional array..
$myArray = array();
$i = 0;
while ($row = mysql_fetch_array($result1)){
echo "<tr><td>".$row['mydata']."</td></tr>";
foreach($row as $key=>$val){
$myArray[$i][$key] = $val;
$i++;
}
}
If I am right than along with getting data in array you want to remove the space in between the data
try this
while ($row = mysql_fetch_array($result1))
{
echo "<tr><td>".$row['mydata']."</td></tr>";
$myArr[] = $row['mydata'];
}
foreach($myarr as $key=>$value)
{
$myArr[$key] = str_replace(" ","",$value);
}
str_replace will remove the spaces.
You can used this,
$db->setQuery($query);
$rows = $db->loadObjectList();
$i=0;
foreach($rows as $row){
//$row;
$image = json_decode($row->images);
// split code
$str = utf8_encode($row->introtext);
$order = array("<p>", "</p>", "\n", "\r");
$replace = '';
$introtext = str_replace($order, $replace, $str);
$introtext_split = explode("|", $introtext);
$data[0]->designation = preg_replace('#<br />?#', "\n", $introtext_split[0]);
$data[0]->description = preg_replace('#<br />?#', "\n\n", $introtext_split[1]);
$data[0]->small_description = preg_replace('#<br />?#', "\n\n", $introtext_split[2]);
}
In data used any tag, Or this tag replace using following section :
$str = utf8_encode($row->introtext);
$order = array("<p>", "</p>", "\n", "\r");
I think its useful to you.

Exporting Data from SQl to Excel Using PHP [duplicate]

This question already has answers here:
Warning: mysql_fetch_assoc() expects parameter 1 to be resource, object given [duplicate]
(2 answers)
Closed last year.
So the admin has the choice to choose what he want to export to excel by selecting checkboxes which i stored in col[]...
here's my code for exporting
session_start();
$HOST = 'localhost';
$USERNAME = 'root';
$PASSWORD = '';
$DB = 'fyp_db';
$link = mysqli_connect($HOST, $USERNAME, $PASSWORD, $DB);
if (is_array($_POST['col'])) {
$sql = "SELECT ";
foreach ($_POST['col'] AS $value) {
$sql .= "{$value}, ";
}
$sql = substr($sql, 0, -2);
$sql .= " FROM account, coursedetail, coursecategory";
/*echo "sql= " . $sql . "<br /><br />\n";*/
} else {
echo "No column was selected<br /><br />\n";
}
function cleanData(&$str) { $str = preg_replace("/\t/", "\\t", $str); $str = preg_replace("/\r?\n/", "\\n", $str); if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"'; }
$filename = "website_data.xls";
header("Content-Type: text/plain");
$flag = false;
$result = mysqli_query($link, $sql) or die(mysqli_error($link));
while(false !== ($row = mysql_fetch_assoc($result))) {
if(!$flag) {
// display field/column names as first row
echo implode("\t", array_keys($row)) . "\r\n";
$flag = true;
}
array_walk($row, 'cleanData');
echo implode("\t", array_values($row)) . "\r\n";
}
I got the error of..
Warning: mysql_fetch_assoc() expects parameter 1 to be resource, object given in C:\xampp\htdocs\project\export_successful.php on line 28
why? :(
You're mixing up mysqli and mysql calls. The two libraries are NOT compatible and handles/statements returned by one cannot be used in the other.
$result = mysqli_query($link, $sql) or die(mysqli_error($link));
^--- note the 'i'
while(false !== ($row = mysql_fetch_assoc($result))) {
^--- note the LACK of an 'i'

Export more than one DB Table as SQL Data

I'm looking to export 11 Database tables' data as XML. I've easily managed to export one table, without issue. But I am looking to export more than one really.
I'm sure theres a way and obviously output the data as seperate table entitys. Any help is much appreciated on this one, As I'm finding it a little tricky.
My code is as follows
<?php
error_reporting(E_ALL);
$host = "localhost";
$user = "root";
$pass = "";
$database = "db_etch";
$table = "keywords";
$SQL_query = "SELECT * FROM $table";
$DB_link = mysql_connect($host, $user, $pass) or die("Could not connect to host.");
mysql_select_db($database, $DB_link) or die ("Could not find or access the database.");
$result = mysql_query ($SQL_query, $DB_link) or die ("Data not found. Your SQL query didn't work... ");
// produce XML
header("Content-type: text/xml");
$XML = "<?xml version=\"1.0\"?>\n";
// root node
$XML .= "<result>\n";
// rows
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$XML .= "\t<$table>\n";
$i = 0;
// cells
foreach ($row as $cell) {
$cell = str_replace("&", "&", $cell);
$cell = str_replace("<", "<", $cell);
$cell = str_replace(">", ">", $cell);
$cell = str_replace("\"", """, $cell);
$col_name = mysql_field_name($result,$i);
$XML .= "\t\t<" . $col_name . ">" . $cell . "</" . $col_name . ">\n";
$i++;
}
$XML .= "\t</$table>\n";
}
$XML .= "</result>\n";
// output the whole XML string
echo $XML;
// Write $sql to file
$File = "keywords.xml";
$fh = fopen($File, 'w') or die("can't open file");
$stringData = $XML;
fwrite($fh, $stringData);
fclose($fh);
?>
I changed some of your code, assuming some little extra what you wanted:
Changed str_replace() to htmlspecialchars()
Moved xml start to the beginning.
Added a new root node.
That's about it. If you want to output all tables from a certain db, you should use "show tables;" -query to find out the tables that the db consist of.
<?php
error_reporting(E_ALL);
$host = "localhost";
$user = "root";
$pass = "";
$database = "db_etch";
$table = "keywords";
$tables_to_output_array = array('keywords', 'othertable1', 'othertable2');
$DB_link = mysql_connect($host, $user, $pass) or die("Could not connect to host.");
mysql_select_db($database, $DB_link) or die ("Could not find or access the database.");
// produce XML
header("Content-type: text/xml");
$XML = "<?xml version=\"1.0\"?>\n";
// root node
$XML .= "<tables>\n";
while (list(, $table) = each($tables_to_output_array)) {
$SQL_query = "SELECT * FROM $table";
$result = mysql_query ($SQL_query, $DB_link) or die ("Data not found. Your SQL query didn't work... ");
// tables
$XML .= "\t<$table>\n";
// rows
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$XML .= "\t\t<row>\n";
$i = 0;
// cells
foreach ($row as $cell) {
$col_name = mysql_field_name($result,$i);
$XML .= "\t\t\t<" . $col_name . ">" . htmlspecialchars($cell) . "</" . $col_name . ">\n";
$i++;
}
$XML .= "\t\t</row>\n";
}
$XML .= "\t</$table>\n";
}
$XML .= "</tables>\n";
// output the whole XML string
echo $XML;
// Write $sql to file
$File = "keywords.xml";
$fh = fopen($File, 'w') or die("can't open file");
$stringData = $XML;
fwrite($fh, $stringData);
fclose($fh);
?>

Categories