Trouble pulling data out of an sql table - php

I have a html form tat my user can use to search through a table in my MYSQL database.
By default if you just hit go it will display the entire table, however I would like them to be able select certain fields and my php form to search via the fields that are filled in.
I seem to be unable to find a way of doing this without writing a seperate query for all 11 inputs in the different combinations they could be entered in, which comes out at a total of 76 queries..
If anyone has a way to simplify this I would love any advice.
I have tried just running a query with the AND operator but that doesnt work as some variables can be left empty and that will return no result, not sure if that is what is upposed to happen, but that is what is happening.
my html and php:
http://jsbin.com/oquwid/1/edit
PHP
$sql = "SELECT * FROM ".$tbl_name."
WHERE fname='".$fname."'
and lname='".$lname."'
and city='".$city."'
and phone='".$pohne."'
and interest_inet='".$internet."'
and interest_tv='".$television."'
and interest_voice='".$voice."'
and submission_ip='".$ip."'
and inquiry_handled='".$handled."'";
$result = mysql_query($sql);
echo "<table border='1'>";
echo "<tr>";
$i = 0;
while ($i < mysql_num_fields($result))
{
$meta = mysql_fetch_field($result, $i);
echo "<th>".$meta->name."</th>";
$i++;
}
while ($row = mysql_fetch_row($result))
{
echo '<tr>';
foreach($row as $item)
{
echo "<td>".$item."</td>";
}
echo '</tr>';
echo $row;
}
echo "</table>";

