Create table dynamically from mysql query - php

I'm trying to create a page where I input a MYSQL query: SELECT column1,column2 FROM table;, and dynamically create an HTML table with column titles.
EDIT: removed most of my question, just left the question part. I have since created a script that does this and included it as an answer. I hope someone else makes use of it like I do (when I'm too lazy to log into phpmyadmin ... hahaha).

I would try mysql_fetch_assoc which gives back an associative array (map). Then you can use array_keys to get the column names.

This sounds like it might be related to testing where you sometimes just need to spit out the results to see them on a screen , so I'm going to put this here...
The php class dbug is an awesome tool for quickly getting a nicely formatted table out of a php array or even a MySQL result:
http://dbug.ospinto.com/

Well. Here's how I accomplished this, building on webjprgm's tip to use mysql_fetch_assoc:
php code to dynamically create a table with column titles, from PHP to mysql to html! :)
<head>
<title>mysql Table maker</title>
</head>
<body>
<center>
<?php
/* posted data sent to this page (from this page)*/
$pdatabase = htmlentities($_POST['database'], ENT_QUOTES); // database
$phost = htmlentities($_POST['host'], ENT_QUOTES); // host
$puser = htmlentities($_POST['user'], ENT_QUOTES); // user
$ppassword = htmlentities($_POST['password'], ENT_QUOTES); // password
$pcolumns = htmlentities($_POST['columns'], ENT_QUOTES); // comma seperated columns
$columns = explode(",",$pcolumns); // array of column names
$ptable = htmlentities($_POST['table'], ENT_QUOTES); // table
$pwhere = str_replace(array(";",'"'),array('',''),$_POST['where']); // WHERE clause
if (!empty($pwhere)) {$pwhere = "WHERE $pwhere";} // if not empty, prepend with "WHERE"
$porder = htmlentities($_POST['order'], ENT_QUOTES); // ORDER BY clause
$psort = htmlentities($_POST['sort'], ENT_QUOTES); // SORTING (asc or desc)
if (!empty($porder)) {$porder = "ORDER BY $porder $psort";} // if order is not empty, prepend with "ORDER BY"
$pgroup = htmlentities($_POST['group'], ENT_QUOTES); // GROUP BY clause
if (!empty($pgroup)) {$pgroup = "GROUP BY $pgroup";} // if not empty, prepend with "GROUP BY"
$plimit = htmlentities($_POST['limit'], ENT_QUOTES); // LIMIT clause
if (!empty($plimit)) {$plimit = "LIMIT $plimit";}
/* The finished product....or query...so to speak...if you will */
$query = "SELECT $pcolumns FROM $ptable $pwhere $pgroup $porder $plimit";
/* Safety precautions */
$query = str_replace(array("delete","drop","update","alter"),array('','','',''),$query);
// print_r($columns);
?>
<form action="mysql-table.php" method="POST">
<span style="position:fixed;top:0;left:0;width:100%;height:30px;background:#35AFE3">
host: <input name="host" type="text" value="<?php echo $phost;?>"/>
user: <input name="user" type="text" value="<?php echo $puser;?>"/>
password: <input name="password" type="password" value="<?php echo $ppassword;?>"/>
database: <input name="database" type="text" value="<?php echo $pdatabase;?>"/>
</span>
<hr/>
<span style="position:fixed;top:30px;left:0;width:100%;height:205px;background:#35FC39;">
SELECT
<input name="columns" type="text" value="<?php echo $pcolumns;?>"/><br/>
FROM
<input name="table" type="text" value="<?php echo $ptable; ?>"/><br/>
WHERE
<input name="where" type="text" value="<?php echo trim(str_replace("WHERE","",$pwhere)); ?>"/><br/>
ORDER BY
<input name="order" type="text" value="<?php echo trim(str_replace("ORDER BY","",$porder)); ?>"/><br/>
SORT
<select name="sort">
<option value=""></option>
<option value="ASC">ASC</option>
<option value="DESC">DESC</option>
</select><br/>
GROUP BY
<input name="group" type="text" value="<?php echo trim(str_replace("GROUP BY","",$pgroup)); ?>"/><br/>
LIMIT
<input name="limit" type="text" value="100"/><br/>
GO:
<input type="submit" value="submit" />
</span>
</form>
<span style="position:absolute;top:235px;left:0;width:100%;height:auto;background:#28c7d6;z-index:-1;">
<?php
if (!empty($_POST['columns']) && !empty($_POST['table'])) {
echo "<h3><b>Query:</b> <i>$query</i></h3><hr/>";
$mysqli = new mysqli($phost,$puser,$ppassword,$pdatabase); // Connect to DB
/* check connection */ // check for connection error
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($result = $mysqli->query($query)) {
echo "<table border='1' style='word-wrap:break-word'>"; // New table
/* Column Title */
echo "<tr>"; // New Row for the titles
foreach($columns as $c) { // For each column, create a column
echo "<td><b>$c</b></td>\r\n";
}
echo "</tr>"; // Close the titles' row
/* DATA RESULTS */
while ($row = $result->fetch_assoc()) { // for each set of rows:
echo "<tr>\r\n\r\n"; // create new row
foreach($columns as $c) { // for each column in the row:
// create a cell
echo "
<td style='max-width:400px;'>
<div style='max-height:300px;overflow-y:auto;'>
$row[$c]
</div>
</td>";
}
echo "</tr>"; // end of that row
} // end foreach results
echo "</table>"; // closing of the table
/* free result set */
$result->free();
} else {
echo "query failed.<hr/>";
}
/* close connection */
$mysqli->close();
} elseif (isset($_POST['columns']) || isset($_POST['table'])) { // end of !empty columns,table
echo "<b>MISSING IMPORTANT INFORMATION.<br/>
For column, you entered: <u> ".$_POST['columns']." </u><br/>
For table you entered: <u> ".$_POST['table']." </u>";
}
?>
</span>
</center>
</body>

