This script allows the user to choose a table from the dropdown and then displays the contents of the chosen table.
At the moment the DB connection is working.
A list of tables is shown in the dropdown.
Problem: No content from the database table is shown.
I have checked through the code and everything looks OK, but it still only seems to partially work.
<?php
//update this to your DB connection details.
$dbh = "localhost";
$dbn = "dbname";
$dbu = "dbuser";
$dbp = "dbpass";
$conn = mysql_connect($dbh,$dbu,$dbp) or die("Unable to connect do database.");
mysql_select_db($dbn, $conn) or die("Unable to select database.");
//Some vars for Order by and Limit.
if (!isset($ordBy)){
$ordBy = 1;
}
if (!isset($ps)){
$ps = 0;
}
if (!isset($ord)){
$ord = 1;
}
if ($ord == 1){
$tOrder = "ASC";
} else {
$tOrder = "DESC";
}
//Tables drop-down
$result = mysql_query("SHOW TABLES FROM $dbn") or die("Cannot list table names.");
echo "
<form name=\"table_browser\" action=\"".$PHP_SELF."\" method=\"GET\" >
<select name=\"t\" onChange=\"javascript:submit();\">
<option>Select a table</option>
";
while ($row = mysql_fetch_row($result)){
echo " <option value=".$row[0].">".$row[0]."</option>\n";
}
echo " </select>
</form>\n";
if (!isset($t)){
die("Please select a table");
}
//Get number of rows in $t and then select
$result = mysql_query("SELECT COUNT(*) FROM $t") or die("The requested table doesn't exist.");
$total = mysql_result($result,0);
$qry = "SELECT * FROM $t ORDER BY ".$ordBy." ".$tOrder." LIMIT ".($ps*20).",20 ";
if (isset($qry)) {
$result = mysql_query($qry) or die("The requested table doesn't exist.");
$i = 0;
while ($i < mysql_num_fields($result)) {
$meta = mysql_fetch_field($result);
if (!$meta) {
echo "No information available on the table<br />\n";
}
$name[$i] = $meta->name;
$i++;
}
//Display table details
echo "Rows ".($ps*20+1)." to ".((($ps+1)*20 < $total) ? (($ps+1)*20) : ($total))." of $total from table:
<b>$meta->table</b>\n<br /><br />\n";
//Count results
if ($ps > 0) {
echo "20 Previous - ";
} else {
echo "20 Previous - ";
}
if ((($ps+1)*20) < $total ){
echo "Next 20\n";
} else {
echo "Next 20\n";
}
//Column names
echo "<br /><br />\n<table>\n <tr>\n";
for ($j = 0; $j < $i; $j++){
echo " <td><b>$name[$j]</b>";
if ($ordBy == $name[$j]) {
echo "<img src=\"images/arrow$ord.gif\">";
}
echo "</td>\n";
}
echo " </tr>\n";
//Data
while ($row = mysql_fetch_array($result)){
echo " <tr onmouseover=\"this.style.background='#DDDDDD'\" onmouseout=\"this.style.background=''\">";
for ($j = 0; $j < $i; $j++){
echo "<td>".$row[$name[$j]]."</td>";
}
echo "</tr>\n";
}
echo "</table>\n";
}
mysql_close();
?>
#gentlebreeze - my eyes hurt from trying to read that - but I can't see where you are actually setting the variable called $t - which is used to determine the table. You should have
$t = $_GET['t'];
somewhere before the line:
....if (!isset($t)){....
because you need to use it in the line:
....$result = mysql_query("SELECT COUNT(*) FROM $t"....
and you should not be using mysql_query either - old and now deprecated. You should switch to PDO and bound variables.
Related
I am making a tictactoe game with php and mysql. It should be played by 2 players from different systems. So I have a table in mysql with a column id which goes from 1-9 and a column tictac which has a value X or O or NULL. Put a x or o in the database is working but retrieving a X or O out of the table and show it on the screen is not working. I have a config file, a class.tictactoe.php, class.game.php and an index.php. The DB connection should be in the class.tictactoe.php but I don't know how.
I am having the most trouble with this part:
function displayGame()
{
if (!$this->isOver())
{
echo "<div id=\"board\">";
$i=1;
for ($x = 0; $x < 3; $x++)
{
for ($y = 0; $y < 3; $y++)
{
require('config.inc.php');
$db = new PDO("mysql:dbname=$db_name;host=$db_host",
$db_user, $db_pass,
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
echo "<div id=\"$i\" class=\"board_cell\">";
$i++;
$query = $db->prepare('SELECT * FROM tictactoe WHERE value IS NOT NULL and id = ?');
if ($this->board[$x][$y])
$query->execute([$lookup[$key]]);
echo "<p>\"{$this->board[$x][$y]}\"</p>";
else
{
echo "<select name=\"{$x}_{$y}\">
<option value=\"\"></option>
<option value=\"{$this->player}\">{$this->player}</option>
</select>";
}
echo "</div>";
}
echo "<div class=\"break\"></div>";
}
echo "
<p align=\"center\">
<input type=\"submit\" name=\"move\" value=\"Take Turn\" /><br/>
<b>It's player {$this->player}'s turn.</b></p>
</div>";
}
else
{
if ($this->isOver() != "Tie")
echo successMsg("Congratulations player " . $this->isOver() . ", you've won the game!");
else if ($this->isOver() == "Tie")
echo errorMsg("Whoops! Looks like you've had a tie game. Want to try again?");
session_destroy();
echo "<p align=\"center\"><input type=\"submit\" name=\"newgame\" value=\"New Game\" /></p>";
}
}
function move($postdata)
{
if ($this->isOver())
return;
require('config.inc.php');
$db = new PDO("mysql:dbname=$db_name;host=$db_host",
$db_user, $db_pass,
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$postdata = array_unique($postdata);
$lookup = ['0_0'=>1, '0_1'=>2, '0_2'=>3, '1_0'=>4, '1_1'=>5, '1_2'=>6,
'2_0'=>7, '2_1'=>8, '2_2'=>9];
$query = $db->prepare('UPDATE tictactoe SET tictac = ? WHERE id = ?');
foreach ($postdata as $key => $value)
{
if ($value!=$this->player) continue;
$query->execute([$this->player, $lookup[$key]]);
if ($value == $this->player)
{
$coords = explode("_", $key);
$this->board[$coords[0]][$coords[1]] = $this->player;
if ($this->player == "X")
$this->player = "O";
else
$this->player = "X";
$this->totalMoves++;
}
}
if ($this->isOver())
return;
}
The indentation might be wrong.
hi guys im trying to insert a mysql data to a variable that will set an if condition depending on the result. is this possible, am i doing it right? what is the right way to do it ? what i want to achieve is to validate if there's a equal value given by the user inside my mysql rows.
$db = mysql_connect('localhost','test','');
if (!$db)
{
print "<h1>Unable to Connect to MySQL</h1>";
}
$dbname = 'test';
$btest = mysql_select_db($dbname);
if (!$btest)
{
print "<h1>Unable to Select the Database</h1>";
}
$sql_statement = "SELECT * ";
$sql_statement .= "FROM registered_email ";
$result = mysql_query($sql_statement);
$outputDisplay = "";
$myrowcount = 0;
if (!$result) {
$outputDisplay .= "<br /><font color=red>MySQL No: ".mysql_errno();
$outputDisplay .= "<br />MySQL Error: ".mysql_error();
$outputDisplay .= "<br />SQL Statement: ".$sql_statement;
$outputDisplay .= "<br />MySQL Affected Rows: ".mysql_affected_rows()."</font><br />";
}
else{
$numresults = mysql_num_rows($result);
for ($i = 0; $i < $numresults; $i++)
{
$row = mysql_fetch_array($result);
$id = $row['id'];
$sentEmailClients = $row['email'];
$outputDisplay.= "".$sentEmailClients."<br />";
}
}
and here what im trying to achieve, btw is $clientEmail has a default values so dont worry about that.
if($clientEmail === $outputDisplay){
...... some codes..........
}
else{
....... some codes.......
}
you can use mysql row to compare with your user input. you can add condition, while you'r getting row value for the email inside the loop.
$email_exist = 0;//define the default value.
for ($i = 0; $i < $numresults; $i++)
{
$row = mysql_fetch_array($result);
$id = $row['id'];
$sentEmailClients = $row['email'];
$outputDisplay.= "".$sentEmailClients."<br />";
//my code start here
if($sentEmailClients == $clientEmail)
$email_exist = 1;
}
//outside the loop
if($email_exist == 1) {
//..........write some code.......
}else{
//........write some code.......
}
why don't you use a while loop?
make sure to update to mysqli_* because mysql_* is deprecated and is going to get removed on php 7.0
$email_exist = 0;//define the default value.
while ( $row = mysql_fetch_assoc($result) ) // you are using associative array and not the indexed once tho you should go for mysql_fetch_assoc
{
$id = $row['id'];
$sentEmailClients = $row['email'];
$outputDisplay.= "".$sentEmailClients."<br />";
//my code start here
if($sentEmailClients == $clientEmail)
$email_exist += 1; //maybe it exist more than once?
}
//outside the loop
if($email_exist == 1) {
//..........write some code.......
}else{
//........write some code.......
}
or you can do something more simple like this
$query = "select email from tablename where email='$clientemail'";
$result = mysql_query($query);
$count = mysql_num_rows($result);
if($count > 0) {
// email exists
} else {
// doesn't exist
}
I'm trying to display 6 items in one page with 3 items in each row. And when the user clicks on the image link it will redirect to another page and display the id. However when the user clicks on the image it does redirect to another page but it shows the id of the last product in the last row of the page, and this is not correct. I'm not sure where I made the mistake. I hope you can look at my code and give me a hint where the mistake lies.
<?PHP
session_start();
function connect()
{
$servername = xxxxxxxx;
$username = xxxxxxxx;
$password = xxxxxxxx;
$dbname = xxxxxxxx;
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
echo 'connection is invalid';
} else {
mysqli_select_db($conn, "mytest");
}
return $conn;
}
function getData()
{
$conn = connect();
if (!isset($_GET['startrow']) or !is_numeric($_GET['startrow'])) {
$startrow = 0;
} else {
$startrow = (int) $_GET['startrow'];
}
$sql = "SELECT * FROM tbl_products LIMIT $startrow, 6";
$getdata = mysqli_query($conn, $sql) or die(mysqli_error());
$cell_img = mysqli_num_rows($getdata);
$i = 0;
$per_row = 3;
echo "<table id='productTumb'><tr id='proRow'>";
$data = '';
while ($row = mysqli_fetch_assoc($getdata)) {
//echo "<a href='ProDet.html'></a>";
echo "<td><a href='test.php'><img style='vertical-align: bottom;' width='218px' height='332px' src='" . $row['products_image'] . "'/ ></a></td>";
$data .= "<td style='background-color:#FF0004'>" . $row['product_name'] . "</td>";
$product_id = $row['products_id'];
$_SESSION['id'] = $product_id;
if (++$i % $per_row == 0 && $i > 0 && $i <= $cell_img) {
echo "</tr><tr>$data</tr><tr>";
$data = '';
}
}
for ($x = 0; $x < $per_row - $i % $per_row; $x++) {
echo "<td></td>";
}
echo "</tr>";
echo "</table>";
echo 'Next >>>';
$prev = $startrow - 5;
if ($prev >= 0)
echo ' <<<< Previous';
}
?>
This line of code $_SESSION['id'] = $product_id; will set last product id to SESSION.(overwrites previous ids)
Try to add product id to the anchor href tag
while ($row = mysqli_fetch_assoc($getdata)) {
echo "<td><a href='test.php?id=".$row['products_id']."'><img style='vertical-align: bottom;' width='218px' height='332px' src='" . $row['products_image'] . "'/ ></a></td>";
......
}
In test.php file get id by below code
if(isset($_GET)){
$pid = $_GET['id'];
echo $pid;
}
hope this will helps you.
How do I display out all the information in a database (All tables and records) using PHP? I read displaying tables as HTML table but how do I do it for all the tables?
I tried the example here:
http://davidwalsh.name/html-mysql-php
But it shows the table names, how do I also display all the values?
Okay got it .. try this
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "username", "password", "DB");
$result = $mysqli->query("SHOW TABLES");
while ($row = $result->fetch_row()) {
$table = $row[0];
echo '<h3>', $table, '</h3>';
$result1 = $mysqli->query("SELECT * FROM `$table`");
echo '<table cellpadding="0" cellspacing="0" class="db-table">';
$column = $mysqli->query("SHOW COLUMNS FROM `$table`");
echo '<tr>';
while ($row3 = $column->fetch_row()) {
echo '<th>' . $row3[0] . '</th>';
}
echo '</tr>';
while ($row2 = $result1->fetch_row()) {
echo '<tr>';
foreach ($row2 as $key => $value) {
echo '<td>', $value, '</td>';
}
echo '</tr>';
}
echo '</table><br />';
}
$mysqli->close();
you can use the recursive function to display the tree Structure of your database.
Here is the a sample code from http://webcodingeasy.com/PHP/Simple-recursive-function-to-print-out-database-tree-structure
<?php
function print_menu($id = 0)
{
// get all records from database whose parent is $id
$result = $query->select_result("*", "table", "where parent = '".$id."'");
//check if there are any results
if($result != 0)
{
echo "<ul> n";
while($row = $query->fetch($result))
{
//print result and call function to check if it has children
echo "<li>".$row['name']."</li> n";
print_menu($row['ID']);
}
echo "</ul> n";
}
}
print_menu();
?>
If you want to pull all tables with the values in mysql, you can use the following code:
<?php
mysql_connect ("localhost", "DB_USER", "DB_PASSWORD"); //your mysql connection
mysql_select_db('DB_NAME') or die( "Unable to select database"); //your db name
$tables = mysql_query("SELECT table_name FROM information_schema.tables WHERE table_schema='DB_NAME'"); //pull tables from theh databsase
while ($table= mysql_fetch_row($tables)) {
$rsFields = mysql_query("SHOW COLUMNS FROM ".$table[0]);
while ($field = mysql_fetch_assoc($rsFields)) {
echo $table[0].".".$field["Field"].", "; //prints out all columns
}
echo $table[0];
$query = "SELECT * FROM ".$table[0]; //prints out tables name
$result = mysql_query($query);
PullValues($result); //call function to get all values
}
//function to pull all values from tables
function PullValues($result)
{
if($result == 0)
{
echo "<b>Error ".mysql_errno().": ".mysql_error()."</b>";
}
elseif (#mysql_num_rows($result) == 0)
{
echo("<b>Query completed. No results returned.</b><br>");
}
else
{
echo "<table border='1'>
<thead>
<tr><th>[Num]</th>";
for($i = 0;$i < mysql_num_fields($result);$i++)
{
echo "<th>" . $i . " - " . mysql_field_name($result, $i) . "</th>";
}
echo " </tr>
</thead>
<tbody>";
for ($i = 0; $i < mysql_num_rows($result); $i++)
{
echo "<tr><td>[$i]</td>";
$row = mysql_fetch_row($result);
for($j = 0;$j < mysql_num_fields($result);$j++)
{
echo("<td>" . $row[$j] . "</td>");
}
echo "</tr>";
}
echo "</tbody>
</table>";
} //end else
}
?>
I am using this and works fine in mysql, for mysqli you need to tweak it a very little.
I am working on a lead management system - and as the database for it grows the need for more bulk functions appears - and unfortunately I am getting stuck with one of them. The database stores many different leads - with each lead being assigned to a specific closer; thus the database stores for each lead the lead id, name, closer name, and other info. The main lead list shows a checkbox next to each lead which submits the lead id into an array:
<input type=\"checkbox\" name=\"multipleassign[]\" value=\"$id\" />
Now this all goes to the following page:
<?php
include_once"config.php";
$id = $_POST['multipleassign'];
$id_sql = implode(",", $id);
$list = "'". implode("', '", $id) ."'";
$query = "SELECT * FROM promises WHERE id IN ($list) ";
$result = mysql_query($query);
$num = mysql_num_rows ($result);
if ($num > 0 ) {
$i=0;
while ($i < $num) {
$closer = mysql_result($result,$i,"business_name");
$businessname = mysql_result($result,$i,"closer");
echo "$closer - $businessname";
echo"<br>";
++$i; } } else { echo "The database is empty"; };
echo "<select name=\"closer\" id=\"closer\">";
$query2 = "SELECT * FROM members ";
$result2 = mysql_query($query2);
$num2 = mysql_num_rows ($result2);
if ($num2 > 0 ) {
$i2=0;
while ($i2 < $num2) {
$username = mysql_result($result2,$i2,"username");
$fullname = mysql_result($result2,$i2,"name");
echo "<option value=\"$fullname\">$fullname</option>";
++$i2; } } else { echo "The database is empty"; }
echo "</select>";
?>
I want to be able to use the form on this page to select a closer from the database - and then assign that closer to each of the leads that have been selected. Here is where I have no idea how to continue.
Actually - i got it. I don't know why I didn't think of it sooner. First off I passed the original $list variable over to the new page - and then:
<?php
include_once"config.php";
$ids = $_POST['list'];
$closer = $_POST['closer'];
$query = "UPDATE `promises` SET `closer` = '$closer' WHERE id IN ($ids) ";
mysql_query($query) or die ('Error updating closers' . mysql_error());
echo "A new closer ($closer) was assigned to the following accounts:";
$query = "SELECT * FROM promises WHERE id IN ($list) ";
$result = mysql_query($query);
$num = mysql_num_rows ($result);
if ($num > 0 ) {
$i=0;
while ($i < $num) {
$businessname = mysql_result($result,$i,"business_name");
echo "<li>$businessname";
++$i; } } else { echo "The database is empty"; };
?>
The updated page before this:
$query = "SELECT * FROM promises WHERE id IN ($list) ";
$result = mysql_query($query);
$num = mysql_num_rows ($result);
if ($num > 0 ) {
$i=0;
while ($i < $num) {
$closer = mysql_result($result,$i,"business_name");
$businessname = mysql_result($result,$i,"closer");
echo "$closer - $businessname";
echo"<br>";
++$i; } } else { echo "The database is empty"; };
echo "<form name=\"form1\" method=\"post\" action=\"multiple_assign2.php\">";
echo "<input type=\"hidden\" name=\"list\" value=\"$list\" />";
echo "<select name=\"closer\" id=\"closer\">";
$query2 = "SELECT * FROM members ";
$result2 = mysql_query($query2);
$num2 = mysql_num_rows ($result2);
if ($num2 > 0 ) {
$i2=0;
while ($i2 < $num2) {
$username = mysql_result($result2,$i2,"username");
$fullname = mysql_result($result2,$i2,"name");
echo "<option value=\"$fullname\">$fullname</option>";
++$i2; } } else { echo "The database is empty"; }
echo "</select>";
echo "<input name=\"submit\" type=\"submit\" id=\"submit\" value=\"Reassign Selected Leads\">";
?>
After you select the leads and submit the form , your script should show them in a list with hidden inputs (with name=leads[] and value=the_lead's_id) and next to each lead there will be a dropdown box () which will be populated with all the closers.
After choosing and sending the second form your script will "run" all-over the leads' ids array and update each and every one of them.
Got the idea or you want some code?