Shows Table and Values Using Drop Down - php

In this application I have a drop down so you can select what table you want to view. Using Ajax I push the variable $tbl as an integer and the code below prints out the table that corresponds with that integer. Something is not working though and I need an extra pair of eyes to help debug.
if($tbl == 9){$table = "person";}
$conn = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);
$query = mysqli_query($conn, "SELECT * FROM $table ") or die(mysqli_error($conn));
if($query){
echo '<table border="1"><thead><tr>';
$colnames = array();
while ($finfo = mysqli_fetch_field($query)) {
$name=$finfo->name;
array_push($colnames, $name);
echo "<th>".$name."</th>";
}
mysqli_free_result($query);
echo '</tr></thead><tbody>';
$count = 0;
echo $colnames[$count]; // this test prints the correct column name but it ends up being printed OUTSIDE the table for some reason
while ($row = mysqli_fetch_array($query, MYSQLI_BOTH)){
echo '<td>'.$row[$colnames[$count]].'</td>';
$count++;
}
echo "</tbody></table>";
}
The last while loop is suppose to echo out each field value but it isn't executing <tbody> is left blank.

You called mysqli_free_result($query) too early. So by the time you called mysqli_fetch_array, the sql result was already gone. Move mysqli_free_result after the last loop.

I'm not sure whether it's a typo or that the following is where the problem lies, but you're missing opening and closing <tr> tags around the column names after <tbody> and before </tbody>. This may help explain why stuff is being printed apparently "outside" the table.

Related

How to display all rows of mysql_fetch_array using while loop

Unable to display all rows of mysql_fetch_array using while loop.
Hi. My problem is I am only able to display last row entered into database table.
I am parsing form data with php to insert into a database table.
I know that the form data is being inserted into the table.
I am using a while loop to attempt to extract data from two columns in all of the rows of the table.
I am using php to display the data of the two columns id & product_name in each row.
It is my understanding that a mysql_fetch_array will only return 1 row unless it is used in conjunction with a while loop, which then should return all rows. So I am confused why I can only out put the last row.
When I browse the table in phpMyAdmin there are three rows each with an id number.
They are ordered sequentially 1, 2, 3 because the id column is auto increment.
id column is primary key.
product_name column is unique key.
I don't think there is a problem with my query structure.
Possibly a problem defining $product_list variable ? I don't know.
I have closed browser and cleared all history, cookies etc.
I have stopped & restarted Apache server & mysql.
When I echo var_dump ($sql); I get: resource(6) of type (mysql result) .
When I echo var_dump ($product_list); I get: string(99) "3 - Blue Jeans edit • delete "
When I print_r ($sqL); I get: Resource id #6
When I echo $product_list; I get: 3 - Blue Jeans edit • delete
I have spent a lot of time searching for answer to this via google searches but none seem to fit this particular problem.
I did see one similar question suggesting using a concatenation approach, but there were zero (0) up-votes. So I wasn't sure if this was a viable remedy to my problem.
Here is the code I am using:
<?php
//this block grabs the whole list for viewing
$product_list = "";
$sql= mysql_query ("SELECT * FROM `products`");
$product_count = mysql_num_rows ($sql);
if ($product_count > 0) {
while($row = mysql_fetch_array ($sql)) {
$id = $row['id'];
$product_name = $row ['product_name'];
$product_list = "$id - $product_name <a
href='#'>edit</a> • <a href='#'>delete</a>
<br/>";
}
} else {
$product_list = "You have no products listed in your store yet";
}
?>
<?php echo $product_list; ?>
You are overwriting $product_list in every loop.
You have to concateate by concat operator .=
$product_list .= "$id - $product_name <a href='#'>edit</a> • <a href='#'>delete</a> <br/>";
Ok this answer might not what you're looking for but I only use mySQLi not the older version. I'll rewrite the your code with the newer syntax only because I know this would work. So here goes
<?php
$conn = new mysqli($server, $username, $password, $database);
$product_list = "";
$sql = $conn->query("SELECT * FROM products");
$product_count = mysqli_num_rows ($sql);
if ($product_count > 0) {
while($row = $sql->fetch_assoc()) {
$id = $row['id'];
$product_name = $row ['product_name'];
$product_list = "$id - $product_name <a
href='#'>edit</a> • <a href='#'>delete</a>
<br/>";
}
} else {
$product_list = "You have no products listed in your store yet";
}
?>
You would need to either add the $conn = new mysqli($server, $username, $password, $database); in mySQLi Object Orientated method or can replace $conn on the $sql = $conn->query("SELECT * FROM products"); line withe your existing one and this should work.

Why won't my WHERE query work?

