PHP create MySQL query with conditions if/elseif/else - php

I'm new to PHP & MySQL and was trying to use php to create query for MySQL below is the current state of the code and it's still WIP but the if/elseif structure already gives the desired output which varies according to data input, which for example could be as follows
"SELECT * FROM tuntikortti WHERE PVM BETWEEN '2014-09-11' AND '2014-09-27' AND Henkilo =
'Van' AND Tyonumero = '123456' AND Toiminto = '123';"
I've confirmed that the query line itself works in MySQL but I would need to somehow get it inside the MySQL_query($con, The query here).
So how do I get the php output of whole if/elseif query line build in variable or similar to be used?
<?php
include("db_connect.php");
$pvm1 = $_POST['pvm1'];
$pvm2 = $_POST['pvm2'];
$henkilo = $_POST['henkilo'];
$tyonumero = $_POST['tyonumero'];
$toiminto = $_POST['toiminto'];
/* MySQL query line build, beginning */
ECHO "SELECT * FROM tuntikortti WHERE ";
/* PVM */
if(!empty($pvm1) && !empty($pvm2)){
echo "PVM BETWEEN '". $pvm1 ."' AND '". $pvm2 ."'";
} elseif(!empty($pvm1)) {
echo "PVM = '". $pvm1 ."'";
};
/* Henkilo */
if(!empty($henkilo) && !empty($pvm1)){
echo " AND Henkilo = '". $henkilo ."'";
} elseif(!empty($henkilo)) {
echo " Henkilo = '". $henkilo ."'";
};
/* Tyonumero */
if(!empty($tyonumero) && (!empty($pvm1) || !empty($henkilo))){
echo " AND Tyonumero = '". $tyonumero ."'";
} elseif(!empty($tyonumero)) {
echo " Tyonumero = '". $tyonumero ."'";
};
/* Toiminto */
if(!empty($toiminto) && (!empty($tyonumero) || !empty($pvm1) || !empty($henkilo))){
echo " AND Toiminto = '". $toiminto ."'";
} elseif(!empty($toiminto)) {
echo " Toiminto = '". $toiminto ."'";
};
echo ";";
$query = mysqli_query($sql,$con);
echo "<table border='1'>
<tr>
<th>TID</th>
<th>PVM</th>
<th>Henkilo</th>
<th>Tyƶnumero</th>
<th>Toiminto</th>
<th>Tunnit</th>
<th>Selite</th>
</tr>";
while($row = mysqli_fetch_array($query)) {
echo "<tr>";
echo "<td>" . $row['TID'] . "</td>";
echo "<td>" . $row['PVM'] . "</td>";
echo "<td>" . $row['Henkilo'] . "</td>";
echo "<td>" . $row['Tyonumero'] . "</td>";
echo "<td>" . $row['Toiminto'] . "</td>";
echo "<td>" . $row['Tunnit'] . "</td>";
echo "<td class='selitetyyli'>" . $row['Selite'] . "</td>";
echo "</tr>";
}
echo "</table>";
include("db_close_connection.php");
?>

Check this example and try to modify your code,
$sql = '';
$sql = "SELECT * FROM tablename WHERE ";
if(condition){
$sql.= "fieldname = 'value'";
} elseif(condition) {
$sql.= "fieldname = 'value'";
};
$sql.= ";";
$query = mysqli_query($con,$sql);

Related

Search and Sort with MySQL Data in PHP

