PHP mysql query returns a blank screen - php

I've commented out the bottom part, and the SQL query works fine. Its the displaying of the query where the error is coming from i believe.
$host = "127.0.0.1";
$user = "root";
$pass = "Toom13371!";
$connection = mysql_connect($host,$user,$pass) or die (mysql_errno().": ".mysql_error()."<BR>");
// 2. Selecting DB.
$dbname = "filters";
mysql_select_db($dbname);
// 3. Build/Test SQL Query
$sql = ("select * from filter_bandpass where start_passband=" . $_POST['Lowfreq'] . " and stop_passband='" . $_POST['Highfreq'] . "'");
//echo $sql; //Comment/Uncomment to test sql query.
// 4. Retrieve info from MySQL.
$query = mysql_query($sql);
// 5. Display Query.
echo "<table border='1'>
<tr>
<th>Low Frequency</th>
<th>High Frequency</th>
</tr>";
while($row = mysql_fetch_array($query)) {
echo "<tr>";
echo "<td>" . $row['Lowfreq'] . "</td>";
echo "<td>" . $row['Highfreq'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
Any help would be appreciated, I'm sure it's going to be some small stupid error i've over looked.
Thanks in advance :)

I'm guessing, based on your query, that you need to change this
mysql_select_db($dbname);
to
mysql_select_db($dbname, $connection);
and
while($row = mysql_fetch_array($query)) {
echo "<tr>";
echo "<td>" . $row['Lowfreq'] . "</td>";
echo "<td>" . $row['Highfreq'] . "</td>";
echo "</tr>";
}
to
while($row = mysql_fetch_array($query)) {
echo "<tr>";
echo "<td>" . $row['start_passband'] . "</td>";
echo "<td>" . $row['stop_passband'] . "</td>";
echo "</tr>";
}

Change line
mysql_select_db($dbname);
to
mysql_select_db($dbname, $connection);
Also before query check
$_POST['Lowfreq'] and $_POST['Highfreq']
If there is no value in these variables query will must return empty.

In your query there should not brackets for string.
$sql = ("select * from filter_bandpass where start_passband=" . $_POST['Lowfreq'] . " and stop_passband='" . $_POST['Highfreq'] . "'");
should be:
$sql = "select * from filter_bandpass where start_passband=" . $_POST['Lowfreq'] . " and stop_passband='" . $_POST['Highfreq'] . "'";

Related

php - search form with drop down

I am trying to create a basic advanced search with an input which will then search through any results that have a matching category field that is selected in the dropdown and then also a matching keyword field for company_name in "advancedSearch". I have gotten to the stage where I can use the drop down to then display the matching data but I’m having trouble querying that with the search input.
Here is my form code from index.php
<form action="advanced-search.php" method="POST">
<input id="advancedInput" placeholder="Advanced Search" type="search" name="advancedSearch">
<?php
$sqlSelect="SELECT category FROM categories";
$result = $db -> query ($sqlSelect);
echo "<select id=\"selectAdvanced\" name=\"value\">";
echo "<option></option>";
while ($row = mysqli_fetch_array($result)) {
$rows[] = $row;
}
foreach ($rows as $row) {
print "<option value='" . $row['category'] . "'>" . $row['category'] . "</option>";
}
echo "</select>";
?>
<input type="submit" value="search"/>
</form>
And here is the code from my advanced-search.php
<?php
if(isset($_POST['value']) && !empty($_POST['value'])) {
$username = trim(strip_tags($_POST['value']));
include('dbConfig.php');
if (mysqli_connect_errno()) {
printf("Can't connect: %s\n", mysqli_connect_error());
exit();
}
$where = ($username == "category")? "" : " WHERE category = '$username'";
$sql = "SELECT * FROM company_listings" . $where; // Create Query
$result = mysqli_query($db, $sql); // Run Query
echo "<table border=1><tr><th>id</th><th>name</th><th>created</th></tr>";
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['company_name'] . "</td>";
echo "<td>" . $row['created'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_free_result($result);
}
This code works great for echoing out the matching categories from the dropdown but I cant work out how I would further query the search from the "advanced search" input.
Any help would be greatly appreciated.
I worked out that using AND in my query like this and using the Request on submit I was able to get what I was after... Thanks to #ADyson for the nudge. I have added my updated advanced-search.php file below;
if(isset($_REQUEST['submit'])){
$username = (($_POST['value']));
$advanced = (($_POST['advancedSearch']));
include('dbConfig.php');
if (mysqli_connect_errno()) {
printf("Can't connect: %s\n", mysqli_connect_error());
exit();
}
$sql=" SELECT * FROM company_listings WHERE company_name like '%".$advanced."%' AND category LIKE '%".$username."%'";
$result = mysqli_query($db, $sql); // Run Query
echo "<table border=1><tr><th>id</th><th>name</th><th>created</th></tr>";
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['company_name'] . "</td>";
echo "<td>" . $row['created'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_free_result($result);
}

How do I hide entire row if a certain cell in that row is empty?

I've been stuck with this for a while now. How do I hide a row if the second columns (svar) cell is empty on all rows where the cells under svar is not filled in?
Here is my code so far:
PHP
$localhost = "localhost";
$username = "root";
$password = "";
$connect = mysqli_connect($localhost, $username, $password)or
die("Kunde inte koppla");
mysqli_select_db($connect, 'wildfire');
$result = mysqli_query($connect,"SELECT * FROM question");
echo "<table border='1'>
<tr>
<th>Fråga</th>
<th>Svar</th>
<th>Poäng</th>
<th>Redigera</th>
<th>Radera</th>
<th>AID</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['qid'] . "</td>";
echo "<td>" . $row['answer'] . "</td>";
echo "<td>" . $row['Point'] . "</td>";
echo "<td>Redigera</td>";
echo "<td>Ta bort</td>";
echo "<td>" . $row['aid'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($connect);
JQuery
var t = $('table').parent().children().find("td:nth-child(2):empty").parent().hide();
I would update the query so you only return the records you want displayed. So change:
$result = mysqli_query($connect,"SELECT * FROM question");
to
$result = mysqli_query($connect,"SELECT * FROM question where answer <> '' && answer IS NOT NULL");
You can try this:
$('td:nth-child(2):empty').closest('tr').hide();
Here is the FIDDLE.

Run Query in PHP to display in table

I'm trying to create a league table, the query works in phpmyadmin. But I cannot display it in a table using php.
I think the issue is that I'm not running the query the correct way. When I run the code I get "league table query not populated"
Please can you give some advice on running this:
<?php
$sql =
"SELECT player_name,
SUM(win+draw+lose) AS Played,
SUM(win) AS Won,
SUM(draw) AS Drawn,
SUM(lose) AS Lost,
SUM(`for`) AS `Goals For`,
SUM(`against`) AS `Goals Against`,
SUM(cast(`for`AS SIGNED) - cast(`against`AS SIGNED)) AS `Goal Difference`,
SUM((win*3)+(draw)+extra_points) AS Points,
ROUND((SUM((win*3)+draw))/SUM((win+draw+lose)*3)*100,1) AS Record
FROM appearances
WHERE season_id = 4
GROUP BY player_name
ORDER BY Points DESC,
Played ASC,
`Goal Difference` DESC, `Goals For` DESC,
player_name ASC[...]";
if (!$sql) {
echo 'sql query has not worked';
}else {
$leaguetable = mysql_query($sql);
if (!$leaguetable){
echo 'league table query not populated';
} else {
$records = mysql_fetch_array($leaguetable);
If (!$records) {
echo 'records have not been placed in assoc array';
}
else {
echo "<tr width='600'>";
echo "<td>" . $records["player_name"] . "</td>";
echo "<td>" . $records["Played"] . "</td>";
echo "<td>" . $records["Won"] . "</td>";
echo "<td>" . $records["Drawn"] . "</td>";
echo "<td>" . $records["Lost"] . "</td>";
echo "<td>" . $records["Goals For"] . "</td>";
echo "<td>" . $records["Goals Against"] . "</td>";
echo "<td>" . $records["Goal Difference"] . "</td>";
echo "<td>" . $records["Points"] . "</td>";
echo "<td>" . $records["Record"] . "</td>";
echo "</tr>";
//while ($records = mysql_fetch_assoc($sql));
}
}
}
?>
When I run the above I get "league table query not populated"
Thanks in advance for your help
I've just tried the PDO method and its still not displaying the records, i believe there is a database connection, here's the code
<?php
require 'pdoconnect.php';
$db = new PDO('mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['dbname'], $config['db']['username'], $config['db']['password']);
$stmt = $db->prepare("SELECT player_name,
SUM(win+draw+lose) AS Played,
SUM(win) AS Won,
SUM(draw) AS Drawn,
SUM(lose) AS Lost,
SUM(`for`) AS `Goals For`,
SUM(`against`) AS `Goals Against`,
SUM(cast(`for`AS SIGNED) - cast(`against`AS SIGNED)) AS `Goal Difference`,
SUM((win*3)+(draw)+extra_points) AS Points,
ROUND((SUM((win*3)+draw))/SUM((win+draw+lose)*3)*100,1) AS Record
FROM appearances
WHERE season_id = 4
GROUP BY player_name
ORDER BY Points DESC,
Played ASC,
`Goal Difference` DESC, `Goals For` DESC,
player_name ASC[...]");
$stmt->execute();
$result = $stmt->fetchAll(pdo::FETCH_ASSOC);
while($row = $result){
echo "<tr width='600'>";
echo "<td>" . $row['player_name'] . "</td>";
echo "<td>" . $row['Played'] . "</td>";
echo "<td>" . $row['Won'] . "</td>";
echo "<td>" . $row['Drawn'] . "</td>";
echo "<td>" . $row['Lost'] . "</td>";
echo "<td>" . $row['Goals For'] . "</td>";
echo "<td>" . $row['Goals Against'] . "</td>";
echo "<td>" . $row['Goal Difference'] . "</td>";
echo "<td>" . $row['Points'] . "</td>";
echo "<td>" . $row['Record'] . "</td>";
echo "</tr>";
//while ($records = mysql_fetch_assoc($sql));
}
?>
Please replace this statement
$leaguetable = mysql_query($sql);
with
$leaguetable = mysql_query($sql) or die(mysql_error());
to check the reason due to which query failed
Not a real andwer and I don't know which version of PHP you are using but you might consider the warning on http://php.net/manual/en/function.mysql-query.php
This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used.
you can do somting like this..
<!doctype html>
<html>
<head></head>
<body>
<table>
<tr>
<?php
header('Content-Type: text/html; charset=UTF-8');
mysql_connect("localhost", "user", "password");
mysql_select_db("alarm");
mysql_query( "SET NAMES utf8" );
mysql_query( "SET CHARACTER SET utf8" );
$dave = mysql_query("select blablabla as ab");
while ($row = mysql_fetch_assoc($dave)) {
echo $row['ab'];
echo "<td>";
.
. put where you want..
.
echo "<tr>";
}
?>
</body>
</html>
You have to connect to your database before issuing any query to it:
Try this on the beginning of your script (replace localhost, mysql_user and mysql_password with your servers data):
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_link= mysql_select_db('database_name', $link);
if (!$db_link) {
die ('Can\'t use database_name: ' . mysql_error());
}
See http://php.net/manual/en/function.mysql-connect.php
And http://php.net/manual/en/function.mysql-select-db.php for more detail.

PHP - SQL select Data display

<html>
<head>
<meta http-equiv = "content-type" content = "text/html; charset = utf-8" />
<title>Using file functions PHP</title>
</head>
<body>
<h1>Web Development - Lab05</h1>
<?php
require_once("settings.php");
$dbconnect = #mysqli_connect($host, $user, $pswd, $dbnm);
if($dbconnect->connect_errno >0)
{
die('Unable to connecto to database [' . $db->connect_error . ']');
}
$queryResult = "SELECT car_id, make, model, price FROM cars";
echo "<table width='100%' border='1'>";
echo "<tr><th>ID</th><th>Make</th><th>Model</th><th>Price</th></tr>";
//initiate array
$displayrow= mysqli_fetch_array($queryResult);
//initiate while loop to iterate through table
while($displayrow)
{
echo "<tr>";
echo "<td>" . $row['ID'] . "</td>";
echo "<td>" . $row['Make'] . "</td>";
echo "<td>" . $row['Model'] . "</td>";
echo "<td>" . $row['Price'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($dbconnect);
?>
</body>
</html>
This is doing my head in, I cannot figure out why it will not display the actual data apart from the Table header. No matter what I used.
I have tried mysqli_fetch_array, mysqli_fetch_row, mysqli_fetch_assoc but nothing works.
Help and explanation why it was not displaying the data would be much appreciated :)
First: You aren't running a query, you are only putting the query text in a variable. You need to use mysqli_query.
Second: You should add mysqli_fetch_array to the loop.
For example:
while($displayrow = mysqli_fetch_array($queryResult))
{
}
Otherwise you are only getting the first row.
Third: Array keys are case sensitive. There is no $row['ID'], as Jeribo pointed out, it is $row['car_id'] as referenced in your query. $row['Make'] is not the same as $row['make'].
Please Precision to names of field in Query ( car_id,make,...)
while($displayrow= mysql_fetch_assoc($queryResult) )
{
echo "<tr>";
echo "<td>" . $displayrow['car_id'] . "</td>";
echo "<td>" . $displayrow['make'] . "</td>";
echo "<td>" . $displayrow['model'] . "</td>";
echo "<td>" . $displayrow['price'] . "</td>";
echo "</tr>";
}
If you want to query outside you still have to set it in the loop:
$result = $db->query($queryResult)
while($row = $result ->fetch_assoc()){
...
}
a Good Tutorial is shown here: http://codular.com/php-mysqli
$row needs to be initialized so why don't you try:
while($row = mysqli_fetch_array($queryResult))
{
....
}
You have to get the result set first and then try fetching array from result set
<?php
require_once("settings.php");
$dbconnect = #mysqli_connect($host, $user, $pswd, $dbnm);
if($dbconnect->connect_errno >0)
{
die('Unable to connecto to database [' . $db->connect_error . ']');
}
$query = "SELECT car_id, make, model, price FROM cars";
$resultSet=mysqli_query($dbconnect,$query)
echo "<table width='100%' border='1'>";
echo "<tr><th>ID</th><th>Make</th><th>Model</th><th>Price</th></tr>";
//initiate array
$displayrow= mysqli_fetch_array( $resultSet);
//initiate while loop to iterate through table
while($displayrow)
{
echo "<tr>";
echo "<td>" . $row['ID'] . "</td>";
echo "<td>" . $row['Make'] . "</td>";
echo "<td>" . $row['Model'] . "</td>";
echo "<td>" . $row['Price'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($dbconnect);
?>
http://www.w3schools.com/php/func_mysqli_fetch_array.asp

Select Statement Not Working ("mysql_fetch_array(): supplied argument is not a valid")

Error:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in E:\webareas\ie803\projectx\search.php on line 306
My php code is as follows:
<?php
$car = mysql_real_escape_string($_REQUEST['car']);
$model = mysql_real_escape_string($_REQUEST['model']);
$type = mysql_real_escape_string($_REQUEST['type']);
$colour = mysql_real_escape_string($_REQUEST['colour']);
$year = mysql_real_escape_string($_REQUEST['year']);
$price = mysql_real_escape_string($_REQUEST['price']);
$con = mysql_connect("--","---","---");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('-----', $con);
$sql = "SELECT * FROM Cars WHERE Make ='$car', Model ='$model', Type ='$type', Colour = '$colour', Year = '$year', Price = '$price'";
$result=mysql_query($sql, $con);
{
while($info = mysql_fetch_array($result)){
echo "<tr>";
echo "<td>" . $info['Make']. "</td>";
echo "<td>" . $info['Model']. "</td>";
echo "<td>" . $info['Type']. "</td>";
echo "<td>" . $info['Colour']. "</td>";
echo "<td>" . $info['Year']. "</td>";
echo "<td>" . $info['Price']. "</td>";
echo "<br/><br/><td>" . '<hr>' . "</td>";
}
}
echo "</tr>";
echo "</table>";
?>
line 306 is the while statement. I keep on getting errors after each change I make.
The select statement is just a string, you have to feed it through mysql_query to get the result set, it is typically done as follows:
$sql = "SELECT * FROM Cars WHERE Make ='$car', Model ='$model', Type ='$type', Colour = '$colour', Year = '$year', Price = '$price'";
$result=mysql_query($sql, $con);
You need to use mysql_query before mysql-fetch-aarray. See this page for example of how to do this
I don't think that your query is even being executed. I've never seen the syntax of WHERE [column], [column], [column] before.
Try:
SELECT * FROM Cars WHERE Make ='$car' AND Model ='$model' AND Type ='$type' AND Colour = '$colour' AND Year = '$year' AND Price = '$price'
I've added some error checking so that you can see whatever mysql errors you get, if the syntax was correct.
$sql = "SELECT * FROM Cars WHERE Make ='$car', Model ='$model', Type ='$type', Colour = '$colour', Year = '$year', Price = '$price'";
$result=mysql_query($sql, $con);
if($result)
{
while($info = mysql_fetch_array($result)){
echo "<tr>";
echo "<td>" . $info['Make']. "</td>";
echo "<td>" . $info['Model']. "</td>";
echo "<td>" . $info['Type']. "</td>";
echo "<td>" . $info['Colour']. "</td>";
echo "<td>" . $info['Year']. "</td>";
echo "<td>" . $info['Price']. "</td>";
echo "<br/><br/><td>" . '<hr>' . "</td>";
}
else {
die(mysql_error();
}
You don't have mysql_query(), try
$sql = "SELECT * FROM Cars WHERE Make ='$car', Model ='$model', Type ='$type', Colour = '$colour', Year = '$year', Price = '$price'";
$result = mysql_query($sql) or die("ERROR: ".mysql_error());
EDIT
I put in the or die statement to help with debug, you can remove it at any time you wish. I personally find it makes it easier.

Categories