I want to be able to parse a SQL database with PHP to output an XML, however I cannot get it to show the table name and all of it's contents. I could use some help, here is my code without login information:
I have defined the db server,mdb user and pass, and db name; should anything else be defined?
<?php
// connection to the database
$dbhandle = mysql_connect(DB_SERVER, DB_USER, DB_PASS)
or die("Unable to connect to MySQL");
// select a database to work with
$selected = mysql_select_db(DB_NAME, $dbhandle)
or die("Could not select data");
// return all available tables
$result_tbl = mysql_query( "SHOW TABLES FROM "DB_NAME, $dbhandle );
$tables = array();
while ($row = mysql_fetch_row($result_tbl)) {
$tables[] = $row[0];
}
$output = "<?xml version=\"1.0\" ?>\n";
$output .= "<schema>";
// iterate over each table and return the fields for each table
foreach ( $tables as $table ) {
$output .= "<table name=\"$table\">";
$result_fld = mysql_query( "SHOW FIELDS FROM "$table, $dbhandle );
while( $row1 = mysql_fetch_row($result_fld) ) {
$output .= "<field name=\"$row1[0]\" type=\"$row1[1]\"";
$output .= ($row1[3] == "PRI") ? " primary_key=\"yes\" />" : " />";
}
$output .= "</table>";
}
$output .= "</schema>";
// tell the browser what kind of file is come in
header("Content-type: text/xml");
// print out XML that describes the schema
echo $output;
// close the connection
mysql_close($dbhandle);
?>
I think it's better to use standard php class XmlWriter for this one.
Look at http://www.php.net/manual/en/book.xmlwriter.php
$result_tbl = mysql_query( "SHOW TABLES FROM "DB_NAME, $dbhandle );
^^^---typo
$result_fld = mysql_query( "SHOW FIELDS FROM "$table, $dbhandle );
^^^---typo
You've got at least two typos in your queries. Most likely you want this:
$result_tbl = mysql_query("SHOW TABLES FROM " . DB_NAME, $dbhandle) or die(mysql_error());
and
$result_fld = mysql_query("SHOW FIELDS FROM $table", $dbhandle) or die(mysql_error());
Note the concatenation operator (.) on the first one, and the addition of or die(...). Never assume a query succeeds. even if the query string itself is syntactically correct, there's far too many OTHER reasons is could fail to NOT check for an error condition.
Related
*The condition for "die" had been left out of my code by mistake when I copied it to the question. I put it back in.
I know this question might seem repetitive, but I have not found an answer in any of the other questions. I am trying to create a drop-down list based off a column in a database. I have tried two different ways and neither gave me correct results. Does anyone know a correct way of doing this?
The first way I saw in other StackOverflow answers (Fetching data from MySQL database to html drop-down list, Fetching data from MySQL database to html dropdown list). My code is below:
<?php
$connect = mysql_connect('localhost', 'root');
if ($connect == false)
{
die ("Unable to connect to database<br>");
}
$select = mysql_select_db('ViviansVacations');
if ($select == false)
{
die ("Unable to select database<br>");
}
$query = "SELECT * FROM Destinations";
$result = mysql_query($query);
?>
<select name="select1">
<?php
while ($row = mysql_fetch_array($result))
{
echo "<option value='". $row['Europe'] ."'>" .$row['Europe'] ."</option>" ;
}
?>
</select>
NetBeans sends me an error saying that "Text not allowed in element 'select' in this context".
The second way I tried:
<?php
$connect = mysql_connect('localhost', 'root');
{
die ("Unable to connect to database<br>");
}
$select = mysql_select_db('ViviansVacations');
{
die ("Unable to select database<br>");
}
$query = "SELECT * FROM Destinations";
$result = mysql_query($query);
?>
<select name="select1">
<?php
while ($line = mysql_fetch_array($result))
{
?>
<option value="<?php echo $line['Europe'];?>"> <?php echo
$line['field'];?> </option>
<?php
}
?>
</select>
This code did not produce any errors. However, inside the form were the opening php lines followed by an empty drop down box:
"); } $select = mysql_select_db('ViviansVacations'); { die ("Unable to select database
"); } $query = "SELECT * FROM Destinations"; $result = mysql_query($query); ?>
So there are many problems with your approach. First of all you are using a deprecated mysql_* functions which is bad idea and second you are not debugging your database connection properly :
$connect = mysql_connect('localhost', 'root');
{
die ("Unable to connect to database<br>");
}
In above code the die statement will always execute stopping further execution.
Also make sure the database ViviansVacations and table Destinations and column Europe exists with correct names(Follow standards and try to use all small letters for database/table/column naming)
The correct mysqli_* approach is(tested locally and the select box forms correctly) :
<?php
$db = 'ViviansVacations';
$mysqli = new mysqli('localhost', 'root', '', $db);
if($mysqli->connect_error)
die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
$query = "SELECT * FROM Destinations";
$result = mysqli_query($mysqli, $query);
?>
<select name="select1">
<?php
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['Europe'] . "'>" . $row['Europe'] . "</option>";
}
?>
</select>
There are couple of things, you to verify and correct.
First of all, your database connection code, that doesn't seems to be correct. I didn't see any condition on which you are suppose to invoke die.
$connect = mysql_connect('localhost', 'root');
{
die ("Unable to connect to database<br>");
}
From the above code, below line will execute all the time
die ("Unable to connect to database<br>");
You should correct your database connection code to below :
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
You can refer mysql_connect for the usage.
Also, verify your file extension is .php
Mainly your problem is database connection. Try this -
<?php
mysql_connect("localhost", "root", "") or
die("Could not connect: " . mysql_error());
mysql_select_db("your_db");
$result = mysql_query("SELECT * FROM your_table");
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
print_r($row);
echo "<br>";
}
mysql_free_result($result);
?>
There could be few issues:
Use mysqli_connect instead of mysql_connect because mysql is depreciated
Make 3rd parameter as empty `mysqli_connect('localhost', 'root', '');//as per standards
Debug your code for example: (print_r($connect), execute your query in phpmyadmin, print_r($result) and then in loop print_r($row).
At end, I am sure you will get your desired result and also you will know in detail that what was happening.
You might want to try to use this ..The dept_id and the description u have to change according to your database .Hope this will help you
<?php
$sql = mysql_query("SELECT dept_id ,description FROM department
ORDER BY dept_id ASC");
db_select($sql,"dept_id",$dept_id,"","-select Department-","","");
?>
I just need to know how to print out the table names and columns, everything I try doesn't work even though this is apparently very simple. I've looked everywhere and I can't find anything that will print out the columns. Can anyone help?
The following code should pull out the information you're after.
<?php
$mysqli = new mysqli("hostname", "username", "password", "database");
if($mysqli->connect_errno)
{
echo "Error connecting to database.";
}
// Gather all table names into an array.
$query = "SHOW TABLES";
$result = $mysqli->query($query);
$tables = $result->fetch_all();
// Step through the array, only accessing the first element (the table name)
// and gather the column names in each table.
foreach($tables as $table)
{
echo "<h2>" . $table[0] . "</h2>";
$query = "DESCRIBE " . $table[0];
$result = $mysqli->query($query);
$columns = $result->fetch_all();
foreach($columns as $column)
{
echo $column[0] . "<br />";
}
}
$mysqli->close();
?>
The MySQL syntax for those uses the command SHOW which can be used to show the tables in the selected database (SHOW tables;) or output table structure (SHOW tableName;).
Here is functional code to see the tables in the current database so long as you update the connection details (first line of code):
$mysqli = new mysqli("server.com", "userName", "password", "dbName");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$query = "SHOW tables;";
$result = $mysqli->query($query);
/* associative array */
$rows = $result->fetch_all(MYSQLI_ASSOC);
var_export($rows);
$result->free();
/* close connection */
$mysqli->close();
The code below is working for one if statement but not giving results for another else if and it is showing the 'flights' table in first query but after another condition not display the other table named 'isb to muree'
<?php
$from = isset($_POST['from'])?$_POST['from']:'';
$To = isset($_POST['To'])?$_POST['To']:'';
if( $from =='Islamabad'){
if($To == 'Lahore'){
$db_host = 'localhost';
$db_user = 'root';
$database = 'homedb';
//$table = 'flights';
if (!mysql_connect($db_host, $db_user))
die("Can't connect to database");
if (!mysql_select_db($database))
die("Can't select database");
$result = mysql_query("SELECT * FROM flights");
if (!$result) {
die("Query to show fields from table failed");
}
$fields_num = mysql_num_fields($result);
echo "<h1>Table: 'flights'</h1>";
echo "<table border='1'><tr>";
while($row = mysql_fetch_row($result))
{
echo "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>\n";
}
}
else if( $from =='Islamabad'){
if($To == 'murree'){
if (!mysql_connect($db_host, $db_user))
die("Can't connect to database");
if (!mysql_select_db($database))
die("Can't select database");
$result = mysql_query("SELECT * FROM 'isb to murree'");
if (!$result) {
die("Query to show fields from table failed");
}
$fields_num = mysql_num_fields($result);
echo "<h1>Table: 'isb to murree'</h1>";
echo "<table border='1'><tr>";
while($row = mysql_fetch_row($result))
{
echo "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>\n";
}
}
}
}
mysqli_close($con);
?>
Enclose the table name in backticks (`) instead of single quotes ('):
SELECT * FROM `isb to murree`
To avoid this and other problems in the future, always enclose schema, table, and column names in backticks to distinquish them from data and MySQL keywords. Consider using table names without spaces for easier handling.
As Fred noted, your code is using two database APIs: mysql_* and mysqli_* . In general, the two do not mix well. Consider upgrading all of your code to use mysqli_* or PDO. See Deprecated features in PHP 5.5.x and Why are PHP's mysql_ functions deprecated? for mysql_* deprecation notes.
You should move the database connection variables to the top of your code (so they are outside of the if statement)
$db_host = 'localhost';
$db_user = 'root';
$database = 'homedb';
I am fetching some data having UTF8 collation (utf8_unicode_ci) from a MySQL database with PHP. I am using this piece of code:
function advancedDatabaseSearch($pattern, $lpref) {
$link = mysql_connect(DB_URL, DB_USER, DB_PWD);
if (!$link) {
return 'Could not connect: ' . mysql_error();
}
$esc_value = mysql_real_escape_string($pattern);
$esc_lpref = mysql_real_escape_string($lpref);
mysql_select_db(DB_NAME, $link);
$query = "SELECT RAWVALUE FROM rawvalueitem "
."WHERE RAWVALUE LIKE '".$esc_value."' "
."AND LANGUAGE = '".$esc_lpref."' "
."ORDER BY RAWVALUE ASC";
$result = mysql_query($query);
$return = "";
while($row = mysql_fetch_array($result)) {
$return = $return.$row['RAWVALUE']." ";
}
mysql_close($link);
return $return;
}
and then from the php called by Ajax:
$result = advancedDatabaseSearch($tttmp, $lpref);
echo $result;
return;
Yet, when I display the result in a text area, the accents are not displayed properly:
On the other side, when I fetch UT8 data from a file:
if ( $file_loc != NULL ) {
if ( file_exists($file_loc) ) {
$handle = fopen($file_loc, "rb");
$contents = fread($handle, filesize($file_loc));
fclose($handle);
$result = $contents;
}
}
echo $result;
return;
I don't get this issue !!! How can I solve it when using PHP to fetch data from MySql?
Did you set UTF-8 as the default character set of your database connection?
mysql_set_charset('utf8', $link);
http://www.php.net/manual/en/function.mysql-set-charset.php
Also, does your page have a <meta> tag with the correct character set?
This is working like a.. you now!
<?php
$config_db_server='localhost';
$config_db_server_username='root';
$config_db_server_password='';
$config_db_database='test';
$config_db_charset='utf8';
$config_db_collation='utf8_general_ci';
$config_table_prefix='class_';
$config_live_site='http://localhost';
$config_abs_path='C:\xampp\htdocs';
$config_debug=0;
$dbLink = mysql_connect($config_db_server, $config_db_server_username, $config_db_server_password);
mysql_query("SET character_set_results=utf8", $dbLink);
mb_internal_encoding('utf8');
mysql_query("set names 'utf8'",$dbLink);
?>
Change here your db connect: ( $dbLink = mysql_connect($config_db_server, $config_db_server_username, $config_db_server_password); )
I was wondering if there's a way in PHP to list all available databases by usage of mysqli. The following works smooth in MySQL (see php docs):
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$db_list = mysql_list_dbs($link);
while ($row = mysql_fetch_object($db_list)) {
echo $row->Database . "\n";
}
Can I Change:
$db_list = mysql_list_dbs($link); // mysql
Into something like:
$db_list = mysqli_list_dbs($link); // mysqli
If this is not working, would it be possible to convert a created mysqli connection into a regular mysql and continue fetching/querying on the new converted connection?
It doesn't appear as though there's a function available to do this, but you can execute a show databases; query and the rows returned will be the databases available.
EXAMPLE:
Replace this:
$db_list = mysql_list_dbs($link); //mysql
With this:
$db_list = mysqli_query($link, "SHOW DATABASES"); //mysqli
I realize this is an old thread but, searching the 'net still doesn't seem to help. Here's my solution;
$sql="SHOW DATABASES";
$link = mysqli_connect($dbhost,$dbuser,$dbpass) or die ('Error connecting to mysql: ' . mysqli_error($link).'\r\n');
if (!($result=mysqli_query($link,$sql))) {
printf("Error: %s\n", mysqli_error($link));
}
while( $row = mysqli_fetch_row( $result ) ){
if (($row[0]!="information_schema") && ($row[0]!="mysql")) {
echo $row[0]."\r\n";
}
}
Similar to Rick's answer, but this is the way to do it if you prefer to use mysqli in object-orientated fashion:
$mysqli = ... // This object is my equivalent of Rick's $link object.
$sql = "SHOW DATABASES";
$result = $mysqli->query($sql);
if ($result === false) {
throw new Exception("Could not execute query: " . $mysqli->error);
}
$db_names = array();
while($row = $result->fetch_array(MYSQLI_NUM)) { // for each row of the resultset
$db_names[] = $row[0]; // Add db name to $db_names array
}
echo "Database names: " . PHP_EOL . print_r($db_names, TRUE); // display array
Here is a complete and extended solution for the answer, there are some databases that you do not need to read because those databases are system databases and we do not want them to appear on our result set, these system databases differ by the setup you have in your SQL so this solution will help in any kind of situations.
first you have to make database connection in OOP
//error reporting Procedural way
//mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
//error reporting OOP way
$driver = new mysqli_driver();
$driver->report_mode = MYSQLI_REPORT_ALL & MYSQLI_REPORT_STRICT;
$conn = new mysqli("localhost","root","kasun12345");
using Index array of search result
$dbtoSkip = array("information_schema","mysql","performance_schema","sys");
$result = $conn->query("show databases");
while($row = $result->fetch_array(MYSQLI_NUM)){
$print = true;
foreach($dbtoSkip as $key=>$vlue){
if($row[0] == $vlue) {
$print=false;
unset($dbtoSkip[$key]);
}
}
if($print){
echo '<br/>'.$row[0];
}
}
same with Assoc array of search result
$dbtoSkip = array("information_schema","mysql","performance_schema","sys");
$result = $conn->query("show databases");
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$print = true;
foreach($dbtoSkip as $key=>$vlue){
if($row["Database"] == $vlue) {
$print=false;
unset($dbtoSkip[$key]);
}
}
if($print){
echo '<br/>'.$row["Database"];
}
}
same using object of search result
$dbtoSkip = array("information_schema","mysql","performance_schema","sys");
$result = $conn->query("show databases");
while($obj = $result->fetch_object()){
$print = true;
foreach($dbtoSkip as $key=>$vlue){
if( $obj->Database == $vlue) {
$print=false;
unset($dbtoSkip[$key]);
}
}
if($print){
echo '<br/>'. $obj->Database;
}
}