Display COLUMN NAMES from database through PHP - php

I am trying to pull all the column names from my database 'settings' and list them in PHP.
A bit of research has come up with the following:
SHOW COLUMNS FROM settings
but I don't know how to go about listing these off through PHP.
it would be helpful if any code posted was a prepared statement format, but not required.
Here is my PHP, it's giving me this error:
Notice: Undefined index: sThumbWidth in /home/demomycm/public_html/subdomains/mercury/eshop/library/classes/class.settings.php on line 204
for every field in my database.
$loadColumns = array();
$query = "SHOW COLUMNS FROM settings";
$result = $this->glob->dbConn->query($query);
if($this->glob->dbConn->errno) {
trigger_error('An error occurred whilst loading counties from the database.' . PHP_EOL . 'Query: ' . $query . PHP_EOL . 'Error[' . $this->glob->dbConn->errno . ']: ' . $this->glob->dbConn->error, E_USER_WARNING);
} elseif($result->num_rows) {
while($row = $result->fetch_assoc()) {
$loadColumns[$row['Field']];
}
return $loadColumns;
}
$loadColumnsHtml = '';
$loadColumns = $this->Settings->LoadColumns();
foreach($loadColumns as $i => $field) {
$loadColumnsHtml .= '<div class="home-stat-small-link">' . ($i + 1) . '. <strong>' . $field['Field'] . '</strong>.</div>';
}

use describe
DESCRIBE my_table;
Or in newer versions you can use INFORMATION_SCHEMA:
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'my_database' AND TABLE_NAME = 'my_table';

In your code you have $loadColumns as an array.
This line does nothing: $loadColumns[$row['Field']];
Basically your getting the value in $loadColumns with the key associated with $row['Field'] and not assigning anything.
You want something like this perhaps for that line:
array_push($loadColumns,$row['Field']);
Full code below
$loadColumns = array();
$query = "SHOW COLUMNS FROM settings";
$result = $this->glob->dbConn->query($query);
if($this->glob->dbConn->errno) {
trigger_error('An error occurred whilst loading counties from the database.' . PHP_EOL . 'Query: ' . $query . PHP_EOL . 'Error[' . $this->glob->dbConn->errno . ']: ' . $this->glob->dbConn->error, E_USER_WARNING);
} elseif($result->num_rows) {
while($row = $result->fetch_assoc()) {
array_push($loadColumns,$row['Field']); //<-- this line has been changed
}
return $loadColumns;
}
$loadColumnsHtml = '';
$loadColumns = $this->Settings->LoadColumns();
foreach($loadColumns as $i => $field) {
$loadColumnsHtml .= '<div class="home-stat-small-link">' . ($i + 1) . '. <strong>' . $field['Field'] . '</strong>.</div>';
}

On MySQL connection (deprecated) you can use:
mysql_list_fields
On PDO (recommend) use:
$query = $dbh->prepare("DESCRIBE tablename");
$query->execute();
$tableFields = $query->fetchAll(PDO::FETCH_COLUMN);
On PDO you can also use PDOStatement::getColumnMeta(). But it has the status: EXPERIMENTAL

Related

How to remove 5 characters from the end of every column in a table MySQLi

