My array won't echo a value for some reason - php

I have a database that holds thousands of structures. The structures are searchable by choosing the "area" first, then selecting the "block_number". My first page allows the user to select the area, the area is then passed through the url to the next page. The next page uses php to pull up the blocks in that area. I'm trying to echo the "area" and "block_number" in the results. The my query works just fine but, for some reason I can't display the "area" in the results. See the code below.
<?
include("conn.php");
include("pl_header.php");
$area = mysql_real_escape_string($_GET['area']);
$wtf = '$area';
?>
<h3>Choose A Block Number in<br> <?=$area?></h3><br>
<center>
<?php
$tblWidth = 1;
$sql = mysql_query("SELECT DISTINCT block_number FROM platform_locations WHERE area='$area'");
$i = 1;
// Check to see if any results were returned
if(mysql_num_rows($sql) > 0){
echo '<div class="redBox extraIndent">';
// Loop through the results
while($row = mysql_fetch_array($sql)){
echo ''. $row['area'] .''. $row['block_number'] .'';
if($i == $tblWidth){
echo '';
$i = 0;
}
$i++;
}
echo '';
}else{
echo '<br>Sorry No Results';
}
?>
</div>
</body>
</html>
My issue is where you see '. $row['area'] .' displays nothing, but the '. $row['block_number'] .' works just fine.

Your query is only selecting block_number.
Try changing:
$sql = mysql_query("SELECT DISTINCT block_number FROM platform_locations WHERE area='$area'");
To:
$sql = mysql_query("SELECT DISTINCT block_number, area FROM platform_locations WHERE area='$area'");
Edit: If you have this issue in the future try var_dump($row); to see what the array contains. This would show you that you only have access to the block_number and not the area.
Double edit: I didn't notice, but the other answer is right about the $area var- you've already got the $area saved, use that variable instead of the return from the DB as it's already in memory. If this could change per record, it'd be prudent to use the record's area variable to make your code more reusable. However, in this particular case, your SQL statement has the area in the where clause, so it wont vary unless you attempt to use portions of this code elsewhere.

Your SQL query is only selecting block_number, so that's the only field that will be in the $row array. You've already got area as a variable $area so use that, not $row['area'].

Related

PHP INSERT a variable number of records to mysql from a html form

I have a HTML form that retrieves a varying number product types that the user inputs stock figures. This data then needs to be INSERTED to a new table.
Here is the PHP query that populates the form.
require_once 'config.php';
$i = 1;
$sql = "SELECT * FROM dealer_product WHERE customer_code='$custcode' ORDER BY prod_code";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
$prodcode = $row['prod_code'];
echo "<tr><td><input type='text' name='prod".($i++)."' value='" . $prodcode . "'/></td><td><input type='number' name='openstock".($i++)."'/></td><td><input type='number' name='sold".($i++)."'/></td></tr>";
}
mysql_close($con);
?>
I know how to INSERT a set number of multiple records, but how do I INSERT a varying number of records?
Thanks in advance. Sorry for my basic knowledge, I'm a network admin not PHP MYSQL.
Name your input fields as if they were arrays, e.g.:
<input name="prods[0]" />
You can then output a variable number of inputs in your HTML, even add more with JavaScript. PHP will convert the input to an array over which you can iterate:
<?php
foreach ($_POST['prods'] as $prod) {
/* Process $prod */
}
?>
I recommend that you go in the same way but using
while ($row = mysql_fetch_assoc($result))
And now you have not numbers as index that is more complicated way to see things, better see associative way that's the column name from your table in mysql.
And you're doing a lot of increments there doing $i++ a lot of times. I don't know if you're doing that intentionally but if not just increment $i once.
Also the number of row can be reached using this:
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
Look inside the manual
http://us1.php.net/mysql_fetch_assoc

Echo each record of a query result