I've been on this for some days now. At first I thought the problem was in binding the parameters but I've simplified back to a basic mysqli page and still can't find the error. I'm passing the key for one of the rows in the search page before this onto this page so that I can show more details of the item which was selected.
I added an echo to test the the isset which prints correctly, also it puts the Key into the URL. If I leave out the WHERE Key = '$Key' it prints out the entire dataset. If I replace $row['Key'] with $Key it prints the whole dataset but with the selected key on every row.
This tells me that it is passing the key correctly and the print function is correct. I've tried using WHERE Key = $_GET['Key'] as well as $Key but neither work. I must be doing something basicly wrong here but after three days of trying every variation on the code I can think of, I have no more ideas.
<?php
$mysqli = new mysqli('localhost','user','password','database');
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
if(isset($_GET['Key'])){
$Key = $_GET['Key'];
echo "Got it";
}else{
echo "No input";
}
$results = $mysqli->query("SELECT * FROM engravers WHERE Key ='$Key'");
$img_url = "http://www.xxxxx.net/images/";
print '<table border="1" >';
while($row = $results->fetch_assoc()) {
print '<tr>';
print '<td>'.$row["Key"].'</td>';
print '<td>'.$row["Country"].'</td>';
print '<td>'.$row["Year"].'</td>';
print '<td>'.$row["Description"].'</td>';
print '<td>'.$row["Engraver1Surname"].'</td>';
print '<td>'.$row["Designer1Surname"].'</td>';
print '<td>'.$row["Printer"].'</td>';
print '<td>'.'<img src="'.$img_url.$row['Images'].'" />'.'</td>';
print '</tr>';
}
print '</table>';
$results->free();
$mysqli->close();
?>
</body>
There are many SQL column names you should avoid. Please read: http://technet.microsoft.com/en-us/library/ms189822.aspx
Same Reserved Keywords are in MySQL.
If you use one of those just cover it with ``
$results = $mysqli->query("SELECT * FROM `engravers` WHERE `Key`='$Key'");
In your query you are using column key which is not allowed because this is a reserved keyword.
Man, you're already using mysqli, why are you still interpolating variables in your query? This is the way to pass a string $Key to the parser
$results = $mysqli->prepare("SELECT * FROM engravers WHERE `Key`= ?");
$results->bind_param("s", $Key);
while($row = $results->fetch_assoc()) {
... stuff ...
}
If that doesn't work, I'm sure it's not because the prepared statement is the problem.
PD: key is a reserved word, so please note the fieldname is wrapped in backticks.

Retrieve multiple checkbox and display other related information from database in a table

I got this list of checkboxes that print out from database. I am able to retrieve data from database if user makes multiple checkbox and display it in table, but i cannot retrieved other information from database and display it in the same table.
This is my code:
<table border='1'>
<tr>
<th>TITLE</th>
<th>PERCENTAGE RESULT</th>
</tr>
<?php
if(isset ($_POST["submit1"]))
{
$selectedcheckbox = $_POST["selectedcheck"];
$query = "SELECT * FROM compareresult where subject=$selectedcheckbox";
$sql_query = mysql_query($query) or die('Error 3 :'.mysql_error());
while($data = mysql_fetch_array($sql_query,MYSQL_ASSOC)){
$result=$data['result'];
}
foreach($selectedcheckbox as $title)
{
echo "<tr>";
echo "<td>".$title."</td>";
echo "<td>".$result."</td>";
}
echo "</tr>";
}
?>
I want to display result after user select multiple checkbox, so I wrote:
echo $result in table
so that the result can be displayed in table beside the selected title, but I am getting an error:
Array to string conversion in C:\xampp\htdocs\sam\c.php on line 31 Error 3 :Unknown column 'Array' in 'where clause'
I am not at the moment in the environment to test your problem, and I do this out of my head, but try something like the following.
if(isset($_POST['submit1'])){
$checkbox = isset($_POST['selectedcheck']) ? $_POST['selectedcheck'] : array();
foreach($checkbox as $title){
$query = "SELECT * FROM compareresult where subject='".$title."'";
$result=mysql_query($query); // <-- to avoid SQL injections, please change your method from mysql_query to mysqli_query (use the mysqli functions instead of mysql)
while($data = mysql_fetch_array($result)){
$result=$data['result'];
echo "<tr>";
echo "<td>".$title."</td>";
echo "<td>".$result."</td>";
echo "</tr>
}
}
}
It checks first if your checkboxes are checked and if they are they put it in an array.
Then it runs the foreach statement, where it sets the checkbox value as title. It runs there if the query if it the title is in the database, if so, spit it out through the while loop. Rinse and repeat until done.
edit
I see you put your open tablerow statement in the foreach but close it outside. So either you want it all printed on one line or is it an error? If its on one line, make sure you open the table row BEFORE the while loop and end it AFTER, else it's like how i spit it out.

Store oracle row value on php variable