Related

Create Autofill form with PHP

So im still relatively new to php and im trying to create a form that autofill's with information from a table. The table is called students and has the students id, first and last name, and their address. Im trying to make it so it only autofill's with the information of the student with a certain id, for example if the students id is 102 it fills the textboxes with their info.
I have some code which i thought would work but its telling me somethings wrong with the while loop and i don't know what.
Edit: The error i keep getting is this:"mysqli_fetch_assoc() expects parameter 1 to be mysqli_result".
PHP code:
<?php
require_once ('Connection.php');
$query = "SELECT * from students where Id = 102";
$result = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_assoc($result)) {
$row['student_id'];
$row['stu_Fname'];
$row['stu_Lname'];
$row['stu_addr'];
}
?>
Html Form:
<form action="http://localhost/test.php" method="post">
<p>Student ID:
<input name="stu_id" size="5" value="<?php echo $row['student_id']; ?>" pattern="^\d{3}" required autofocus /><?php echo $row['student_id']; ?>
</p>
<p>First Name:
<input type="text" name="fname" size="30" value="<?php echo $row['stu_Fname']; ?>"/>
</p>
<p>Last Name:
<input type="text" name="lname" size="30" value="<?php echo $row['stu_Lname']; ?>"/>
</p>
<p>Address:
<input type="text" name="address" size="30" value="<?php echo $row['stu_addr']; ?>"/>
</p>
<p>
<input type="submit" name="submit" value="Send"/>
</p>
</form>
EDIT: Connection code:
<?php
DEFINE ('DB_User', 'testuser');
DEFINE ('DB_Password', 'abc123*');
DEFINE ('DB_Host', 'localhost');
DEFINE ('DB_Name', 'student');
//start database connection
$dbc = new mysqli(DB_Host, DB_User,DB_Password,DB_Name);
if(mysqli_connect_errno())
{
printf("can't connect to database.", mysqli_connect_error());
exit();
}
?>
while ($row = mysqli_fetch_assoc($result)) {
$row['student_id'];
$row['stu_Fname'];
$row['stu_Lname'];
$row['stu_addr'];
}
You're not actually accomplishing anything within the while loop above. There is no assignment, nor output.
Each iteration of the while loop will grab a row (if there is one in the database). Assuming that the row has the four columns you've listed, you can print the data to the screen. For example:
while ($row = mysqli_fetch_assoc($result)) {
echo $row['student_id'] . ", ";
echo $row['stu_Fname'] . ", ";
echo $row['stu_Lname'] . ", ";
echo $row['stu_addr'];
}
Assuming you're outputting a form for each student, you can place the form logic within the while loop.

How to add a full name on psql database using html select method and php?

My goal is to get the names on one of my tables on my psql database and add them to other table using the HTML form select method. I am able to get the names but unfortunately It´s adding only the first names. And I also want to add the number of each name but for all the names it´s only add the number of the last name.
Any help?
my code
<select style="width: 300px" type=text name=diurno value="<?php echo $nome; ?>"><br>
<?php
$sql = "select * from professore1 where coordenacao='$coordenacao' order by coordenacao;";
$res = pg_query ($con, $sql);
for ($i= 0; $i < pg_numrows($res);$i++) {
$nome = pg_fetch_result ($res, $i, "nome");
$numero = pg_fetch_result ($res, $i, "numero");
echo "<option value = $nome>$nome";
}
?>
<input type="hidden" value="<?php echo $numero;?>" name="numero" required>
<input type="hidden" value="<?php echo $numero;?>" name="numero" required>
my table