I'm attempting to extract some data from a database and echo each result. The code below is code that I took from a textbook and then tried to modify to fit my own website that is hosted locally. I cannot see where I'm going wrong, no error messages are shown, just a blank screen when I run the scrip.
<?php #script 9.4 view top 5 recipients
// This script exctracts data from db and then displays each record in a table
DEFINE('SYSPATH','FOO');
require '../application/config/database.php';
require 'mysqli_connect.php';
$q = "SELECT alert_recipient as NAME
FROM alert
LIMIT 5;
";
$r = mysqli_query($dbc,$q);
// $dbc database connection comes from required mysqli_connect.php
if($r)
{
while($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
echo $row['name'];
}
}
else {
echo "<p>ERROR</p>".mysqli_error($dbc);
}
?>
The code looks okay except for your echo $row['name'];, note that you are selecting NAME, uppercase.
Change your echo statement to be:
echo $row['NAME'];
because field names quoted within $row array are case sensitive.
(Can't comment yet)
Maybe the script works but there is no results to display. Check your database.

Nested while loop in PHP is not working for MySQL database queries

All the whole day I'm trying to solve this problem but still no luck.
The scenario is: I am developing a vertical menu which should query groups and items of those groups in a menu respectively, but groups are being populated without its items.
Code was written in the following way:
$data1 = mysql_query(select groupnames from groups where categoryy='Agriculture');
while($info1=mysql_fetch_array($data1))
{
echo $info1[0];
$data2==mysql_query(select itms from groupitems where categoryy='Agriculture' and groupname='$info1[0]');
while($info2=mysql_fetch_array($data2))
{
echo $info2[0];
}
}
In the above code, groups are being populated nicely but no items from groupitems table are being populated. If I write Grain (Grain is one of the group of agriculture in my database) instead of groupname=$info1[0] then it works. But it should be got dynamically from the query.
Please help, I'm in trouble.
at last its solved! here's the code:
<?php
include "aPannel/dbconn.php";
$query="select GroupName from categorygroup where categoryy='Agriculture'";
$i=0;
$result=mysql_query($query);
$num=mysql_num_rows($result);
$groupname=mysql_result($result ,$i ,"GroupName");
mysql_close();
if ($num=="0") echo "<p>Sorry, there are no groups to display for this Category.</p>";
else
{
echo "<p>There are currently <strong>$num</strong> groups represented in our database.</p><br>";
while($i < $num)
{
$groupname=mysql_result($result ,$i ,"GroupName");
include("aPannel/dbconn.php");
$query2 = "SELECT subcategory FROM groupsubcategory WHERE groupname='$groupname'"; // count number of items in each group
echo $query2 . "<br/>";
$resultt=mysql_query($query2);
$countt=mysql_num_rows($resultt);
mysql_close();
echo $countt . "subcategories" . "<br/>"; // display number of items
$i++;
}
} // end if results
?>
Your queries are not wrapped around double-quotes (" ") . Always remember that what you pass to mysql_query method is a string argument. And also $data2==.... seems wrong.
So, change the code like this
$data1=mysql_query("select groupnames from groups where categoryy='Agriculture'");
while($info1=mysql_fetch_array($data1))
{
echo $info1[0];
$infoTemp=$info1[0];
$data2=mysql_query("select itms from groupitems where categoryy='Agriculture'
and groupname='$infoTemp'");
while($info2=mysql_fetch_array($data2))
{
echo $info2[0];
}
}
I hope it should work
EDIT: Also are you sure column itms in second query or items ?
EDIT: added temporary variable

Need a Pagination PHP code to integrate with my SEARCH php script

It's been a month and am really messed up trying to integrate a php pagination code to my search script. Referred to most of the tutorials Googling, but in vain. Any help would be much appreciated. Here I go...
<?php
ob_start();
session_start();
$_GET['term'] = trim($_GET['term']);
$output = preg_replace('!\s+!', ' ', $_GET['term']);
if(empty($_GET['term'])|| preg_match("/^[#!#\$\^%&*()+=\-\[\]\\\';,\.\/\{\}\|\":<>\?\ _ ]+$/i", $_GET['term']) || $output== ' ' || $_GET['term']== "%24_GET%5B%27term%27%5D")
{
echo "<BR>";
echo "<BR>";
echo("Please enter a Valid Search term");
}
else
{
mysql_connect("localhost", "root", "root");
mysql_select_db("search");
$_GET['term'] = explode(' ', $_GET['term']);
foreach($_GET['term'] AS $_GET['term'])
{
$_GET['term'] = trim($_GET['term']);
$sql = mysql_query("SELECT DISTINCT * FROM searchengine WHERE pagecontent LIKE '%" . str_replace(' ', "%' AND pagecontent LIKE '%", $_GET['term'])."%' LIMIT 0,10");
while($ser = mysql_fetch_array($sql)) {
echo "<BR>";
echo "<b><u><a href='$ser[pageurl]'>$ser[title]</a></u></b>";
echo "<BR>";
echo("<span class='style_block'>{$ser['pagecontent']}</span>");
echo "<BR>";
echo ("<a href='$ser[pageurl]'>$ser[pageurl]</a>");
echo "<BR>";
echo "<BR>";
}
}
$count=mysql_num_rows($sql);
if($count==0)
{
echo "<BR>";
echo "<BR>";
echo "Sorry, No News material was found... Please refine your search criteria and try again.";
}
}
?>
Apart from the problems Luc M has mentioned in his comment (which you should certainly resolve before moving forward), you are almost there.
You need to consider a couple of points, really: How many records to display per page, and what page you are on. These will dictate the records you need to retrieve and display. So, how do you go about this?
The first point is covered in your code already through use of the LIMIT clause in your SQL query. The second point is a tiny bit more complex to start with. You need a way of identifying the page you are on. This is probably easiest to identify through a GET variable, for example http://site.com/search.php?page=2. Now, for implementing this, you want something along these lines:
$recordsPerPage = 10; // although you may want to have this as a GET or POST variable as well, so the user can decide
if(isset($_GET['page']) // this ensures a default value
{
$currentPage = $_GET['page'];
}
else
{
$currentPage = 1;
}
Then, for your SQL query, you want to build something like this:
$query = "SELECT * FROM table_name LIMIT " . $recordsPerPage . " OFFSET " . ($currentPage - 1)*$recordsPerpage . ";";
The OFFSET clause of SQL along with LIMIT basically says "Select this many records, starting from result number x". You offset on $currentPage - 1 because the first page doesn't want an offset, and the second page only wants an offset of however many records were shown on the first page, so on and so forth.
To create navigation for the paginated data, you want to find out how many records are in your result set, which can be done through the count($array) function of PHP. Then, to find the number of pages, simply use something like:
$numPages = ceil(count($array)/$recordsPerPage);
Where $array is your dataset from the SQL query. The ceil() function rounds the result up to the next integer.
Once you have this result, you simply need to output links to each page, which can be done simply with a for loop:
for($i = 0; i < $numPages; i++)
{
echo '<a href="/search.php?page="' . $i+1 . '>' . $i+1 . '</a>';
}
To create first, previous, next and last page links, you need to do something like:
$firstPage = 1;
$previousPage = $currentPage - 1; // you may want to check here or elsewhere to make sure you have no page zero
$nextPage = $currentPage + 1; // may also want to make sure you don't go past the last page
$lastPage = $numPages;
These values can then be put into your generated links.
Again, I will refer you to Luc M's comment... These need to be fixed, take a look at mysqli functions instead of the now-deprecated mysql_*() functions you're currently using, make sure you clean any user-inputted data before using it, and consider looking at the MVC design pattern.
Hopefully, this will help you out.

Selecting one value from an array called by a query in PHP

Basically I have a query called using PHP:
<?php $result = mssql_query("SELECT * FROM Colours WHERE Type = 'type1' ");
while ($row = mssql_fetch_array($result)) {
if ($row['ColourID'] == "1") {
$sayclass1="imgactive";
}else{
$sayclass1="imginactive"; }
?>
As you can see once I execute the query I then loop it, the problem is that it returns an array, now in some instances I need to use the full array, but I would like to be able to select one entry from it for if statements and such. For example:
<img id="h" src="<?php echo $row['thumbimg']; ?>
now thumbimg is a column in my DB, and it just holds a url. However due to the fact its an array the picture doesn't display because its echoing all the values, so instead of images/image1.png for example it is echoing images/image1.png images/image2.png images/image3.png etc etc...
I hope that makes sense, and can anyone tell me how to manipulate the query/code slight to still return all the entries but to select certain values from the arrays please?
You need to use the img tag with in for each if you want to show all the images
foreach($row[thumbimg] as $img):
<img id="h" src="<?php echo $img; ?>
end foreach;
<?php $result = mssql_query("SELECT * FROM Colours WHERE Type = 'type1' ");
while ($row = mssql_fetch_array($result)) {
if ($row['ColourID'] == "1") {
$sayclass1="imgactive";
}else{
$sayclass1="imginactive";
}
echo '<img id="h" src="'.$row['thumbimg'].'">';
}
?>
Using this above code, you will get one image per line from the database. The part of code you have copy-pasted is not enough to determine where your mistake is and why $row['thumbimg'] contains a concatenated value of the result.

Categories