How to get field name using the improved MySQL (MySQLI)? [duplicate] - php

This question already has answers here:
Building a HTML table using MySQL/PHP results
(3 answers)
Closed 5 years ago.
The following is a PHP code that I'm using to convert a MySQL table into csv output. However, I couldn't figure out how to convert MySQL_field_name to the equivalent in MySQLI. Can anyone assist?
<?php
/* vars for export */
// database record to be exported
$db_record = 'manufacturing_';
// optional where query
$where = 'WHERE 1 ORDER BY 1';
// filename for export
$csv_filename = 'db_export_'.$db_record.'_'.date('Y-m-d').'.csv';
// database variables
$hostname = "localhost";
$user = "XXXXXXXXX";
$password = "XXXXXXXXX";
$database = "XXXXXXXXX";
// Database connecten voor alle services
$connection = mysqli_connect($hostname, $user, $password) or die('Could not connect: ' . mysqli_error());
mysqli_select_db($connection, $database) or die ('Could not select database ' . mysqli_error());
// create empty variable to be filled with export data
$csv_export = '';
// query to get data from database
$query = mysqli_query($connection, "SELECT * FROM ".$db_record." ".$where);
$field = mysqli_num_fields($query);
// create line with field names
for($i = 0; $i < $field; $i++) {
$csv_export.= mysqli_field_name($connection, $query,$i).';';
}
// newline (seems to work both on Linux & Windows servers)
$csv_export.= '
';
// loop through database query and fill export variable
while($row = mysqli_fetch_array($connection, $query)) {
// create line with field values
for($i = 0; $i < $field; $i++) {
$csv_export.= '"'.$row[mysqli_field_name($connection, $query,$i)].'";';
}
$csv_export.= '
';
}
// Export the data and prompt a csv file for download
header("Content-type: text/x-csv");
header("Content-Disposition: attachment; filename=".$csv_filename."");
echo($csv_export);
?>
Error Message:
Fatal error: Call to undefined function mysqli_field_name()

You can get this infos from INFORMATION_SCHEMA with a query like this. you only must change the TABLE_SCHEMA and the TABLE_NAME
SELECT COLUMN_NAME
FROM information_schema.columns
WHERE TABLE_NAME ='owner' AND TABLE_SCHEMA='test'
ORDER BY ORDINAL_POSITION;

Related

PHP getting results from access not getting dates

I'm using the below code to query an access database using PHP.
<?php
// Create an instance of the ADO connection object
$conn = new COM ("ADODB.Connection") or die("Cannot start ADO");
// Define the connection string and specify the database driver
$connStr = "PROVIDER=Microsoft.Ace.OLEDB.12.0;Data Source=".realpath("HS_BE.accdb").";";
// Open the connection to the database
$conn->open($connStr);
// Declare the SQL statement that will query the database
$query = "SELECT TOP 20 * FROM Valuations WHERE Consultant = '1'";
// Execute the SQL statement and return records
$rs = $conn->execute($query);
$num_columns = $rs->Fields->Count ();
$arrColumns = array();
for ($i=0; $i < $num_columns; $i++) {
$arrColumns[] = $rs->Fields($i);
$newArr[] = $rs->Fields($i)->name;
}
$arrResult = array();
while (!$rs->EOF) {
$arrRow = array();
for ($i=0; $i < $num_columns; $i++) {
$arrRow[$newArr[$i]] = $arrColumns[$i]->value;
}
$arrResult[] = $arrRow;
$rs->MoveNext();
}
header('Content-Type: application/json');
echo json_encode($arrResult);
This is half working, all the text fields are returning fine but the date fields are returning as {} with nothing inside, does anyone know why its choosing to ignore the date fields?
EDIT
When i var_dump $arrResult before converting to json, this is what one of the dates is :
["Appointment"]=>
object(variant)#77 (0) {
}
You most likely need to add charset=utf8 to your connection or to utf8_encode() the date before you json_encode() it.
You could also use:
mysql_query('SET CHARACTER SET utf8')
before your SELECT query.
i did this :
$arrRow[$newArr[$i]] = (string)$arrColumns[$i]->value;
Converting it to a string and it worked

Create MySQL table dynamically from Excel CSV file