How to loop through results of a mysql query and display them in option values in an html form

How can I loop through results of a MySQL query and display them in option values in the html form in my script.
I have tried putting the values manually into the option tags and values, but I want to do it depending on whats already inside the database. Do I need another connection to the database to run in the same part as the form element itself?
<title>Add a unit</title>
</head>
<body>
<div class= "container">
<h1>Add a unit</h1>
<?php // Script 12.4 - add_size.php
// This script adds a blog size to the database.
if ($_SERVER['REQUEST_METHOD'] == 'POST') { // Handle the form.
// Connect and select:
$connection = mysqli_connect('localhost', $user, $password, $database);
mysqli_set_charset($connection, 'utf8');
// Validate the form data:
$problem = false;
if (!empty($_POST['unit']) && !empty($_POST['size']) && !empty($_POST['price'] && isset($_POST['building'])) {
$unit = mysqli_real_escape_string($connection, trim(strip_tags($_POST['unit'])));
$size = mysqli_real_escape_string($connection, trim(strip_tags($_POST['size'])));
$price = mysqli_real_escape_string($connection, trim(strip_tags($_POST['price'])));
$building = mysqli_real_escape_string($connection, trim(strip_tags($_POST['building'])));
} else {
echo '<p style="color: red;">Please submit a unit and an size and price.</p>';
}
if (!$problem) {
// Define the query:
$query = "INSERT INTO individualspecs (Space, Size, Price, fk_Id, Id) VALUES ('${unit}', '${size}', '${price}', '${building}', 0)";
// Execute the query:
if (#mysqli_query($connection, $query)) {
echo '<p>The unit has been added!</p>';
// why doesnt print "$msg"; work when using $i
} else {
echo '<p style="color: red;">Could not add the unit because:<br>'.mysqli_error($connection).'.</p><p>The query being run was: '.$query.'</p>';
echo $msg;
}
mysqli_close($connection); // Close the connection.
} // No problem!
} // End of form submission IF.
// Display the form:
?>
<form action="add_units.php" method="post" enctype="multipart/form-data">
<p>Select Building: <select name="building">
<option value="<?php echo ?>"><?php echo ?></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
</select>
</p>
<p>Enter Unit: <input type="text" name="unit" size="40" maxsize="100"></p>
<p>Enter Size in Sq Feet: <input type="number" name="size" size="40" maxsize="100"></p>
<p>Enter Price: <input type="text" name="price" size="40" maxsize="100"></p>
<!-- removed upload photos -->
<input type="submit" name="submit" value="Add indiviual Space!">
</form>
</div>
</body>
</html>
I would like the select dropdown menu to show a list of all buildings currently in the database so that the user can select a building to add his unit to.
If no buildings exist in database handle situation i.e. echo 'No buildings found in database, you need to
add a building record before attempting to add individual units';
Here is my buildings table:
https://imgur.com/a/2KMOUBD
Here is my units table:
https://imgur.com/a/w24IFuy
Here's a simple code to do what you need
Your code is so messed up, try to clean it :-)
We connect to mysql DB Using PDO class because it's more powerful and secure
you can change root with your db username
pass with your db password
db with your db name
read more about PDO here
// connect to db
$dbh = new \PDO('mysql:host=127.0.0.1;dbname=db', "root", "pass");
// query to select from db
$q = 'SELECT * FROM users';
// prepare and execute the query
$buildsq = $dbh->prepare($q);
$buildsq->execute();
// fetch the results and save them to $build var
$builds = $buildsq->fetchAll();
// check if their is results and print them
if($buildsq->rowCount()) {
foreach ($builds as $build) {
echo '<option value="">' . $build['name'] . '</option>';
}
} else {
echo "<option>No results </option>";
}
It's not the best, but it does what you need.
Try to put connection part in a function to clean up your code.

I only want to update one MySQL row with PHP