I'm learning PHP, I create a page to show my data table in MySQL. I want to paging, searching, sorting with that data.
I write some conditions to search and sort. But it's not working. My Paging seem work fine.
<?php
echo "<form action = 'Activiti_Data_Table_Detail.php' method = 'post'>";
echo "<input type = 'text' name = 'valueToSearch' placeholder = 'Value to search'><br><br>";
echo "<input type = 'submit' name = 'search' value = 'Filter'><br><br>";
echo "<input type = 'submit' name = 'ASC' value = 'Ascending'><br><br>";
echo "<input type = 'submit' name = 'DESC' value = 'Descending'><br><br>";
echo "<table id = 'datatable' border='1'>";
echo "<thead>";
echo "<tr>";
echo "<th>ID_</th>";
echo "<th>PROC_INST_ID_</th>";
echo "<th>BUSINESS_KEY_</th>";
echo "<th>PROC_DEF_ID_</th>";
echo "<th>START_TIME_</th>";
echo "<th>END_TIME_</th>";
echo "<th>DURATION_</th>";
echo "<th>START_USER_ID_</th>";
echo "<th>START_ACT_ID_</th>";
echo "<th>END_ACT_ID_</th>";
echo "<th>SUPER_PROCESS_INSTANCE_ID_</th>";
echo "<th>DELETE_REASON_</th>";
echo "<th>TENANT_ID_</th>";
echo "<th>NAME_</th>";
echo "</tr>";
echo "</thead>";
//connect to database
$con=mysqli_connect("localhost","root","123456","activiti") or die(mysqli_connect_errno());
//define how many results per page
$result_per_page = 10;
//number of results stored in database
$sql = "SELECT * FROM act_hi_procinst";
$result = mysqli_query($con, $sql);
$num_of_results = mysqli_num_rows($result); //225
//determine number of total pages available
$number_of_pages = ceil($num_of_results/$result_per_page);
//determine current page is on
if (!isset($_GET['page'])) {
$page = 1;
} else {
$page = $_GET['page'];
}
//determine the SQL LIMIT starting number for the result on the displaying page
$this_page_first_result = ($page - 1) * $result_per_page;
if(isset($_POST['search']) & isset($_POST['ASC'])){
$valueToSearch = $_POST['valueToSearch'];
$sql = "SELECT * FROM act_hi_procinst WHERE concat(ID_, PROC_INST_ID_, PROC_DEF_ID_, START_TIME_, END_TIME_, DURATION_) LIKE '%".$valueToSearch."%'
ORDER BY END_TIME_ ASC LIMIT" .$this_page_first_result . ',' . $result_per_page;
} elseif (isset($_POST['search']) & isset($_POST['DESC'])) {
$valueToSearch = $_POST['valueToSearch'];
$sql = "SELECT * FROM act_hi_procinst WHERE concat(ID_, PROC_INST_ID_, PROC_DEF_ID_, START_TIME_, END_TIME_, DURATION_) LIKE '%".$valueToSearch."%'
ORDER BY END_TIME_ DESC LIMIT" .$this_page_first_result . ',' . $result_per_page;
} elseif (isset($_POST['search'])) {
$valueToSearch = $_POST['valueToSearch'];
$sql = "SELECT * FROM act_hi_procinst WHERE concat(ID_, PROC_INST_ID_, PROC_DEF_ID_, START_TIME_, END_TIME_, DURATION_) LIKE '%".$valueToSearch."%'
LIMIT" .$this_page_first_result . ',' . $result_per_page;
} elseif (isset($_POST['ASC'])) {
$sql = "SELECT * FROM act_hi_procinst ORDER BY END_TIME_ ASC LIMIT" .$this_page_first_result . ',' . $result_per_page;
} elseif (isset($_POST['DESC'])) {
$sql = "SELECT * FROM act_hi_procinst ORDER BY END_TIME_ DESC LIMIT" .$this_page_first_result . ',' . $result_per_page;
} else {
$sql = "SELECT * FROM act_hi_procinst LIMIT" .$this_page_first_result . ',' . $result_per_page;
}
$result = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($result)) {
echo "<tbody>";
echo "<tr>";
echo "<td><a href='Data_Table_Detail.php' target='_blank'>" . $row['ID_'] . "</a></td>";
echo "<td>" . $row['PROC_INST_ID_'] . "</td>";
echo "<td>" . $row['BUSINESS_KEY_'] . "</td>";
echo "<td>" . $row['PROC_DEF_ID_'] . "</td>";
echo "<td>" . $row['START_TIME_'] . "</td>";
echo "<td>" . $row['END_TIME_'] . "</td>";
echo "<td>" . $row['DURATION_'] . "</td>";
echo "<td>" . $row['START_USER_ID_'] . "</td>";
echo "<td>" . $row['START_ACT_ID_'] . "</td>";
echo "<td>" . $row['END_ACT_ID_'] . "</td>";
echo "<td>" . $row['SUPER_PROCESS_INSTANCE_ID_'] . "</td>";
echo "<td>" . $row['DELETE_REASON_'] . "</td>";
echo "<td>" . $row['TENANT_ID_'] . "</td>";
echo "<td>" . $row['NAME_'] . "</td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
echo "</form>";
//display the links to the page
for($page = 1; $page <= $number_of_pages; $page++) {
echo '' . $page . ' ';
}
mysqli_close($con);
?>
When I run this, it say: Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result.
Can you help me?
Thank you!
try change all your ifs for this:
$valueToSearch = isset($_POST['search']) ? $_POST['valueToSearch'] : '';
$orderBy = isset($_POST['ASC']) ? 'ORDER BY END_TIME_ ASC' : (isset($_POST['DESC']) ? 'ORDER BY END_TIME_ DESC' : '');
$sql = "SELECT * FROM act_hi_procinst WHERE concat(ID_, PROC_INST_ID_, PROC_DEF_ID_, START_TIME_, END_TIME_, DURATION_) LIKE '%".$valueToSearch."%' " . $orderBy . " LIMIT " . $this_page_first_result . ',' . $result_per_page;

Fitting table in HTML

I'm trying to design a webpage where it simply shows info from a database using PHP.
I almost solve all of my problem but it's the first time I'm using HTML and I am having trouble finding a solution for my problem.
The code I have so far is:
<?php
$connection = mysql_connect('localhost','XXXX','XXXX');
mysql_select_db('cardata_laptimer');
echo "<table>";
echo "<table border = 1>";
$query = "SELECT * from tempos GROUP BY piloto";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
$query = "SELECT * from tempos WHERE piloto = '" . $row['piloto'] . "' ORDER BY tempo";
$resultado = mysql_query($query);
echo "<td>" . $row['piloto'] . "</td></tr>";
while($rows = mysql_fetch_array($resultado))
{
echo "<td>" . $rows['tempo'] . "</td><td>" . $rows['data'] . "</td></tr>";
}
}
The output I'm getting can be seen in www.cardata.pt
1st problem: How to I make the "piloto" (for example AA) occupy the space of 2 cells?
2nd problem: I want the table to show "pilotos" side by side and the info for each one (tempo and data) down the piloto name.
Thanks in advance
To occupy the space of 2 cells add : colspan="2"
here is my edit of your code :
<?php
$connection = mysql_connect('localhost','XXXX','XXXX');
mysql_select_db('cardata_laptimer');
echo '<table border="0"><tr>';
$query = "SELECT * from tempos GROUP BY piloto";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
echo '<td><table border="1"><tr>';
$query = "SELECT * from tempos WHERE piloto = '" . $row['piloto'] . "' ORDER BY tempo";
$resultado = mysql_query($query);
echo '<td colspan="2">' . $row['piloto'] . "</td></tr><tr>";
while($rows = mysql_fetch_array($resultado))
{
echo "<td>" . $rows['tempo'] . "</td><td>" . $rows['data'] . "</td>";
}
echo '</tr></table></td>';
}
echo '</tr></table>';
?>