I'm trying to loop through every row in a table, and remove 5 characters from the end of one column. I have written the following code but it seems to remove 2 characters for some reason.
<?php
$connection = new mysqli('localhost', 'nawd_test', 'password', 'nawd_test');
if ($connection->connect_errno > 0) {
die ('Unable to connect to database [' . $connection->connect_error . ']');
}
$sql = "SELECT *
FROM test";
if (!$result = $connection->query($sql)) {
die ('There was an error running query[' . $connection->error . ']');
}
//Create an array to hold the values of id's already changed
$ids = [];
$newVals = [];
echo '<p>Fetching rows...</p>';
while ($row = $result->fetch_assoc()) {
//Check / Add the id
if (in_array($row['id'], $ids)) {
echo '<p style="red"><strong>Error: Script has repeated itself!</strong></p>';
break;
}
$ids[] = $row['id'];
$rowName = $row['name'];
$newName = substr($rowName, -1);
$newName = rtrim($rowName,$newName);
$newVals[] = $newName;
}
//Now loop and update
$newValID = 0;
foreach ($ids as &$id) {
echo '<p>Updating row with ID ' . $id . '</p>';
mysqli_query($connection, "UPDATE test SET name ='" . $newVals[$newValID] . "' WHERE id=" . $id);
echo '<p>Column successfully changed "<em>' . $newVals[$newValID] . '</em>"</p>';
$newValID++;
}
echo '<p style="color: green;"><strong>Script complete!</strong></p>';
?>
Dont do this in php, you can do it with a single sql query:
UPDATE test SET name = LEFT(name, LENGTH(name) - 5)
Change
$newName = substr($rowName, -1);
$newName = rtrim($rowName,$newName);
into
$newName = substr($rowName, 0, strlen($rowName) - 5);
With the way you're working, you could never predict how many characters that would have removed at the end.
Minimum 1, maximum the whole word.
Please read the documentation about rtrim and substr.
try this if you wanna doit inside the query:
update table1 set name=substr(name,-5,length(name))

Getting table doesnt exist with php and mysql

This code down here should search database. but I am getting error that my table doesnt exists. And also I want to ask why if I push second time submit button it just jumps to else so it echo choose at least.... and also all data from database. Thanks!
Here is php
if (isset($_POST['submit'])) {
$query = 'SELECT * FROM station_tab';
if (!empty($_POST['station_name']) && !empty($_POST['city']) && !empty($_POST['zone']))
{
$query .= 'WHERE station_name' .mysql_real_escape_string($_POST['station_name']) . 'AND city' . mysql_real_escape_string($_POST['city']) . 'AND zone' . mysql_real_escape_string($_POST['zone']);
} elseif (!empty($_POST['station_name'])) {
$query .= 'WHERE station_name' . mysql_real_escape_string($_POST['station_name']);
} elseif (!empty($_POST['city'])) {
$query .= 'WHERE city' . mysql_real_escape_string($_POST['city']);
} elseif (!empty($_POST['zone'])) {
$query .= 'WHERE zone' . mysql_real_escape_string($_POST['zone']);
} else {
echo "Choose at least one option for search";
}
$result = mysql_query($query, $db) or die(mysql_error($db));
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)){
echo '<br/><em>' .$row['station_name'] . '</em>';
echo '<br/>city: '. $row['city'];
echo '<br/> zone: ' .$row['zone'];
echo '<br/> Long: ' .$row['lon'];
echo '<br/> Lat: ' . $row['lat'];
}
}
}
here is error message when I add name of the city to city.
Table 'stanice_tab.station_tabwhere' doesn't exist
Here is your corrected code:
$query = 'SELECT * FROM station_tab '; // note the space at the end
if (!empty($_POST['station_name']) && !empty($_POST['city']) && !empty($_POST['zone'])) {
$query .= ' WHERE station_name = "' .mysql_real_escape_string($_POST['station_name']) . '" AND city = "' . mysql_real_escape_string($_POST['city']) . '" AND zone = "' . mysql_real_escape_string($_POST['zone']).'"'; // note the = signs and the space before each AND
} elseif (!empty($_POST['station_name'])) {
$query .= ' WHERE station_name = "' . mysql_real_escape_string($_POST['station_name']).'"'; // note the = sign and the space at the beginning
} elseif (!empty($_POST['city'])) {
$query .= ' WHERE city = "' . mysql_real_escape_string($_POST['city']).'"'; // note the = sign and the space at the beginning
} elseif (!empty($_POST['zone'])) {
$query .= ' WHERE zone = "' . mysql_real_escape_string($_POST['zone']).'"'; // note the = sign and the space at the beginning
} else {
echo "Choose at least one option for search";
}
Take the habit of echoing your $query variable so concatenation does not add any typo mistakes.
in phpmyadmin select the database and then select your table
and in menu above there is a sql menu. you can use this functionality to construct sql queries or debug when there are errors like this

HTML & PHP | Filling a select with a query