I am working on a page that I need to be able to update single records from my MySQL database using PHP. Can someone please help me? When I try to update one record all my other records are updated.
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p><strong>ID:</strong> <?php echo $id; ?></p>
<strong>Name: *</strong> <input class="form-control" type="text" name="name" value="<?php echo $name; ?>" /><br/>
<strong>Month: *</strong> <input class="form-control" type="text" name="month" value="<?php echo $month; ?>" /><br/>
<strong>event1: *</strong> <input class="form-control" type="text" name="event1" value="<?php echo $event1; ?>" /><br/>
<strong>event2: </strong> <input class="form-control" type="text" name="event2" value="<?php echo $event2; ?>" /><br/>
<strong>event3: </strong> <input class="form-control" type="text" name="event3" value="<?php echo $event3; ?>" /><br/>
<strong>event4: </strong> <input class="form-control" type="text" name="event4" value="<?php echo $event4; ?>" /><br/>
<strong>timesub: </strong> <input class="form-control" type="text" name="timesub" value="<?php echo $timesub; ?>" readonly /><br/>
<p>* Required</p>
<input type="submit" name="submit" value="Submit" class="btn btn-info">
<input type=reset name="reset" value="Reset" class="btn btn-danger">
</div>
</form>
That is my form, and then I follow it with this code:
<?php
}
include('db_connect.php');
if (isset($_POST['submit'])) {
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['id'])) {
$id = $_POST['id'];
$name = mysql_real_escape_string(htmlspecialchars($_POST['name']));
$month = mysql_real_escape_string(htmlspecialchars($_POST['month']));
$event1 = mysql_real_escape_string(htmlspecialchars($_POST['event1']));
$event2 = mysql_real_escape_string(htmlspecialchars($_POST['event2']));
$event3 = mysql_real_escape_string(htmlspecialchars($_POST['event3']));
$event4 = mysql_real_escape_string(htmlspecialchars($_POST['event4']));
$timesub = mysql_real_escape_string(htmlspecialchars($_POST['timesub']));
// check thatfields are filled in
if ($name == '' || $month == '' || $event1 == '' || $timesub == ''){
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($id, $name, $month, $event1, $event2, $event3, $event4, $timesub, $error);
} else {
// save the data to the database
mysql_query("UPDATE announcement SET name='$name', month='$month', event1='$event1', event2='$event2', event3='$event3', event4='$event4', timesub='$timesub'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: view.php");
}
} else {
// if the 'id' isn't valid, display an error
echo 'Error!';
}
} else
// if the form hasn't been submitted, get the data from the db and display the form
{// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0) {
// query db
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM announcement WHERE id=$id")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row) {
// get data from db
$name = $row['name'];
$month = $row['month'];
$event1 = $row['event1'];
$event2 = $row['event2'];
$event3 = $row['event3'];
$event4 = $row['event4'];
$timesub = $row['timesub'];
// show form
renderForm($id, $name, $month, $event1, $event2, $event3, $event4, $timesub, '');
} else {// if no match, display result
echo "No results!";
}
} else {// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
echo 'Error!';
}
}
?>
I got the code from: http://www.killersites.com/community/index.php?/topic/1969-basic-php-system-vieweditdeleteadd-records/
Great article!
Thanks in advance for the help.
First of all stop using mysql_* its deprecated and closed in PHP 7. You can use mysqli_* or PDO.
Whats wrong with your query:
This is very important, if you not use WHERE CLAUSE in your UPDATE STATEMENT than it will update the all rows.
You must need to add WHERE CLAUSE in your query at end, something like:
WHERE id = '$id'
Also note that, your code is open for SQL INJECTION, you must need to prevent with SQL INJECTION, you can learn about the prepared statement. This post will help you to understand: How can I prevent SQL injection in PHP?
*If you want to know How mysqli_* works, this document will help you: http://php.net/manual/en/book.mysqli.php
If you want to work on PDO, you can follow this manual: http://php.net/manual/en/book.pdo.php
Take a close look at your query:
mysql_query("UPDATE announcement SET name='$name', month='$month', event1='$event1', event2='$event2', event3='$event3', event4='$event4', timesub='$timesub'")
Your query is missing a WHERE clause. Without a WHERE clause, your query will update all rows in the table announcement. You need to add something like:
WHERE id='$id'
This will restrict the update to only the row you want to update.

php mysql checkbox and textboxes values insert into database

I have a db table called 'ice_flavours' with the columns: 'id', 'flavours', 'date', 'selected'.
and another table called 'ice_today' like: 'id', 'flavours', 'date', 'selected'.
Now, on the left of the page I want to call from 'ice_flavours' and print the entries in a form together with a checkbox.
On the right of the page it shall say SHOWCASE where I want the todays selected flavours to be shown and they shall just stay in there until the end of today´s date and then automatically be discarded. Also when they were selected to show in SHOWCASE, i want them to not show on the left side.
So, when I select the checkbox next to a flavour, the values 'id', 'flavours', 'date', 'selected' ought to be entered into 'ice_today' but for some reason just always the last row of the ice_flavours table is entered and i get the message "Duplicate entry '0' for key 'PRIMARY'"
Maybe this can all be done by just using a single db table but I havent figured it yet. Can someone help please
edit.php:
<?php ob_start();
include_once("dbinfo.inc.php");
include_once("config.php");
if(isset($_POST['submit'])){
$selected = $_POST['selected'];
$id = $_POST['id'];
$flavour = $_POST['flavour'];
$date = $_POST['date'];
if($_POST["submit"] == "submit") {
for($i=0;$i<sizeof($selected);$i++) {
if(!empty($flavour)) {
echo"";
echo "<pre>";
print_r($_POST);
echo "</pre>";
$query="INSERT INTO ice_today VALUES('$id','$flavour','$date','$selected[$i]')";
mysql_query($query) or die(mysql_error());
}
}
echo "Entry added";
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Edit</title>
</head>
<body>
<form name="form1" id="form1" method="POST" action="edit.php">
<table border="1" width="200px">
<td>
<table border="1" width="200px">
<?php
$result = mysql_query("SELECT * FROM ice_flavours WHERE ('selected' != '1') ORDER BY flavour ASC");
$results = mysql_num_rows($result);
if ($results > 0)
{
$num=mysql_numrows($result);
$i=0;
while ($i < $num)
{
$id=mysql_result($result,$i,"id");
$flavour=mysql_result($result,$i,"flavour");
?>
<tr>
<td align="center" valign="middle">
<?php echo $flavour; ?>
<input type="text" name="id" id="id" value="<?php echo $id; ?>">
<input type="text" name="flavour" id="flavour" value="<?php echo $flavour; ?>">
<input type="text" name="datum" id="datum" value="<?php echo date('Y-m-d'); ?>">
<input type="checkbox" name="selected[]" id="selected" value="<?php echo '1'; ?>">
</td></tr>
<?php
$i++;
}
?>
<input type="submit" value="submit">
<?php } ?>
</td>
<td>
<table border="1" width="200px">
<tr><td align="center" valign="middle">
SHOWCASE
</td></tr>
<?php
include_once("dbinfo.inc.php");
include_once("config.php");
$result2 = mysql_query("SELECT * FROM ice_today ORDER BY flavour ASC");
$results2 = mysql_num_rows($result2);
if ($results2 > 0)
{
$num2=mysql_numrows($result2);
$j=0;
while ($j < $num2)
{
$id=mysql_result($result2,$j,"id");
$flavour=mysql_result($result2,$j,"flavour");
?>
<tr><td align="center" valign="middle">
<?php echo $flavour; ?>
</td></tr>
<?php
$j++;
}
}
echo '</td></tr></table>';
?>
</body>
</html>
<?php ob_end_flush(); ?>
Please take a look at the MySQL Reference Manual. You need to specify each column in your INSERT statement:
$query="INSERT INTO ice_today(id, flavours, date, selected) VALUES('$id','$flavour','$date','$selected[$i]')";
I also suggest you to not use the original MySQL-extension anymore, as it is deprecated as of PHP 5.5.x. When using another MySQL extension (MySQLi or PDO for instance: mysqli or PDO - what are the pros and cons?) you can also use prepared statements to become safe against SQL injections (which you aren't right now).
POST-values can be manipulated and as you just feed them into your query via string concatenation, you're not safe against them.
If the field for ID is an autoincrement field, you need to leave it off the insert because the db server will determine the value itself. You should list the fields being inserted, and leave that one off:
$query="INSERT INTO ice_today (flavours, date, selected) VALUES('$flavour','$date','$selected[$i]')";
Listing the fields you are inserting to also prevents insert statements from breaking when you add new fields later. So its good practice to start now.
There are lots of issues in your code.
You text boxes having same name with different values if there are two flavors.
Therefore flavor or id will be always from last row.
You can do something like this.
1.Replace your text boxes with this,
<input type="text" name="id_<?php echo $id; ?>" value="<?php echo $id; ?>">
<input type="text" name="flavour_<?php echo $id; ?>" value="<?php echo $flavour; ?>">
<input type="text" name="datum_<?php echo $id; ?>" value="<?php echo date('Y-m-d'); ?>">
<input type="checkbox" name="selected[]" value="<?php echo $id; ?>">
2.Replace your top if block (i.e. after submit)
if (isset($_POST['submit']) && $_POST["submit"] == "submit") {
$selected = $_POST['selected'];
for($i=0; $i < sizeof($selected); $i++) {
$id = $selected[$i];
$flavour = $_POST['flavour_' . $id];
$date = $_POST['date_' . $id];
$query="INSERT INTO ice_today VALUES('$id','$flavour','$date','$id')";
mysql_query($query) or die(mysql_error());
}
}

Categories