My goal is to create a MySQL table containing data from my CSV file.
I know how to create a MySQL table and how to load data from excel in it.
But the problem is:
I have a large CSV file containing long column names (questions labels for example "Q27 : Are you happy with the after sales service?") so it would be boring to create a MySQL table by copying all column names(almost 35) and add 'VARCHAR(100) NOT NULL'.
That's why I would like to write a small php script to create a MySQL table by getting the first row of my file, and then fill it with the rest of the csv file data.
For now, my script looks like this :
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$database = 'test';
$db = #mysql_connect($host, $user, $pass) or die('mysql connection pb');
#mysql_select_db($database) or die('database selection pb');
/********************************************************************************/
// Parameters: filename.csv table_name
$argv = $_SERVER['argv'];
if($argv[1]) { $file = $argv[1]; }
else {
echo "Please provide a file name\n"; exit;
}
if($argv[2]) {
$table = $argv[2];
}
else {
echo "Please provide a table name\n";
$table = pathinfo($file);
$table = $table['filename'];
}
/**************************************************************************** ****/
// Get the first row to create the column headings
$fp = fopen($file, 'r');
$frow = fgetcsv($fp,";");
$columns=false;
print_r($frow);
foreach($frow as $column) {
if($columns) $columns .= ', ';
$columns .= "`$column` VARCHAR(250) NOT NULL";
}
$create = "create table if not exists $table ($columns);";
#mysql_query($create, $db) or die('table creation pb');
/**************************************************************************** ****/
// Import the data into the newly created table.
$file = addslashes(realpath(dirname(__FILE__)).'\\'.$file);
$q = "load data infile '$file' into table $table fields terminated by ',' ignore 1 lines";
#mysql_query($q, $db);
?>
And when i run in command line : php myscript.php csvfile.csv mytable, it appears that the problem is in the table creation query.
And on top of that the column names are not well identified even though they are separated by ";" in the csv.
As mentioned refrain from using mysql_ functions which as of PHP 7 (current version) this extension is no longer available. Use either mysqli or PDO.
Below is a PDO example with try/catch (more informative than die()). Also, the csv read is handled slightly different and its concatenation in SQL create table string.
<?php
$host="localhost";
$username="root";
$password="password";
$database="test"
// Parameters: filename.csv table_name
$argv = $_SERVER['argv'];
if($argv[1]) {
$file = $argv[1];
} else {
echo "Please provide a file name\n";
exit;
}
if($argv[2]) {
$table = $argv[2];
} else {
echo "Please provide a table name\n";
$table = pathinfo($file);
$table = $table['filename'];
}
// Read in only first row of CSV file
$handle = fopen($file, "r");
$row = 1;
$columns = [];
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE AND $row==1) {
$columns = $data;
$row++;
}
//SQL string commands
$createSQL = "CREATE TABLE IF NOT EXISTS $table
(".implode(" VARCHAR(255) NOT NULL, ", $columns). "
VARCHAR(255) NOT NULL);";
$file = addslashes(realpath(dirname(__FILE__)).'\\'.$file);
$loadSQL = "LOAD DATA INFILE '$file'
INTO TABLE $table
FIELDS TERMINATED BY ','
IGNORE 1 LINES";
// Open database connection
try {
$dbh = new PDO("mysql:host=$host;dbname=$database",$username,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Execute queries
$S1TH = $dbh->query($createSQL);
$S2TH = $dbh->query($loadSQL);
}
catch(PDOException $e) {
echo $e->getMessage();
}
# Close database connection
$dbh = null;
?>

replace non breaking space PHP

* The json_encode is returning NULL? is NOT the answer. I still receive a NULL when using the json_encode.*
I am very new to PHP, so if you could edit the section with the fixed code, I'd appreciate it.
This is my problem:
When an article under "introtext" contains non breaking lines, it returns NULL. The articles that do not have a non breaking space show up just fine.
This is my question:
How can I get the articles under "introtext" to display properly even if they contain a non breaking space.
Here's the code:
$connection = mysqli_connect($host, $user, $pass);
//Check to see if we can connect to the server
if(!$connection)
{
die("Database server connection failed.");
}else{
//Attempt to select the database
$dbconnect = mysqli_select_db($connection, $db);
//Check to see if we could select the database
if(!$dbconnect)
{
die("Unable to connect to the specified database!");
}else{
$catID = $_GET['catid'];
$id = $_GET['id'];
$rtn = $_GET['rtn'];
if($id!=""){
$query = "SELECT * FROM tcp_content WHERE id=" . $id . "";
}else{
$query = "SELECT * FROM tcp_content WHERE catid=" . $catID . " ORDER BY publish_up DESC LIMIT " . $rtn . "";
}
$resultset = mysqli_query($connection,$query);
$records = array();
//Loop through all records and add them to array
while($r = mysqli_fetch_assoc($resultset))
{
$r['introtext'] = print_r($r['introtext'],true);
$records[] = $r;
}
//Output the data as JSON
echo json_encode($records);
}
}
?>
here are two links:
This link contains the non breaking space, so you'll notice introtext returns NULL
This link does NOT contain the non breaking space, so you'll notice the article shows
I found this link json_encode problem
see second answer. Charles is suggesting that use iconv() to remove URL encoded non-breaking space.
I finally figured it out and got it working
$r['introtext'] = utf8_encode($r['introtext']);
$r['introtext'] = str_replace(chr(194).chr(160),' ',$r['introtext']);
$r['introtext'] = str_replace(chr(194).chr(147),'"',$r['introtext']);
$r['introtext'] = str_replace(chr(194).chr(148),'"',$r['introtext']);
$r['introtext'] = str_replace(chr(194).chr(146),"'",$r['introtext']);
$r['introtext'] = str_replace(chr(194).chr(145),"'",$r['introtext']);
$r['introtext'] = htmlentities($r['introtext'], ENT_QUOTES | ENT_IGNORE, "UTF-8");
$records = $r;

CSV export not sorting the data in tabs mysql php

I have a script that exports SQL query to CSV, when I export it, the data is in the correct columns and the tabs are correct on my excel. But on different excel versions the data is not sorted, the columns are correct in the first row but the data below is not correct. This is result I receive in the incorrect version on the second where the data displays.
3283;"Jame Bond";"Clint Josh";"a#A.d";"3";"3";"3";"3 3";"";"";"";
CSV export script
$sql_new = urldecode($_GET['r']);
$sql_new = str_replace('\\','',$sql_new);
$hostname = "localhost";
$user = "root";
$password = "";
$database = "mydb";
mysql_connect($hostname, $user, $password)
or die('Could not connect: ' . mysql_error());
mysql_select_db($database)
or die ('Could not select database ' . mysql_error());
// create empty variable to be filled with export data
$csv_export = '';
// query to get data from database
$query = mysql_query($sql_new);
$field = mysql_num_fields($query);
// create line with field names
for($i = 0; $i < $field; $i++) {
$csv_export.= mysql_field_name($query,$i).';';
}
// newline (seems to work both on Linux & Windows servers)
$csv_export.= '
';
// loop through database query and fill export variable
while($row = mysql_fetch_array($query)) {
// create line with field values
for($i = 0; $i < $field; $i++) {
$csv_export.= '"'.$row[mysql_field_name($query,$i)].'";';
}
$csv_export.= '
';
}
// Export the data and prompt a csv file for download
header("Content-type: text/x-csv");
header("Content-Disposition: attachment; filename=".$csv_filename."");
echo($csv_export);

how to acess my database elements using the for loop?

I'm learning PHP and I'm well versed with Java and C. I was given a practice assignment to create a shopping project. I need to pull out the products from my database. I'm using the product id to do this. I thought of using for loop but I can't access the prod_id from the database as a condition to check! Can anybody help me?! I have done all the form handling but I need to output the products. This is the for-loop I am using. Please let me know if I have to add any more info. Thanks in advance :)
for($i=1; $i + 1 < prod_id; $i++)
{
$query = "SELECT * FROM products where prod_id=$i";
}
I would suggest that you use PDO. This method will secure all your SQLand will keep all your connections closed and intact.
Here is an example
EXAMPLE.
This is your dbc class (dbc.php)
<?php
class dbc {
public $dbserver = 'server';
public $dbusername = 'user';
public $dbpassword = 'pass';
public $dbname = 'db';
function openDb() {
try {
$db = new PDO('mysql:host=' . $this->dbserver . ';dbname=' . $this->dbname . ';charset=utf8', '' . $this->dbusername . '', '' . $this->dbpassword . '');
} catch (PDOException $e) {
die("error, please try again");
}
return $db;
}
function getproduct($id) {
//prepared query to prevent SQL injections
$query = "SELECT * FROM products where prod_id=?";
$stmt = $this->openDb()->prepare($query);
$stmt->bindValue(1, $id, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $rows;
}
?>
your PHP page:
<?php
require "dbc.php";
for($i=1; $i+1<prod_id; $i++)
{
$getList = $db->getproduct($i);
//for each loop will be useful Only if there are more than one records (FYI)
foreach ($getList as $key=> $row) {
echo $row['columnName'] .' key: '. $key;
}
}
First of all, you should use database access drivers to connect to your database.
Your query should not be passed to cycle. It is very rare situation, when such approach is needed. Better to use WHERE condition clause properly.
To get all rows from products table you may just ommit WHERE clause. Consider reading of manual at http://dev.mysql.com/doc.
The statement selects all rows if there is no WHERE clause.
Following example is for MySQLi driver.
// connection to MySQL:
// replace host, login, password, database with real values.
$dbms = mysqli_connect('host', 'login', 'password', 'database');
// if not connected then exit:
if($dbms->connect_errno)exit($dbms->connect_error);
$sql = "SELECT * FROM products";
// executing query:
$result = $dbms->query($sql);
// if query failed then exit:
if($dbms->errno)exit($dbms->error);
// for each result row as $product:
while($product = $row->fetch_assoc()){
// output:
var_dump($product); // replace it with requied template
}
// free result memory:
$result->free();
// close dbms connection:
$dbms->close();
for($i=1;$i+1<prod_id;$i++) {
$query = "SELECT * FROM products where prod_id=$i";
$result = mysqli_query($query, $con);
$con is the Database connection details
you can use wile loop to loop thru each rows
while ($row = mysqli_fetch_array($result))
{
......
}
}
Hope this might work as per your need..
for($i=1; $i+1<prod_id; $i++) {
$query = "SELECT * FROM products where prod_id = $i";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
print_r($row);
}
}
I think you want all records from your table, if this is the requirement you can easily do it
$query = mysql_query("SELECT * FROM products"); // where condition is optional
while($row=mysql_fetch_array($query)){
print_r($row);
echo '<br>';
}
This will print an associative array for each row, you can access each field like
echo $row['prod_id'];

Categories