I have a function that uses mysqli function that is as follows:
public function GetProjectOptions()
{
$return = "";
$sql = "SELECT `id`, `project_name` FROM `projects`;";
$rs = static::$link->query($sql);
$return .= '<select class="form-control" name="project">';
while ($result = mysqli_fetch_assoc($rs));
{
$return .= "<option value='" . $result['id'] . "'>" .
$result['project_name'] . "</option>";
}
$return .= '</select>';
return $return;
}
The purpose of this function is to create the options and select that will be used for the Projects on my site, I know that there are 4 projects currently stored in the table, but they do not return in this function, what have I done wrong?
EDIT:
Link to screen output: (http://i.imgur.com/YIYiheH.png)
Link to code output: (http://i.imgur.com/RZsUIwQ.png)
Link to code usage: (http://i.imgur.com/4J9rvd7.png)
(Wouldn't let me do normal links)
I found the problem.
Remove the semi-colon here
while ($result = mysqli_fetch_assoc($rs));
^
that's why it's not throwing an error, because it's considered as valid syntax.
Your loop is being stopped/terminated by it.
What I think Jay and Styphon mean by their comment is that you don't do any error checking within your SELECT query. Are you sure your query is executing properly? I understand this is a relatively simple query and that you're positive there are four projects currently stored in your table, but it's always a good habit to check. Try this:
public function GetProjectOptions()
{
$return = "";
$sql = "SELECT `id`, `project_name` FROM `projects`;";
$rs = static::$link->query($sql);
$return .= '<select class="form-control" name="project">';
if($rs){
while ($result = mysqli_fetch_assoc($rs));
{
$return .= "<option value='" . $result['id'] . "'>" . $result['project_name'] . "</option>";
}
$return .= '</select>';
}else{
$message = 'Invalid query: ' . mysqli_error() . "\n";
$message .= 'Whole query: ' . $sql;
die($message);
}
return $return;
}
I hope this helps!

AJAX - JSON chained dynamic MySQL Select elements do not work with text but work fine with numerical value

I have the following code snippet that builds chained select boxes based on data pulled from MySQL.
The first select uses a DISTINCT on a column called PartTypeDescription. This code works awesome if the values in the column are numerical in nature (example: 11). You choose the first select and then the second select is populated as it should.
The problem occurs when the data is text (example: Plumbing). You choose Plumbing for example and the second select box is empty. I'm assuming the second query that builds the second select box is not working correctly. Is there something in the code below that does not allow text values?
/* Configure the select boxes */
if (isset($_GET['key'])) {
$key = $_GET['key'];
switch ($key) {
case 'callTypeSelect':
$select = new SelectBox('What vehicle are you working from?','Choose a vehicle');
$res = mysql_query('SELECT DISTINCT PartTypeDescription FROM ' . DB_TABLE2);
$callTypes = array();
for ($i = 0; list($callType) = mysql_fetch_row($res); $i++) {
$callTypes[] = $callType;
$select->addItem($callType, 'brandSelect-' . $callType);
}
header('Content-type: application/json');
echo $select->toJSON();
break;
default:
if (strpos($key, 'brandSelect-') === 0) {
$callType = str_replace('brandSelect-', '', $key);
$resBrands = mysql_query('SELECT Invm_InventoryNumber FROM ' . DB_TABLE2
. ' WHERE PartTypeDescription = ' . mysql_real_escape_string($callType) . " ORDER BY Invm_InventoryNumber");
$select = new SelectBox('What part number are you looking for?', 'Pick a part');
for ($i = 0; list($brand) = mysql_fetch_row($resBrands); $i++) {
$select->addItem($brand, 'result-' . $brand . '-' . $callType);
}
header('Content-type: application/json');
echo $select->toJSON();
} elseif (strpos($key, 'result-') === 0) {
list($null, $brand, $callType) = explode('-', $key);
$res = mysql_query('SELECT * FROM ' . DB_TABLE2
. ' WHERE PartTypeDescription = \'' . mysql_real_escape_string($callType) . '\'
AND Invm_InventoryNumber = \'' . mysql_real_escape_string($brand) . "'");
$markup = '';
for ($i = 0; $row = mysql_fetch_assoc($res); $i++) {
//$row = array_map('htmlspecialchars', $row); it looks like the items is already encoded
$markup .= <<<HTML
You can't escape characters inside of single quotes. For example:
$x = 'I don\'t like tomatoes';
That won't escape the quote like you think it would and will cause problems. In your code with this line:
$res = mysql_query('SELECT * FROM ' . DB_TABLE2
. ' WHERE PartTypeDescription = \'' . mysql_real_escape_string($callType) . '\'
AND Invm_InventoryNumber = \'' . mysql_real_escape_string($brand) . "'");
You need to wrap strings with escape sequences with double quotes.
$res = mysql_query('SELECT * FROM ' . DB_TABLE2
. " WHERE PartTypeDescription = \'" . mysql_real_escape_string($callType) . "\'
AND Invm_InventoryNumber = \'" . mysql_real_escape_string($brand) . "'");

Adding a resultset to an existing result set

I am trying to solve a problem where I need to execute a query on the database within a do while loop and keep on adding to the resultset. However once its finished running all the queries and I then start processing the result set php gives the error
Warning: mysql_fetch_array() expects parameter 1 to be resource,
string given in
The idea is it executes a query with a limit of 0,2 then executes again with a limit of 2,2 and so on until the numbers of rows returned is empty. I know the best solution would be to do a count and work out from there but this is not an option as the database is too large.
Below is the code that I currently have
$tempResult = "";
$i = 0;
$result = null;
do
{
if (is_resource($tempResult))
{
echo 'Cleared Result <br />';
mysql_free_result($tempResult);
}
echo 'Count: ' . $i . '<br />';
$query = "select * from table_test LIMIT $i, 2";
$tempResult = mysql_query($query) or die ("MySQL Error: " . mysql_error());
echo 'Temp Result: ' . $tempResult .' <br />';
$i = $i + 2;
$result .= $tempResult;
} while (mysql_num_rows($tempResult) > 0);
while ($myrow = mysql_fetch_array($result))
{
echo $myrow['col1'] . ' + ' . $myrow['col2'] .
' + ' . $myrow['col3'] . ' <br />';
}
Thanks for any help you can provide.
Why dont you use a result array? For example something like this:
$tempResult = "";
$i = 0;
$resultArray = array();
$result = null;
do
{
if (is_resource($tempResult))
{
echo 'Cleared Result <br />';
mysql_free_result($tempResult);
}
echo 'Count: ' . $i . '<br />';
$query = "select * from table_test LIMIT $i, 2";
$tempResult = mysql_query($query) or die ("MySQL Error: " . mysql_error());
$resultArray = merge($resultArray, mysql_fetch_array($tempResult));
echo 'Temp Result: ' . $tempResult .' <br />';
$i = $i + 2;
} while (mysql_num_rows($tempResult) > 0);
while ($resultArray as $myRow)
{
echo $myrow['col1'] . ' + ' . $myrow['col2'] .
' + ' . $myrow['col3'] . ' <br />';
}
Well, from such an unusual question we can only guess the right answer.
My bet:
Your goal is to do some calculations on the data stored in the table.
And you are going to do it in the PHP script instead of the proper way of calculating using database facilities.
So, it's better you would do all the calculations in one query.
Anyway,
It is always a good practice to ask a core question, a root problem, instead of a question related to some unusual way you choose to solve it.
Once you ask this one, you will get complete and professional answer.
Why not just print the results in the first loop?
$i = 0;
do
{
$query = "SELECT * FROM table_test LIMIT $i, 2";
$result = mysql_query($query) or die("MySQL Error: " . mysql_error());
while ($myrow = mysql_fetch_array($result))
{
echo $myrow['col1'] . ' + ' . $myrow['col2'] . ' + ' . $myrow['col3'] . ' <br />';
}
$i = $i + mysql_affected_rows();
} while (mysql_affected_rows() > 1);
echo 'Count: ' . $i . '<br />';
But really, this method just seems like a way to add additional overhead to fetching rows from the database.

Categories