I have a table in Oracle with this columns: IMGPOSX, IMGPOSY and IDIMG. Each row of the table has a different X Y value positions and an ID to identify witch of this values correspond to an specified ID.
For example: IDIMG = image1 > IMGPOSX = 20 IMGPOSY = 50
With this value then I build a html map image and load the image with an specified ID and put the results of the IMGPOSX and IMGPOSY on the margin-top and margin-left css properties.
I have found several example of how to get the values of the first line of the row but i don't know how to get the another ones (the table has 12 rows)
With the next code I get the first row of each column (IMGPOSX, IMGPOSY and IDIMG) but i don't know how to get the rest of the rows of the table. If I put row1[1] the parser get an error.
<?php
$conn = oci_connect('TEST', 'TEST', 'ORCL');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT IMGPOSX, IMGPOSY, IDIMG FROM TESTTABLE ');
if(oci_execute($stid))
{
$row=oci_fetch_row($stid) ;
"<table border='2'>";
print"<tr><td><p>posx: </td><td>$row[0] </td></tr>";
print"<tr><td>posy: </td><td>$row[1] </td></tr>";
print"<tr><td>idimg: </td><td>$row[2] </td></tr>";
print"</table></br>";
}
oci_free_statement($stid);
oci_close($conn);
?>
Also I like to filter the results of the fetch by the idimg, for example, some code that says "showme only the IMGPOSX and IMGPOSY from the IDIMG='image2'.
A rough example could be appending a WHERE clause to your query:
$id = 'image2';
$stid = oci_parse($conn, "SELECT IMGPOSX, IMGPOSY, IDIMG FROM TESTTABLE WHERE IMDIMG = $id;");
or, with the same query, you can filter with IF:
if ($row[2] == $id) {
//show
}
The sentence before your code states that you could need more than one row, so if you are not filtering, you will recieve more, to get them you need a proper fetch. Your current one if fetch_row, maybe you need fetch_array in order to recieve array with all values.
I would suggest oci_fetch_assoc http://php.net/manual/en/function.oci-fetch-assoc.php so you can access the column via their names. Also the filtering will use a named column.
if ($row['IDIMG'] == $id) {
//show
}
Have in mind the following sentence of the function description:
This function is typically called in a loop until it returns FALSE
You'd need something like:
<?php
//all the code here
// ...
// ...
?>
<table border="2">
<?php while ($row = oci_fetch_assoc($stid)): ?>
<tr><td><p>posx:</p></td><td><?=$row['IMGPOSX'];?></td></tr>
<tr><td><p>posy:</p></td><td><?=$row['IMGPOSY'];?></td></tr>
<tr><td><p>idimg:</p></td><td><?=$row['IDIMG'];?></td></tr>
<?php endwhile; ?>
</table><br />
<?php
oci_free_statement($stid);
oci_close($conn);
?>

MySQL retrieval from database not retrieving multiple rows

I'm trying to retrieve all data with the LIKE query from the users input and match it to the database, it works but only returns one record but I have many records in the table.
It returns the closest record it can find,
so say for example I have 2 records who's ItemDesc field contains the characters 'The', when I search for 'The' in my input box and click submit it returns the closest (earliest created) record when it is supposed to return both.
<?php
$username = "a3355896_guy";
$password = "++++++";
$hostname = "mysql5.000webhost.com";
$dbh = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
mysql_select_db("a3355896_book") or die("Unable to connect to database");
$ItemDesc = $_POST['ItemDesc'];
$query = "select * from StockItems where ItemDesc LIKE '%$ItemDesc%'";
$result=mysql_query($query);
$num=mysql_num_rows($result);
mysql_close();
?>
Sorry was supposed to included the retrieval:
<?php
if ($num>0)
{
echo "<center><table border=1><tr><th>Item Code</th><th>Item Desc</th>";
echo "<th>Item Stock Qty</th>";
echo "<th>Item Unit Price</th><th>Item Category</th></tr>";
$ItemCode = mysql_result($result,$i,"ItemCode");
$ItemDesc = mysql_result($result,$i,"ItemDesc");
$ItemStockQty = mysql_result($result,$i,"ItemStockQty");
$ItemUnitPrice = mysql_result($result,$i,"ItemUnitPrice");
$ItemCategory = mysql_result($result,$i,"ItemCategory");
echo "<tr><td>$ItemCode</td><td>$ItemDesc</td><td align=right>";
echo "$ItemStockQty</td>";
echo "<td align=right>$ItemUnitPrice</td>";
echo "<td>$ItemCategory</td></tr>";
echo "</table></center>";
}
else
{
echo "<form name='DeleteStock2'>";
echo "<p> Sorry, $ItemDesc does not exist!<p>";
echo "<input type='button' value='Leave' onclick='history.go(-1)'>";
}
?>
You aren't actually accessing your data here- you need to iterate over the result set.
$setLength = mysql_num_rows($result);
for($i = 0; $i < $setLength; $i++){
//Here, mysql_fetch_assoc automatically grabs the next result row on each iteration
$row = mysql_fetch_assoc($result);
//do stuff with "row"
}
Unless you ARE doing that and you just chose to not include it in your snippit. Let us know :)
--Edit--
First off, I apologize- out of old habit I suggested that you use mysql_fetch_assoc instead of the mysqli set of functions.
Try using the fetch_assoc or fetch_array functions, it could solve your issue. I've never used the method you used, I think it has been deprecated for a while.
Check it out here:
http://php.net/manual/en/mysqli-result.fetch-assoc.php

Categories