PHP mysql query returns a blank screen

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'] . "'";

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.

printing [mysql_query] result in a table

I want to print mysql_query result in a table. I know how to do it but I am just confused. I tried this.
<?php
mysql_connect("localhost","root","") or die("Could not Connect.");
mysql_select_db("check") or die("Could not Select DB");
$table = "cc";
$i = 1;
$query = "select * from $table";
$sql = mysql_query($query);
if($sql){
echo "<table border='5'><tr>";
while($i<=2 && $row = mysql_fetch_array($sql)){
echo "<td>" . $row[id] . " : " . $row[name] . "</td>";
++$i;
}
echo "</tr><tr>";
while($i<=4 && $row = mysql_fetch_array($sql)){
echo "<td>" . $row[id] . " : " . $row[name] . "</td>";
++$i;
}
echo "</tr><tr>";
while($i<=6 && $row = mysql_fetch_array($sql)){
echo "<td>" . $row[id] . " : " . $row[name] . "</td>";
++$i;
}
echo "</tr><tr>";
while($i<=8 && $row = mysql_fetch_array($sql)){
echo "<td>" . $row[id] . " : " . $row[name] . "</td>";
++$i;
}
echo "</tr><tr>";
echo "</tr></table>";
}
?>
As you can see it is written again and again with a slight change of 2,4,6,8 in the while loop. It works but the problem is I cant rewrite it again and again as when the website will go live it will have more than 1000 entries. Could You guys help me out by suggesting another way to do this?
""** I need it to be like these dots (dots represent records in the database) **"""
. . . .
. . . .
. . . .
THANKS in Advance.
Ramzy
<?php
mysql_connect("localhost","root","") or die("Could not Connect.");
mysql_select_db("check") or die("Could not Select DB");
$table = "cc";
$query = "select * from $table";
$sql = mysql_query($query);
if($sql){
echo "<table border='5'><tr>";
while($row = mysql_fetch_array($sql)){
echo "<td>" . $row['id'] . " : " . $row['name'] . "</td>";
}
echo "</tr></table>";
}
?>
while($row = mysql_fetch_array($sql)) {
echo "<td>" . $row['id'] . " : " . $row['name'] . "</td>";
}
I don't really see what's the problem here.
By the way you should never call you're array like this $row[id] but you should quote the key instead $row['id']; Because if a constant id exists it will screw up your code and also for performance reason.
Just use
$limit = 1000;//place any value you need here to limit the number of rows displayed
while ($i<=$limit && $row = mysql_fetch_array($sql)){
echo "<td>" . $row['id'] . " : " . $row['name'] . "</td>";
++$i;
}
Also, that limit is unnecessary if all you want is to flush every record to the output. You could just do
while ($row = mysql_fetch_array($sql)){
echo "<td>" . $row['id'] . " : " . $row['name'] . "</td>";
}
And it will stop as soon as there are no more records.
To print all database rows into an HTML-table, use:
echo '<table>';
$i = 0; // $i is just for numbering the output, not really useful
while($row = mysql_fetch_array($sql))
{
echo '<tr><td>' . $i . ' - ' . $row['id'] . ' : ' . $row['name'] . '</td></tr>';
$i++;
}
echo '</tr></table>';
here is a general function I use:
function query_result_to_html_table($res, $table_id = NULL, $table_class = NULL, $display_null = true)
{
$table = array();
while ($tmp = mysql_fetch_assoc($res))
array_push($table, $tmp);
if (!count($table))
return false;
echo "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" "
. ($table_id ? "id=\"$table_id\" " : "")
. ($table_class ? "class=\"$table_class\" " : "") . ">";
echo "<tr>";
foreach (array_keys($table[0]) as $field_name) {
echo "<th>$field_name";
}
foreach ($table as $row) {
echo "<tr>";
foreach ($row as $col => $value) {
echo "<td>";
if ($value === NULL)
echo "NULL";
else
echo $value;
}
echo "\n";
}
echo "</table>\n";
return true;
}
I Got The Answer.. I wanted it to be like this. I made this and It Actually Works.
<?php
$i = 1;
mysql_connect("localhost" , "root" , "") or die('Could not Connect.');
mysql_select_db("db") or die('Could not select DB.');
$query = "select * from `check`";
$sql = mysql_query($query) or die(mysql_error());
echo "<table border='5' width='50%'><tr><th>Name</th><th>Gender</th></tr></table><table border='5' width='50%'><tr>";
if($i<3){
echo "<td align='center'>".$row['name']."</td>";
echo "<td align='center'>".$row['gender']."</td>";
++$i;
} else {
echo "<td align='center'>".$row['name']."</td><td align='center'>".$row['gender']."</td>";
echo "</tr>";
$i = 1;
echo "<tr>";
}
}
echo "</table>";
?>
</div>
Thank You Guys For Your Support

Categories