You could append parts to the query depending on which are filled in:
if(!empty($fname) || !empty($lname) || !empty($city) || etc.etc.) {
$sql = "SELECT * FROM $tbl_name WHERE ";
$queryParts = array();
if($fname != "") {
$queryParts[] = " fname='$fname'";
}
if($lname != "") {
$queryParts[] = " lname='$lname'";
}
etc.etc.
$sql .= implode(" AND ", $queryParts);
// do query, etc.
}
else {
// Don't do query if no parameters are specified
}
You also need to make sure that you escape all of your query parameters before you use them or risk having someone ravage your data.
The following uses loops to avoid duplicate code:
$fieldIsSpecified = false;
$queryFields = array('fname' => $fname, 'lname' => $lname, 'city' => $city, etc...);
foreach($queryFields as $column => $value) {
if(!empty($value){
$fieldIsSpecified = true;
break;
}
}
if($fieldIsSpecified) {
$sql = "SELECT * FROM $tbl_name WHERE ";
$queryParts = array();
foreach($queryFields as $column => $value) {
if(!empty($value)) {
$queryParts[] = " $column = '$value'";
}
}
$sql .= implode(" AND ", $queryParts);
// do query, etc.
}
else {
// Don't do query if no parameters are specified
}

The reason you're query isn't working if a value is not filled in, is probably because the query results in this (given first name is empty)
SELECT * FROM $tbl_name WHERE fname=''
And there probably isn't a user having no first name.
Further, you considered adding a flag per requested info, and on base of that either add or remove the needed part to the select part of the query ?
For example,
$sql = "SELECT * FROM $tbl_name WHERE ";
$queryChanged = false;
if (isset($fname)){
if (!empty($fname)){
$sql .= "fname='$fname' ";
$queryChanged=true;
}
}
if (isset($lname)){
if (!empty($lname)){
$sql .= ($queryChanged) ? " AND lname='$lname'" : "lname='$lname'";
$queryChanged = true;
}
}
... //Continue the logic
I'd recommend you to read this post about select * as well as this about user input and how to handle it

this is how i am going to have to do it
php:`
//if just lname is set
if(empty($start_date) && empty($end_date) && empty($fname) && isset($lname) && empty($city) &&
empty($internet) && empty($television) && empty($voice) && empty($phone) && empty($ip) &&
empty($handled) && empty($not_handled)){
$sql = "SELECT * FROM ".$tbl_name."
WHERE lname='".$lname."'";
$result = mysql_query($sql);
echo "<table border='1'>";
echo "<tr>";
$i = 0;
while ($i < mysql_num_fields($result))
{
$meta = mysql_fetch_field($result, $i);
echo "<th>".$meta->name."</th>";
$i++;
}
while ($row = mysql_fetch_row($result))
{
echo '<tr>';
foreach($row as $item)
{
echo "<td>".$item."</td>";
}
echo '</tr>';
}
echo "</table>";
exit();
}
//if just city is selected
if(empty($start_date) && empty($end_date) && empty($fname) && empty($lname) && isset($city) &&
empty($internet) && empty($television) && empty($voice) && empty($phone) && empty($ip) &&
empty($handled) && empty($not_handled)){
$sql = "SELECT * FROM ".$tbl_name."
WHERE city='".$city."'";
$result = mysql_query($sql);
echo "<table border='1'>";
echo "<tr>";
$i = 0;
while ($i < mysql_num_fields($result))
{
$meta = mysql_fetch_field($result, $i);
echo "<th>".$meta->name."</th>";
$i++;
}
while ($row = mysql_fetch_row($result))
{
echo '<tr>';
foreach($row as $item)
{
echo "<td>".$item."</td>";
}
echo '</tr>';
}
echo "</table>";
exit();
}
And etc... i am going to have to repeat this process until i cover all, 76 i believe, possibilites. thnkfully its just a lot of copy paste. thanks for the help everyone

First don't use MYSQL_*. Use PDO
Second, with your code, your are requiring all fields to be filled.
If you don't wanna do that then go this way:
You can use WHERE 1=1 , but it's not recommended !!!!!
$sql = "SELECT * FROM ".$tbl_name." WHERE confirm = '0' ";
$sql .= "AND fname = ".$fname."";
$sql .= "AND lname = ".$lname."";
$sql .= "AND city = ".$city."";
$sql .= "AND phone = ".$pohne."";
$sql .= "ORDER BY date DESC";
$result = mysql_query($sql);
echo "<table border='1'>";
echo "<tr>";
$i = 0;
while ($i < mysql_num_fields($result))
{
$meta = mysql_fetch_field($result, $i);
echo "<th>".$meta->name."</th>";
$i++;
}
while ($row = mysql_fetch_row($result))
{
echo '<tr>';
foreach($row as $item)
{
echo "<td>".$item."</td>";
}
echo '</tr>';
echo $row;
}
echo "</table>";

Related

PHP new strings update in DB with unshift?

I have a problem to adding more strings in my database.
The idea is: SELECT information, then added array together, after these UPDATE to database.
These are in one code, but UPDATE not working with summed arrays only separately.
With echo I see the array_unshift is working well, the data is good, but not updating.
Need I change something on the server? Maybe version?
(I don't get mysqli_error!)
//CHECKBOX KIOLVASÁSA DB-BŐL!
$sql = ("SELECT id, checkbox FROM osszesito WHERE id = '$id'");
//$result = mysqli_query($conn, $sql);
//if (mysqli_num_rows($result) > 0) {
if ($result = mysqli_query($conn, $sql)) {
while($row = mysqli_fetch_assoc($result)) {
//EREDETI SOR LISTÁZÁSA
$original_array = array( $row["checkbox"] );
$x ="";
echo 'Eredeti sor: ';
foreach ($original_array as $x)
{
echo "$x "."<br><br>";
}
//EREDETI SOR KIEGÉSZÍTÉSE AZ ÚJ ADATTAL
array_unshift($original_array, $chb);
$last ="";
echo "Új sor: "."<br>";
foreach ($original_array as $last)
{
echo $last."<br>";
}
//ÚJ SOR FRISSÍTÉSE A DB-BEN!
//$sqla = "UPDATE osszesito SET checkbox = '$chb' WHERE id = '$id' ";
$sqla = "UPDATE osszesito SET checkbox = '$last' WHERE id = '$id' ";
if (mysqli_query($conn, $sqla)) {
echo "ÚJ SOR ELMENTVE!";
//header("Location: /megrendelesek/index.php");
} else {
echo "Hiba a beírás során: " . mysqli_error($conn);
}
}
///////////////////////////////////////////////
//LEZÁRÁS
} else {
echo "Jelenleg nincs megrendelés az adatbázisban!";
}
mysqli_close($conn);

possible ?: mysql row to an if condition

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
}

Search a MySQL table in PHP

I am building a script where a user can query (search) a MySQL database.
The user firstly selects the table from a drop down list, and then they can choose upto 4 'filters' for example userID=001.
Here is my code:
$con=mysqli_connect("localhost","Username","Password","DBname");
// Check connection
if(mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "SELECT * FROM ".$table." WHERE 1=1 ";
if($filter1 != "" or $filter1v != "" )
{
$query .= " and $filter1 LIKE'%$filter1v%'";
}
if($filter2 != "" or $filter2v != "" )
{
$query .= " and $filter2 LIKE'%$filter2v%'";
}
if($filter3 != "" or $filter3v != "" )
{
$query .= " and $filter3 LIKE'%$filter3v%'";
}
if($filter4 != "" or $filter4v != "")
{
$query .= " and $filter4 LIKE'%$filter4v%'";
}
$query .= ";";
$resultRAW = mysqli_query($con, $query);
echo mysqli_error($con);
$result = array();
while($data = mysqli_fetch_array($resultRAW, MYSQLI_ASSOC))
{
$result[] = $data;
}
echo "<table class='table table-striped' id='tableWithExportOptions'>";
$amountRows = count($result);
for($i = 0; $i < $amountRows; $i++)
{
$keys = array_keys($result[$i]);
$amountColumns = count($keys);
if ($i == 0)
{
echo "<thead><tr>";
//I replaced the foreach clause because of performance reasons but they would work as well
for($j = 0; $j < $amountColumns; $j++)
{
echo "<th>".$keys[$j]."</th>";
}
echo "</tr></thead>";
}
echo "<tr>";
for($j = 0; $j < $amountColumns; $j++)
{
echo "<th>".$result[$i][$keys[$j]]."</th>";
}
echo "</tr>";
}
echo "</table>";
?>
If the user doesn't choose any filters the script works fine, however when using a filter it doesn't show any results?
Depending on your database this may vary. But you can not append a string to the result. $result is a MySQL Result object. You need to fetch the result for example with this code:
$array = array();
while($data = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$array[] = $data;
}
Then you can work with your result array $array and do whatever you want to do
If you want to create a query this way you need to call the mysqli_query later and build the query which could look like this:
$con = mysqli_connect("localhost","Username","Password","DBname");
// Check connection
if(mysqli_connect_errno())
{
echo "Failed to connect to MySQL: ".mysqli_connect_error();
}
$query = "SELECT * FROM ".$table." WHERE 1=1 ";
if($field != "" or $fieldvalue != "" )
{
$query .= " and ".$field." LIKE'%".$fieldvalue."%'";
}
if($filter1 != "" or $filter1value != "" )
{
$query .= " and ".$filter1." LIKE'%".$filter1value."%'";
}
if($filter2 != "" or $filter2value != "" )
{
$query .= " and ".$filter2." LIKE'%".$filter2value."%'";
}
if($filter3 != "" or $filter3value != "" )
{
$query .= " and ".$filter3." LIKE'%".$filter3value."%'";
}
if($filter4 != "" or $filter4value != "")
{
$query .= " and ".$filter4." LIKE'%".$filter4value."%'";
}
$query .= ";";
$resultRAW = mysqli_query($con, $query);
$result = array();
while($data = mysqli_fetch_array($resultRAW, MYSQLI_ASSOC))
{
$result[] = $data;
}
And I would be extremely careful with $table. in the query. This looks like a very good point to start an SQL Inejction attack. To prevent those I recomment the use of prepared statements. More can be found here: Prevent SQL Injection.
Unfortunalty this does not work with tablenames so you need to manually test it for any malicios input. If you "trust" this variable then it might be ok but if it is a use rinput I would AT LEAST call:
$table = mysqli_real_escape_string($table);
EDIT:
echo "<table class='table table-striped' id='tableWithExportOptions'>";
$amountRows = count($result);
for($i = 0; $i < $amountRows; $i++)
{
$keys = array_keys($result[$i]);
$amountColumns = count($keys);
if ($i == 0)
{
echo "<thead><tr>";
//I replaced the foreach clause because of performance reasons but they would work as well
for($j = 0; $j < $amountColumns; $j++)
{
echo "<th>".$keys[$j]."</th>";
}
echo "</tr></thead>";
}
echo "<tr>";
for($j = 0; $j < $amountColumns; $j++)
{
echo "<th>".$result[$i][$keys[$j]]."</th>";
}
echo "</tr>";
}
echo "</table>";
If this does not work please tell me, I have not tested this.
Because you concatenate string to $result = mysqli_query
$result = "SELECT * FROM $table WHERE 1=1";
if ($field != "" or $fieldvalue != "") {
$result .= " and $field LIKE'%$fieldvalue%'";
}
if ($filter1 != "" or $filter1value != "") {
$result .= " and $filter1 LIKE'%$filter1value%'";
}
if ($filter2 != "" or $filter2value != "") {
$result .= " and $filter2 LIKE'%$filter2value%'";
}
if ($filter3 != "" or $filter3value != "") {
$result .= " and $filter3 LIKE'%$filter3value%'";
}
if ($filter4 != "" or $filter4value != "") {
$result .= " and $filter4 LIKE'%$filter4value%'";
}
mysqli_query($con, $result);
Few things I can see that give me pause here.
But firstly, to Answer your question:
The mysqli_query(); method executes the query you pass to it. In your code you're executing the basic query with mysqli_query(); before you check for and add the filters and their values. So no matter what the user selects on your drop downs, that query without filters will always be executed first. You need to build your whole query string first, then execute the query with mysqli_query(); after all the checking and possible additions to your query.
Additionally, things that might break things later on:
Also, you might want to use and/&& in your if statements. or like you have it will allow your SELECT statement to break if you have the $filter1value populated with a value and $filter1 not, it will test true in your if and the WHERE clause will be concatenated to your query with a value but no field.
TIPS: echo your SQL command out to see what your php code has generated to see if it's valid SQL before running it while you develop.
Myself and many other PHP developers prefer to use PDO to interact with Databases personally, but that's just my preference.
I wanted to give you a code example of how I would have done it, but I honestly would change too much of your code, so I left it.
Side-note: I'm not sure what levels of security you have on the inputs but what you're doing by including your input variables directly into you SQL command string like that leaves you open to SQL injection attacks. Very dangerous depending on who will be able to access your script. Perhaps try using a prepared statement with parameters to keep security up a bit. Please look at mysqli_prepare(); it's friend, the mysqli_stmt_bind_param(); method in this case where you're using mysqli. Always use prepared statements on the database libraries you use if you're accepting external inputs to your system. It'll save your job one day.
Just my two cents use it, don't use it. :)
I guess you should add the filters on the query string before you execute the query, instead of adding the filter to the results? E.g.
$query = "SELECT * FROM $table WHERE 1=1";
if (...) {
$query .= ...
}
// some more ifs...
$result = mysqli_query($con, $query);

Why Getting only 1 array instead of many arrays?

I am a completely newbie in programming php I would like to make this code below return many arrays(to flash as3), however I only receive one array.Can anyone please pinpoint what is my mistake here? thanks.
$data_array = "";
$i = 0;
//if(isset($_POST['myrequest']) && $_POST['myrequest'] == "get_characters")
//{
$sql = mysqli_query($conn, "SELECT * FROM ns_users ORDER BY Char_id");
while($row = mysqli_fetch_array($sql))
{
$i++;
$fb_name = $row["Username"];
$fb_id = $row["Fb_id"];
$fb_at = $row["Access_token"];
$fb_sig = $row["Fb_sig"];
$char_id = $row["Char_id"];
if($i == 1)
{
$data_array .= "$fb_name|$fb_id|$fb_at|$fb_sig|$char_id";
}
else
{
$data_array .= "(||)$fb_name|$fb_id|$fb_at|$fb_sig|$char_id";
}
echo "returnStr=$data_array";
exit();
}
When you write your exit insight your loop you stop executing your program and you get only one record. You should set the echo and exit after your while loop.
$data_array = "";
$i = 0;
$sql = mysqli_query($conn, "SELECT * FROM ns_users ORDER BY Char_id");
while($row = mysqli_fetch_array($sql)) {
$i++;
$fb_name = $row["Username"];
$fb_id = $row["Fb_id"];
$fb_at = $row["Access_token"];
$fb_sig = $row["Fb_sig"];
$char_id = $row["Char_id"];
if($i == 1) {
$data_array .= "$fb_name|$fb_id|$fb_at|$fb_sig|$char_id";
} else {
$data_array .= "(||)$fb_name|$fb_id|$fb_at|$fb_sig|$char_id";
}
}
echo "returnStr=$data_array";
exit();
Those two last line of your should be outside of your loop:
$data_array = "";
$i = 0;
//if(isset($_POST['myrequest']) && $_POST['myrequest'] == "get_characters")
//{
$sql = mysqli_query($conn, "SELECT * FROM ns_users ORDER BY Char_id");
while($row = mysqli_fetch_array($sql))
{
$i++;
$fb_name = $row["Username"];
$fb_id = $row["Fb_id"];
$fb_at = $row["Access_token"];
$fb_sig = $row["Fb_sig"];
$char_id = $row["Char_id"];
if($i == 1)
{
$data_array .= "$fb_name|$fb_id|$fb_at|$fb_sig|$char_id";
}
else
{
$data_array .= "(||)$fb_name|$fb_id|$fb_at|$fb_sig|$char_id";
}
}
echo "returnStr=$data_array";
exit();
If you would name the columns that you want in the SELECT then it's much simpler. Make sure to use MYSQLI_ASSOC in the fetch:
$sql = mysqli_query($conn, "SELECT Username, Fb_id, Access_token, Fb_sig, Char_id FROM ns_users ORDER BY Char_id");
while($row = mysqli_fetch_array($sql, MYSQLI_ASSOC))
{
$data_array[] = implode('|', $row);
}
echo "returnStr=" . implode('(||)', $data_array);
exit();

Update Multiple Rows (PHP + MySQL)

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?

Categories