I'm trying to populate a dropdown list in my web page from a mysql database table which has only one column (pathology_id). I know there is test data in there but the best I can do is populate the box with the field name, not the row values. The code I have thus far is below, can anyone suggest how to get more than just the column name? Thanks in advance.
<?php $con = mysql_connect("localhost","dname","dbpass");
if(!$con)
{
die('Could not connect: ' . mysql_error());
}
$fields = mysql_list_fields("dbname","PATHOLOGY",$con);
$columns = mysql_num_fields($fields);
echo "<form action = newcase.php method = POST><select name = Field>";
for($i = 0; $i < $columns ; $i++)
{
echo "<option value = $i>";
echo mysql_field_name($columns , $i);
}
echo "</select></form>";
if(!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
else
{
echo "1 record added";
}
mysql_close($con) ?>
Try this:
<?php
// This could be supplied by a user, for example
$firstname = 'fred';
$lastname = 'fox';
// Formulate Query
// This is the best way to perform an SQL query
// For more examples, see mysql_real_escape_string()
$query = sprintf("SELECT firstname, lastname, address, age FROM friends WHERE firstname='%s' AND lastname='%s'",
mysql_real_escape_string($firstname),
mysql_real_escape_string($lastname));
// Perform Query
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_assoc($result)) {
echo $row['firstname'];
echo $row['lastname'];
echo $row['address'];
echo $row['age'];
}
// Free the resources associated with the result set
// This is done automatically at the end of the script
mysql_free_result($result);
?>
From PHP: mysql_query().
mysql_list_fields just returns information about a given table, NOT the data contained.
Select option should has close tag.
echo '<form action="newcase.php" method="POST"><select name"="Field">';
for($i = 0; $i < $columns ; $i++)
{
echo '<option value="' . $i . '">';
echo mysql_field_name($columns , $i);
echo '</option>';
}
echo '</select></form>';
Related
Recently I've bought webhosting at names.co.uk and I'm trying to set up something simple which will display the name from a table named Team if the id = 1.
This is my code
<?php
$q = "SELECT * FROM `Team` WHERE id =1";
$result = mysql_query($q);
echo '<br />Query is send';
echo '<br />Result is true';
$row = mysql_fetch_array($result);
echo '<br />tryed fetching row';
if ($row === FALSE) {
echo '<br />$row is not false.';
$name = $row['name'];
echo '<br />$name now is "' . $name . '"';
}
else {
echo( mysql_error());
}
echo $name;
?>
This is the output:
Query is send Result is true tryed fetching rowNo such file or
directory
UPDATE:
I have changed to msqli:
$q = "SELECT * FROM `Team` WHERE id =1";
$result = mysqli_query($q);
echo '<br />Query is send';
echo '<br />Result is true';
$row = mysqli_fetch_array($result);
echo '<br />tryed fetching row';
if ($row !== FALSE) {
echo '<br />$row is not false.';
$name = $row['name'];
echo '<br />$name now is "' . $name . '"';
}
else {
echo( mysqli_error());
}
echo $name;
and now I'm getting this output:
Query is send Result is true tryed fetching row $row is not false.
$name now is ""
You need to fist establish a connection. For example: $connection = mysqli_connect($servername, $username, $password);.
See this link on how to use MySQLi: https://www.w3schools.com/PHP/php_mysql_connect.asp (but note that w3schools is a bad resource, with outdated information and bad practices - I'm only linking to it because this tutorial is basic and clear).
Be sure to check later, if you still haven't, on how to properly sanitize your queries. See this, for example: How can I prevent SQL injection in PHP?
Use function:
$result = mysqli_query($q);
mysql_query() have been deprecated in PHP7 onwards.
The code below works fine for printing one record from a database table, but what I really want to be able to do is print all the records in the mysql table in a format similar to my code.
I.E.: Field Name as heading for each column in the html table and the entry below the heading. Hope this is making sense to someone ;)
$raw = mysql_query("SELECT * FROM tbl_gas_meters");
$allresults = mysql_fetch_array($raw);
$field = mysql_query("SELECT * FROM tbl_gas_meters");
$num_fields = mysql_num_fields($raw);
$num_rows = mysql_num_rows($raw);
$i = 1;
print "<table border=1>\n";
while ($i < $num_fields)
{
echo "<tr>";
echo "<b><td>" . mysql_field_name($field, $i) . "</td></b>";
//echo ": ";
echo '<td><font color ="red">' . $allresults[$i] . '</font></td>';
$i++;
echo "</tr>";
//echo "<br>";
}
print "</table>";
Just as an additional piece of information you should probably be using PDO. It has more features and is helpful in learning how to prepare SQL statements. It will also serve you much better if you ever write more complicated code.
http://www.php.net/manual/en/intro.pdo.php
This example uses objects rather then arrays. Doesn't necessarily matter, but it uses less characters so I like it. Difference do present themselves when you get deeper into objects, but not in this example.
//connection information
$user = "your_mysql_user";
$pass = "your_mysql_user_pass";
$dbh = new PDO('mysql:host=your_hostname;dbname=your_db;charset=UTF-8', $user, $pass);
//prepare statement to query table
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
//loop over all table rows and fetch them as an object
while($result = $sth->fetch(PDO::FETCH_OBJ))
{
//print out the fruits name in this case.
print $result->name;
print("\n");
print $result->colour;
print("\n");
}
You probably also want to look into prepared statements. This helps against injection. Injection is bad for security reasons. Here is the page for that.
http://www.php.net/manual/en/pdostatement.bindparam.php
You probably should look into sanitizing your user input as well. Just a heads up and unrelated to your current situation.
Also to get all the field names with PDO try this
$q = $dbh->prepare("DESCRIBE tablename");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);
Once you have all the table fields it would be pretty easy using <div> or even a <table> to arrange them as you like using a <th>
Happy learning PHP. It is fun.
Thanks guys, got it.
$table = 'tbl_gas_meters';
$result = MYSQL_QUERY("SELECT * FROM {$table}");
$fields_num = MYSQL_NUM_FIELDS($result);
ECHO "<h1>Table: {$table}</h1>";
ECHO "<table border='1'><tr>";
// printing table headers
FOR($i=0; $i<$fields_num; $i++)
{
$field = MYSQL_FETCH_FIELD($result);
ECHO "<td>{$field->name}</td>";
}
ECHO "</tr>\n";
// printing table rows
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";
}
while ( $row = mysql_fetch_array($field) ) {
echo $row['fieldname'];
//stuff
}
Try this :
$raw = mysql_query("SELECT * FROM tbl_gas_meters");
$allresults = mysql_fetch_array($raw);
$field = mysql_query("SELECT * FROM tbl_gas_meters");
while($row = mysql_fetch_assoc($field)){
echo $row['your field name here'];
}
Please note that, mysql_* functions are deprecated in new php version , so use mysqli or PDO instead.
Thanks! I adapted some of these answers to draw a table from all records from any table, without having to specify the field names. Just paste this into a .php file and change the connection info:
<?php
// Authentication detail for connection
$servername = "localhost";
$username = "xxxxxxxxxx";
$password = "xxxxxxxxxx";
$dbname = "xxxxxxxxxx";
$tablename = "xxxxxxxxxx";
$orderby = "1 DESC LIMIT 500"; // column # to sort & max # of records to display
// Create & check connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error); // quit
}
// Run query & verify success
$sql = "SELECT * FROM {$tablename} ORDER BY {$orderby}";
if ($result = $conn->query($sql)) {
$conn->close(); // Close table
$fields_num = $result->field_count;
$count_rows = $result->num_rows;
if ($count_rows == 0) {
die ("No data found in table: [" . $tablename . "]" ); //quit
}
} else {
$conn->close(); // Close table
die ("Error running SQL:<br>" . $sql ); //quit
}
// Start drawing table
echo "<!DOCTYPE html><html><head><title>{$tablename}</title>";
echo "<style> table, th, td { border: 1px solid black; border-collapse: collapse; }</style></head>";
echo "<body><span style='font-size:18px'>Table: <strong>{$tablename}</strong></span><br>";
echo "<span style='font-size:10px'>({$count_rows} records, {$fields_num} fields)</span><br>";
echo "<br><span style='font-size:10px'><table><tr>";
// Print table Field Names
while ($finfo = $result->fetch_field()) {
echo "<td><center><strong>{$finfo->name}</strong></center></td>";
}
echo "</tr>"; // Finished Field Names
/* Loop through records in object array */
while ($row = $result->fetch_row()) {
echo "<tr>"; // start data row
for( $i = 0; $i<$fields_num; $i++ ) {
echo "<td>{$row[$i]}</td>";
}
echo "</tr>"; // end data row
}
echo "</table>"; // End table
$result->close(); // Free result set
?>
I am trying to use AES_DECRYPT in MySQL to decrypt a successfully encrypted SSN. In the output I get the word "Array" instead of the actual data from that field. My PHP and MySQL knowledge is a bit rusty, so I'm sure it's something silly I overlooked. Any help would be appreciated.
OUTPUT:
verify_name other_names ssn dob
: test : test : Array : test
CODE:
$key="88b871WZ3SntWK67rN3l2J1SvMqsOjyk";
$SQLstring = "SELECT * FROM applications";
$QueryResult = #mysql_query($SQLstring, $conn) or die("Query Problem - "
. mysql_error($conn) . " - Error Number - "
. mysql_errno($conn));
echo "verify_name other_names ssn dob";
$num_result = mysql_num_rows($QueryResult);
for ($i = 0; $i < $num_result; $i++)
{
$row = mysql_fetch_array($QueryResult);
$SQLstring2 = "SELECT AES_DECRYPT(ssn,'$key') FROM applications WHERE name='" . $row["name"] . "'";
$QueryResult2 = #mysql_query($SQLstring2, $conn) or die("Query Problem - "
. mysql_error($conn) . " - Error Number - "
. mysql_errno($conn));
$num_result2 = mysql_num_rows($QueryResult2);
for ($j = 0; $j < $num_result; $j++){
$ssndecrypt = mysql_fetch_array($QueryResult2);
echo $ssndecrypt[0];
}
echo $row["verify_name"];
echo $row["other_names"];
echo $ssndecrypt;
echo $row["dob"];
It's because you're fetching the result as an array.
$ssndecrypt = mysql_fetch_array($QueryResult2);
...
echo $ssndecrypt;
It's echoing Array because you never reassign the $ssndecrypt variable.
The core of the problem, however, seems to be that you're needlessly complicating your queries. There's no reason to query the table twice when you can just do:
SELECT verify_name,
other_names,
dob,
AES_DECRYPT(ssn,'$key') AS ssn
FROM applications
This simplifies the code quite a bit:
$stmt = "SELECT verify_name, other_names, dob, AES_DECRYPT(ssn,'$key') AS ssn FROM applications";
$result = #mysql_query($stmt, $conn) or die("Query Problem - " . mysql_error($conn) . " - Error Number - " . mysql_errno($conn));
echo "verify_name other_names ssn dob";
while ($row = mysql_fetch_assoc($result))
{
echo $row["verify_name"];
echo $row["other_names"];
echo $row["ssn"];
echo $row["dob"];
}
Ideally, though, you should be using PDO instead of the mysql_* functions:
try {
$dbh = new PDO('mysql:host=localhost;dbname=mydb', $user, $pass);
foreach($dbh->query("SELECT verify_name, other_names, dob, AES_DECRYPT(ssn,'$key') AS ssn FROM applications") as $row) {
echo $row["verify_name"];
echo $row["other_names"];
echo $row["ssn"];
echo $row["dob"];
}
$dbh = null;
} catch (PDOException $e) { die("ERROR: " . $e->getMessage()); }
I need help displaying data from mysql to a webpage, I am coding in php.
My database consists of products which are cars(same type e.g Chevy), right now I have 2 rows (I can add more if I want to), each cars contains the image path, and description.
I can show one row (car) but I am unable to show all rows. I know I have to go through a loop to get all the data from the cars database but I am not sure how to implement it.
This is what I have so far. Assuming I already connected to my database
note: the image path I would like to show the picture in my website.
This is how i would like it to display in my webpage:
$query = "SELECT * FROM cars where cars.carType = 'Chevy' AND \
cars.active = 1";
$numberOfFieds = mysqli_num_fields($result);
$numberOfRows = mysqli_num_rows($result);
/* Gets the contents */
$row = mysqli_fetch_row($result);
$rows = mysqli_fetch_assoc($result);
$fieldcarssontable = array_keys($row);
echo "<table>";
while($row = mysqli_fetch_assoc($result)){
echo "<th>" . $fieldcarssontable[imgPath] . "</th>";
echo "<th>" . $fieldcarssontable[description] . "</th>";
}
echo "</tr>";
echo "</table>";
Just add a while loop. mysqli_fetch_assoc returns a row and moves the internal pointer to the next row until all rows are fetched, then it returns false and the while loop will stop
Pseudo syntax to understand while
while ( this is true ) {
execute this
}
So on your case you can say
while ( $row = mysqli_fetch_assoc( $result ) ) {
// process/output $row
}
mysqli_fetch_assoc and mysqli_fetch_row literally do the same, assoc gives you the array with your result field names as index so this is simpler to access ( $row['name'] rather than $row[0] when using fetch_row )
Have fun! :)
EDIT
// connect to your database server
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
// an error occured
if (!$link) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
// build your query
$query = "SELECT
* # select actual fields instead of *
FROM
cars
WHERE
cars.carType = 'Chevy'
AND
cars.active = 1";
// execute query
$result = mysqli_query($link, $query );
if ( !$result ) {
die( 'no result' );
}
// number of fields
$numberOfFields = mysqli_num_fields($result);
// the field names
$fieldNames = mysqli_fetch_fields($result);
// number of result rows
$numberOfRows = mysqli_num_rows($result);
// watch the content of fieldName and compare it with the table header in the output
print_r( $fieldName );
echo "<table>\n";
// table header, not neccessary to put this into a loop if the query isn't dynamic
// so you actually know your field names - you can echo the header without any variable.
// for the sake of learning about loops I added this
foreach( $fieldNames as $index => $fieldName ) {
echo "\t<th>field #" $index . ", name:" . $fieldName . "</th>\n";
}
// now it's time to walk through your result rows, since we only need to check for "true" a while loop does best
while ( $row = mysqli_fetch_assoc( $result ) ) {
echo "\t<tr><td>" . $row['imgPath'] . "</td><td>" . $row['description'] . "</td></tr>\n";
}
echo "</table>\n";
// remove the result from memory
mysqli_free_result( $result );
mysqli_close( $link );
You misspelled $numberOfFields in your loop, which means you're using a different variable for your loop control. Your loop won't work.
I recommend turning on the error reporting so PHP can catch this stuff for you.
Use this... just while loop
<?php
// Array
while($result = mysql_fetch_assoc($result)) {
//show you fields
echo $result["FieldName"];
}
?>
Or use this proper
<?php
// Edit it as per your query
$query = "SELECT * FROM cars";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while($row = $result->fetch_assoc()) {
//show you fields
echo $row["Name"];
}
/* free result set */
$result->free();
}
/* close connection */
$mysqli->close();
?>
I'm trying to display all my database fields like radio buttons. For example I have this database fields :
hostess_id
hostess_name_en
hostess_surname_en
... etc ...
I want to display them as radio buttons, in order to select them, then display data information only for the selected buttons.
How can I do that?
I have something like this:
<?php
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Could not connect to MySQL server: ' . mysql_error());
}
$dbname = 'db_up';
$db_selected = mysql_select_db($dbname, $link);
if (!$db_selected) {
die("Could not set $dbname: " . mysql_error());
}
$res = mysql_query('select * from hostess', $link);
while ($row = mysql_fetch_assoc($result)){
echo "<td><input type=\'checkbox\' name=\'hostess[]\' value=\'" . $row['hostess_id'] . "\'>" . $row['hostess_firstname_en'] . "<br />";
}
?>
With PDO, It will get all fields
$q = $dbh->prepare("DESCRIBE tablename");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);
With deprecated mysql_*
function mysql_field_array( $query ) {
$field = mysql_num_fields( $query );
for ( $i = 0; $i < $field; $i++ ) {
$names[] = mysql_field_name( $query, $i );
}
return $names;
}
// Example of use
$fields = mysql_field_array( $query );
Than you can loop through that array of field names and use the name with your check box.
Checkboxes need a unique name or they need to be an array. A checkbox array would be appropriate for what you're doing:
while ($row = mysql_fetch_assoc($result)){
echo "<input type='checkbox' name='hostess[]' value='" . $row['id'] . "' />" . htmlentities($row['hostess_surname_en']) . "<br />";
}
This will give you a list of checkboxes with the hostess surname next to each.
Now, when this form is submitted to a PHP script, you will be able to access the selected row id's with:
$selectedIds = $_POST['hostess']; // an array
$selectedIds is an array of the checked record ids.
I suggest using PDO or MySQLi for new code because the mysql_* library is deprecated.