PHP Select from multiple tables and add value together to get total - php

i am trying to run these queries in PHP to a mysql table
$sql="SELECT * from customer where customerid > '' and voicemail_max > '' and company_status = '' ";
$rs=mysql_query($sql,$conn);
while($customer=mysql_fetch_array($rs)) {
$sql2="SELECT * from client where parent_client_id = '".$customer["customerid"]."' ";
$rs2=mysql_query($sql2,$pbx01_conn);
while($result2=mysql_fetch_array($rs2))
{
$sql3="SELECT * from extension where client_id = '".substr($result2["id"],1,3)."' ";
$rs3=mysql_query($sql3,$pbx01_conn);
while($result3=mysql_fetch_array($rs3))
{
$sql4="SELECT * from extension_voicemail where extension_id = '".$result3["id"]."' ";
$rs4=mysql_query($sql4,$pbx01_conn);
$voicemail_size_total=0;
while($result4=mysql_fetch_array($rs4)) {
$voicemail_size_total = $voicemail_size_total+$result4["filesize"];
}
}
}
echo $voicemail_size_total;
}
it should be adding up multiple values from one column
the $sql4 query looks like:
SELECT * from extension_voicemail where extension_id = '1454'
and when i run that in the database, it returns one row with the file size column as 31780
but when i echo $voicemail_size_total variable, it shows nothing.
it works fine if i echo that variable one line up from where it is, but where it is now shows nothing

Declare $voicemail_size_total=0; outside of all of the while loops. Everytime you get back to the loop you re-set that back to 0. That might be the problem.

Well, it depends on what you want to achieve:
1. If you want to get a total of all the filesizes (basicly you are expecting just one value to be presented ) try this:
$sql="SELECT * from customer where customerid > '' and voicemail_max > '' and company_status = '' ";
$rs=mysql_query($sql,$conn);
$voicemail_size_total=0;
while($customer=mysql_fetch_array($rs)) {
$sql2="SELECT * from client where parent_client_id = '".$customer["customerid"]."' ";
$rs2=mysql_query($sql2,$pbx01_conn);
while($result2=mysql_fetch_array($rs2))
{
$sql3="SELECT * from extension where client_id = '".substr($result2["id"],1,3)."' ";
$rs3=mysql_query($sql3,$pbx01_conn);
while($result3=mysql_fetch_array($rs3))
{
$sql4="SELECT * from extension_voicemail where extension_id = '".$result3["id"]."' ";
$rs4=mysql_query($sql4,$pbx01_conn);
while($result4=mysql_fetch_array($rs4)) {
$voicemail_size_total = $voicemail_size_total+$result4["filesize"];
}
}
}
}
echo $voicemail_size_total;
2. If you're looking for the filesizes of each client (ie. expecting a series of filesizes to be presented ) try this:
$sql="SELECT * from customer where customerid > '' and voicemail_max > '' and company_status = '' ";
$rs=mysql_query($sql,$conn);
while($customer=mysql_fetch_array($rs)) {
$sql2="SELECT * from client where parent_client_id = '".$customer["customerid"]."' ";
$rs2=mysql_query($sql2,$pbx01_conn);
$voicemail_size_total=0;
while($result2=mysql_fetch_array($rs2))
{
$sql3="SELECT * from extension where client_id = '".substr($result2["id"],1,3)."' ";
$rs3=mysql_query($sql3,$pbx01_conn);
while($result3=mysql_fetch_array($rs3))
{
$sql4="SELECT * from extension_voicemail where extension_id = '".$result3["id"]."' ";
$rs4=mysql_query($sql4,$pbx01_conn);
while($result4=mysql_fetch_array($rs4)) {
$voicemail_size_total = $voicemail_size_total+$result4["filesize"];
}
}
}
echo $voicemail_size_total;
}

Related

mysql multiple word search

i have a mysql table and a search form
i am filtering the table acc to the given conditions
but my problem is i want to search multiple words from string field
could you please help me how to do this :
i mean i want to allow it to be written multiple words in the string and want them to be searched by "AND"
if ($_REQUEST["string"]<>'') {
$search_string = " AND (customername LIKE '%".mysql_real_escape_string($_REQUEST["string"])."%' OR definition LIKE '%".mysql_real_escape_string($_REQUEST["string"])."%')";
}
if ($_REQUEST["customername"]<>'') {
$search_customername = " AND customername='".mysql_real_escape_string($_REQUEST["customername"])."'";
}
if ($_REQUEST["date"]<>'' and ($_REQUEST["string"]<>'' or $_REQUEST["customername"]<>'') ) {
$sql = "SELECT * from ".$SETTINGS["data_table"]." WHERE date = '".mysql_real_escape_string($_REQUEST["date"])."' ".$search_string.$search_customername;
} else
if ($_REQUEST["date"]<>'' and ($_REQUEST["string"]<>'' or $_REQUEST["customername"]<>'' ) ) {
$sql = "SELECT * from ".$SETTINGS["data_table"]." WHERE date = '".mysql_real_escape_string($_REQUEST["date"])."' ".$search_string.$search_customername;
} else
if ($_REQUEST["date"]<>'' and $_REQUEST["string"]=='' and $_REQUEST["customername"]=='') {
$sql = "SELECT * from ".$SETTINGS["data_table"]." WHERE date = '".mysql_real_escape_string($_REQUEST["date"])."' ";
} else {
$sql = "SELECT * FROM ".$SETTINGS["data_table"]." WHERE id>0".$search_string.$search_customername;
}

Search multiple values if present

sorry my English is weak ....
how can i search multi values from db SQL So that there was any.
i can search name && family together but
I want when the user searched name And family leave empty Return result correctly
how can i write this
if (isset($_POST['searchname']) || isset($_POST['searchfamily'])) {
$sql = "select * from myinfo WHERE name='{$_POST['searchname']}' && family='{$_POST['searchfamily']}' ORDER BY id DESC";
}
else {
$sql = "select * from myinfo ORDER BY id DESC";
}
Your 3 main issues here..
the first being WHERE name= now.. name is already used by mysql therefore you shouldn't use it however.. If you do use it run it like this:
WHERE `name`=
You should always backtick database tables and columns to make life easier in the long haul.
The second issue being you used && where it should be AND
the third is you shouldn't be placing your variables straight into your query as you're left open for SQL Injection.
Now I'm running on the assumption you're using $mysqli as your variable however, this may need adjusting to suit the correct variable you are using:
if (isset($_POST['searchname']) || isset($_POST['searchfamily'])) {
$searchName = $_POST['searchname'];
$family = $_POST['searchfamily'];
$sql = $mysqli->prepare("select * from `myinfo` WHERE `name` = ? OR `family`= ? ORDER BY `id` DESC");
$sql->execute([$searchName, $family]);
} else {
$sql = $mysqli->prepare("select * from `myinfo` ORDER BY `id` DESC");
$sql->execute();
}
If you want to search with both then you need to change your if also. And change && to and in your query
if (isset($_POST['searchname']) && isset($_POST['searchfamily'])) {
$sql = "select * from myinfo WHERE `name`='{$_POST['searchname']}' AND family='{$_POST['searchfamily']}' ORDER BY id DESC";
}
else {
$sql = "select * from myinfo ORDER BY id DESC";
}
Edit
As per your comment try this:
if (isset($_POST['searchname']) || isset($_POST['searchfamily'])) {
$where="";
if(isset($_POST['searchname']))
$where=" WHERE `name`='{$_POST['searchname']}'";
if(isset($_POST['searchfamily']))
{
if($where=="")
$where=" WHERE family='{$_POST['searchfamily']}'";
else
$where=" AND family='{$_POST['searchfamily']}'";
}
$sql = "select * from myinfo $where ORDER BY id DESC";
}
else {
$sql = "select * from myinfo ORDER BY id DESC";
}

How to display default post with get method?

I want to get an id from browser and display some pictures from the database.
If there is no "display2.php?productid=" found, then I want to display default image.
How can I do that?
Here is my code;
$sql = "SELECT * FROM productlist where productid=".$_GET['productid'];
$result = $mysqli->query($sql);
while($myRow = $result->fetch_array())
{
if(null !==($_GET['productid']==$myRow["productid"])){
echo "<img src=".$myRow["productid"].">";
}
else {
echo "<img src="SELECT productimage FROM productlist where productid = 1;">";
}
}
Now I will make it easier to explain for you...
Check this out;
//This part works without any problem
$sql = "SELECT * FROM productlista where productid=".$_GET['productid'];
$result = $mysqli->query($restwo);
while($myRow = $resulttwo->fetch_array())
{
if(null !==($_GET['productid']==$myRow["productid"])){
echo "<img src=".$myRow["productimage"].">";
}
//This part below (that should be default) does not work...
if (!$_GET){
echo "hello world"; }
Asaph pointed out SQL injection. You should bind the parameter (google it), or at the minimum do this:
$defaultImage = "SELECT * FROM productlist WHERE imageSrc != '' OR IS NOT NULL ORDER BY productid DESC LIMIT 1";
// run the query, get the result, create a variable with default image...
$defaultImageSrc = ''; // what you get from the query result
$_GET['productid'] = preg_replace('#[^0-9]#', '', $_GET['productid']);
$sql = "SELECT * FROM productlist where productid=".$_GET['productid'];
$result = $mysqli->query($sql);
while($myRow = $result->fetch_array()) {
if(!$myRow['imageSrc']) $myRow['imageSrc'] = $defaultImageSrc;
echo '<img src="'.$path.'">';
}
If you want either $_GET['productid'] or the max(productid) when $_GET['productid'] is not set, you can use a ternary to change your sql query
$productid = ! empty($_GET['productid']) ? " WHERE productid = ".(int)$_GET['productid'] : " ORDER BY productid DESC LIMIT 1";
$sql = "SELECT * FROM productlist".$productid
$result = $mysqli->query($sql);
while($myRow = $result->fetch_array())
{
echo "<img src=".$myRow["productimage"].">";
}
so if isset($_GET['productid']) your query would be
SELECT * FROM productlist WHERE productid = (int)$_GET['productid']
but if not the default would be
SELECT * FROM productlist ORDER BY productid DESC LIMIT 1

Pagination Php not working when different sql query conditions are added

Hello I am facing a problem with my pagination system, where if I list results from a mysql table it is working fine, but in case If I add some conditions inside the SQL Query like "AND" this column "AND" other column the script shows the results properly on the first page, when I chooce the second page instead of showing the second portion of results from 26 forward it is starting a new pagination and it is showing everything from the begining without the contions added inside the query. Here is the code of the pagination with the query:
//This gets all the other information from the form
$ciudad=$_POST['ciudad'];
$tipo=$_POST['tipo'];
$con=mysqli_connect();
// Check connection
$sql = "SELECT * FROM cursos WHERE 1";
if (!empty($ciudad)) {
$sql .= " AND ciudad = '$ciudad' ";
}
if (!empty($tipo)) {
$sql .= " AND tipo= '$tipo' ";
}
if (!$result = mysqli_query($con,$sql))
{
die("Error: " . mysqli_error($con));
}
$per_page =25;//define how many games for a page
$count = mysqli_num_rows($result);
$pages = ceil($count/$per_page);
if(!isset($_GET['page']) || $_GET['page']=="") {
$page="1";
} else {
$page=$_GET['page'];
}
$start = ($page - 1) * $per_page;
$sql = "SELECT * FROM cursos WHERE 1 LIMIT $start,$per_page";
?>
This is the code of the generated pages links:
<?php
//Show page links
for ($i = 1; $i <= $pages; $i++)
{?>
<li id="<?php echo $i;?>"><?php echo $i;?></li>
<?php
}
?>
The 2 problems where:
additional filter are not anymore selected in the next page ($_POST will be empty)
instructions related to pagination where calculated AFTER the query (which, obviously, couldn't use theses parameters)
You can either store your extra queries conditions in session, or add it as parameter in the "next page link", or transform your link to a submit form (which is probably the best option)
<li id="<?php echo $i;?>"><?php echo $i;?></li>
If you choose the link solution, don't forget to change your _POST in _GET (or check the second if the first is empty, or use $_REQUEST)
I have to mention your code is not sql injection free and using mysqli_prepare() may worth the time (for security and performances)
EDIT: so, here we go:
sidenotes: using $_REQUEST is not always recommended
And I noticed also you execute your query BEFORE using the pagination system...
//This gets all the other information from the form
$ciudad=$_REQUEST['ciudad'];
$tipo=$_REQUEST['tipo'];
$con=mysqli_connect();
// Check connection
$sql = "SELECT * FROM cursos WHERE 1";
if (!empty($ciudad)) {
$sql .= " AND ciudad = '$ciudad' ";
}
if (!empty($tipo)) {
$sql .= " AND tipo= '$tipo' ";
}
// PAGINATION MOVED UP
$per_page =25;//define how many games for a page
$count = mysqli_num_rows($result);
$pages = ceil($count/$per_page);
if(empty($_GET['page'])) {
$page="1";
} else {
$page=$_GET['page'];
}
$start = ($page - 1) * $per_page;
$sql .= ' LIMIT '.$start.','.$per_page;
if (!$result = mysqli_query($con,$sql))
{
die("Error: " . mysqli_error($con));
}
//Show page links
for ($i = 1; $i <= $pages; $i++)
{?>
<li id="<?php echo $i;?>"><?php echo $i;?></li>
<?php
}
?>
If $ciudad and $tipo both are not empty your query on execution will look like this:
SELECT * FROM cursos WHERE 1 AND ciudad = '$ciudad' ORDER BY id DESC AND tipo= '$tipo' ORDER BY id DESC
It should be like this if i am not mistaken:
SELECT * FROM cursos WHERE 1 AND ciudad = '$ciudad' AND tipo= '$tipo' ORDER BY id DESC
What I would do is change this:
$sql = "SELECT * FROM cursos WHERE 1";
if (!empty($ciudad)) {
$sql .= " AND ciudad = '$ciudad' ORDER BY id DESC ";
}
if (!empty($tipo)) {
$sql .= " AND tipo= '$tipo' ORDER BY id DESC ";
}
too this:
$sql = "SELECT * FROM cursos WHERE 1 ";
if (!empty($ciudad)) {
$sql .= "AND ciudad= '$ciudad' ";
if (!empty($tipo)) {
$sql .= "AND tipo= '$tipo' ";
}
$sql .= "ORDER BY id DESC ";
}
I've also got a link which might help you out with the pagination.
http://www.phpjabbers.com/php--mysql-select-data-and-split-on-pages-php25.html
If city and type are set then your SQL will have two instances of order by... You should add order by after the if statements.

MySQL query within another query's while loop in PHP

I have the following code:
$query = mysql_query("SELECT * FROM activity ORDER BY activity_time DESC LIMIT 50");
while($result = mysql_fetch_array($query)) {
extract($result);
if ($activity_type == "discussion") {
$query = mysql_query("SELECT * FROM discussions WHERE discussion_uuid = '$activity_ref'");
while($result = mysql_fetch_array($query)) {
extract($result);
echo $discussion_user . " said:<br>" . $discussion_text . "<br>";
}
} elseif ($activity_type == "file") {
}
}
But it just returns the last row. My goal is to have a chronological list of "activities" each displayed slightly differently depending on their type.
Your using $query and $result twice so the second loop is overwriting the result of the first and stopping...
$query = mysql_query("SELECT * FROM activity ORDER BY activity_time DESC LIMIT 50");
and
$query = mysql_query("SELECT * FROM discussions WHERE discussion_uuid = '$activity_ref'");
same with $results var...
I would suggest you change to $query and $query2 but best to use something like
$activies = mysql_query("SELECT * FROM activity ORDER BY activity_time DESC LIMIT 50");
while($activity = mysql_fetch_array($activies)) {
and
$discussions = mysql_query("SELECT * FROM discussions WHERE discussion_uuid = '$activity_ref'");
while($discussion = mysql_fetch_array($discussions)) {
I would also avoid using extract - as you might be overwriting vars your not expecting to...
You have to create another connection to the database so that you can run them at the same time.
OR
You can load the results of the first one into an array, and then just loop through the array.

Categories