简体   繁体   中英

Error when fetching data from table using values from two different table - MySQL

I have two MySQL tables - "mfb_servicelog" and "mfb_agent_status_summary".

I want to select data from "total_ce" column in "mfb_agent_status_summary" where sl_id = $sl_id and then export it as an excel sheet using PHPExcel.

I can get the $sl_id value from mfb_servicelog table where h_id = $value[$i].

And the values of $value is coming from another php file using _POST as an array.

Please point me to the right direection.

Here is my code: (Its returning long list of error)

$value = $_POST['hospitalname'];
$from = $_POST['from'];
$to = $_POST['to'];
if($_POST["Submit"]=="Submit") {
for ($i=0; $i<sizeof($value); $i++) {
$queryslid="SELECT sl_id FROM mfb_servicelog WHERE h_id LIKE ('".$value[$i]."')";
if ($resultslid = (mysql_query($queryslid) or die(mysql_error())) {
                while($rowslid = mysql_fetch_row($resultid)) {
                    $slidset[$i] = $rowslid;
                }
                $querycasesentered = "SELECT total_ce FROM agent_summary WHERE sl_id LIKE ('".$slidset[$i]."')";
                if ($resultcaseentered = (mysql_query($querycasesentered) or die(mysql_error())) {
                    while($rowce = mysql_fetch_row($resultcasesentered)) {
                        $casee[$i] = $rowce;
                        if($i == 0) {
                            $col = 'H';
                        }
                        else {
                            $col = $k;
                        }
                        foreach ($rowce as $cell) {
                            $obejctPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$cell);
                            $col++;
                        }
                        $rowNumber++;
                    }
                }
            }

You are using mysql_query in a wrong way. mysql_query has 2 parameters which is the connection and the query

You can look at this definition: http://www.w3schools.com/php/func_mysqli_query.asp

In short, I suggest that you should use PDO when you are not sure what you are doing with mysql. In order to understand what is PDO, you should read this tutorial http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers carefully which help you to prevent your code from the SQL Injection.

Just a heads up, you are accepting POST data without cleaning it before running your SQL statement, this is very very dangerous and opens your database to injection attacts. But to the problem at hand. Use a join SQL statement something like:

$sql = "SELECT total_ce FROM agent_summary AS agent LEFT JOIN mfb_servicelog AS service ON agent.sl_id = service.sl_id WHERE service.h_id LIKE ('".$value[$i]."')"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM