I know how to make a set query display, but I need to take an input, run a statement, and display the result. Here is what I have:
HTML:
<form name="form3" method="post" action="sqlexp.php"> <input name="sqlstatement" type="text" id="sqlstatement" style="width: 340px;"> <input type="submit" name="create" value="Create"> </form>
PHP:
ob_start(); $host = "localhost"; // Host name $username = "root"; // Mysql username $password = "Passw0rd"; // Mysql password $db_name = "time_tracker"; // Database name // Connect to server and select databse. mysql_connect("$host", "$username", "$password") or die("cannot connect"); mysql_select_db("$db_name") or die("cannot select DB"); // Define $sqlstatement $sqlstatement = $_POST['sqlstatement']; // runs statement $sql = " $sqlstatement "; $result = mysql_query($sql); echo $sql; echo $result; ob_end_flush();
I also want to make the statements read only so nobody can mess with my tables. im a little new to this i might need some extra explaining
Advertisement
Answer
To retrieve column names along with the result set, look at this SO question: How to get the columns names along with resultset in php/mysql?
Specifically this code snippet should help you print out the results:
// Print the column names as the headers of a table echo "<table><tr>"; for($i = 0; $i < mysql_num_fields($result); $i++) { $field_info = mysql_fetch_field($result, $i); echo "<th>{$field_info->name}</th>"; } // Print the data while($row = mysql_fetch_row($result)) { echo "<tr>"; foreach($row as $_column) { echo "<td>{$_column}</td>"; } echo "</tr>"; } echo "</table>";
Now, that said, please be very, very careful before proceeding. It looks like you’re unfamiliar with PHP, and what you’re attempting is very dangerous as it opens up a classic SQL injection vulnerability: https://xkcd.com/327/
You could restrict the possibility of damage by restricting the database permissions to read-only for the user you’re logging in as ($username and $password). Do NOT login as root – never!
If this form is only available to Admins, why not give them a true SQL IDE like Toad or SQL Server Management Studio?