使用下拉(选择)菜单修改表单

时间:2016-06-01 02:52:47

标签: php html

所以我尝试使用此代码从数据库中获取记录,但我只获得else alert message。有人可以说我做错了什么或代码中的错误在哪里?它填充了下拉列表,但就像我说的那样,我不会仅获得结果警告消息:

<form  method='post' action='grafikastest.php'> 
    <select id="name">
        <?php  
        include_once ('inc\connect.php'); 
        echo "Pasirinkite datą: &nbsp";  

        $date = strtotime("+0 day");
        $dtt=date('Y-m-d', $date); 
        echo "<option value=$dtt>$dtt</option>";

        $date = strtotime("+1 day"); 
        $dtt=date('Y-m-d', $date);
        echo"<option value=$dtt>$dtt</option>"; 

        $date = strtotime("+2 day"); 
        $dtt=date('Y-m-d', $date);
        echo "<option value=$dtt>$dtt</option>";   

        $date = strtotime("+3 day"); 
        $dtt=date('Y-m-d', $date);
        echo "<option value=$dtt>$dtt</option>";  

        $date = strtotime("+4 day"); 
        $dtt=date('Y-m-d', $date);
        echo "<option value=$dtt>$dtt</option>"; 

        $date = strtotime("+5 day"); 
        $dtt=date('Y-m-d', $date);
        echo "<option value=$dtt>$dtt</option>";   

        $date = strtotime("+6 day"); 
        $dtt=date('Y-m-d', $date);
        echo "<option value=$dtt>$dtt</option>";

        $sql = "SELECT  ID, data, laikas, laikas2 FROM vizitai4 WHERE darb_stat NOT LIKE 'Atlikta' and data LIKE '%" . $dtt .  "%'  OR
darb_stat IS NULL and data LIKE '%" . $dtt .  "%' GROUP BY laikas";

        $result = mysql_query($sql); 
        //rodymas lenteleje
        echo $dtt;
        echo "<table id=t01>
                <tr>
                    <th>Data</th>
                    <th>Remonto pradžia</th>
                    <th>Remonto pabaiga</th>
                </tr>";

        if(mysql_num_rows($result) > 0) {
            while( $row=mysql_fetch_array($result)) { 
                echo "<tr>";
                echo "<td>" . $row['data'] . "</td>";
                echo "<td>Remontas prasideda nuo " . $row['laikas'] .  " </td>";
                echo "<td>Numatomas remonto baigimo laikas " . $row['laikas2'] .  " </td>";
                echo "<td style='display: none;'><form method=post>
                    <input name=id type=hidden value='".$row['id']."';>

                    </form></td>";
                echo "</tr>";
            }
        }else{
            echo "<script>alert('Šios dienos įrašų nėra');</script>";
        }

        echo "</table>"; 
        ?> 
    </select>
    <input  type="submit" name="submit" value="Ieskoti"> 
</form>  
</body> 
</html>    

1 个答案:

答案 0 :(得分:1)

从我们的交流中,问题的核心是您希望与表单进行交互以更改表单本身,并且您只想使用PHP来实现此目的。由于PHP运行一次以生成页面,因此您无法与表单元素进行交互,并让PHP对这些更改做出反应。您需要一个将重新查询PHP的触发效果。这是一个客户端语言的工作,如JavaScript。

因为你在这里要一个例子是一个基本的例子。这不是一件容易的事,并且有一堆活动部件,所以我有一种感觉,如果你&#34;几乎不知道这些东西...&#34; 你现在拥有的东西,你这个答案真的会在黑暗中。

按照说明操作,它应该适合您。我已经测试了大多数(或者已经从我使用的脚本中复制了片段)所以要注意所谓的内容以及放置它们的位置并阅读符号。我建议你创建这个目录/文件结构,然后在尝试对工作文档进行任何修改之前对其进行测试。一旦你做了这些事情,如果你不知道你在做什么,几乎不可能排除故障。另请注意,我不能在良心的情况下回答此问题而不删除对mysql_的引用,这些函数已被弃用或完全删除(php7)

<强> /config.php

<?php
// This page goes on every main page of your site
// Comment out the error lines when live,
// you don't want errors showing on your page except in test
session_start();
ini_set("display_errors",1);
error_reporting(E_ALL);
define('DB_HOST','yourdbhost');
define('DB_USERNAME','yourdbusername');
define('DB_PASSWORD','yourdbpass');
define('DB_NAME','yourdbname');
define('SITE_ROOT',__DIR__);
define('DS', DIRECTORY_SEPARATOR);
define('CLASS_DIR', SITE_ROOT.DS.'core'.DS.'classes');
define('FUNCTION_DIR', SITE_ROOT.DS.'core'.DS.'functions');
require_once(FUNCTION_DIR.DS.'autoloader.php');
// This will help to autoload your classes
// **RESOURCE:** http://php.net/manual/en/function.spl-autoload-register.php
spl_autoload_register('autoloader');
// put whatever else you want on this page to make available to your site.
// You don't need the database connection however

<强> /core/functions/makeOptions.php

<?php
/*
** @description This function uses a for loop to make your options
**              You need to think how to use php to make your script(s)
**              for you
**              **RESOURCE:** http://php.net/manual/en/control-structures.for.php
** @param $max [int] This is how many options the function will make
*/
function makeOptions($max = 6)
    {
        for($i = 0; $i <= $max; $i++) {
            $date   =   strtotime("+".$i." day");
            $dtt    =   date('Y-m-d', $date);
            echo '<option value="'.$dtt.'">'.$dtt.'</option>'.PHP_EOL;
        }
    }

<强> /core/functions/autoloader.php

<?php
/*
** @description This function is used to autoload classes
** @param $class [string] This is automated and is populated by spl_autoload_register()
** **RESOURCE:** http://php.net/manual/en/function.spl-autoload-register.php
*/
function autoloader($class)
    {
        if(class_exists($class))
            return true;

        if(is_file($inc = CLASS_DIR.DS.$class.".php"))
            include_once($inc);
    }

<强> /page1.php

<?php
// Include our config file
require_once(__DIR__.DIRECTORY_SEPARATOR.'config.php');
// Include the function to create our options
include_once(FUNCTION_DIR.DS.'makeOptions.php');
?><!DOCTYPE html>
<html>
<head>
<!-- include in head with anything else you need -->
<!-- **RESOURCE:** http://www.jquery.com/ -->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script>
$(document).ready(function(){
    // Observe any change made to select with name=name
    $(this).on('change','select[name=name]',function() {
        // get the value of that selection
        var thisVal =   $(this).val();
        // Use ajax to query page2.php
        // **RESOURCE:** http://api.jquery.com/jquery.ajax/
        $.ajax({
            // This is the link that will load the contents of the form
            url: '/page2.php',
            data: {
                // This is equivalent to $_POST['name']
                "name":thisVal
            },
            type: 'POST',
            success: function(response) {
                // On success of the ajax, this will post the contents of
                // page2.php into the div with id=loadspot
                $("#loadspot").html(response);
            }
        });
    });
});
</script>
</head>
<body>
<form  method='post' action='grafikastest.php'>
    <!--
        I am not sure the placement of this text, but it can not be
        in the middle of a drop down
    -->
    Pasirinkite datą: &nbsp
    <select id="name" name="name">
        <option value="">Select</option>
        <!-- Apply the options function -->
        <?php makeOptions(); ?> 
    </select>
    <!-- This is where you will load the contents of the dropdown via ajax -->
    <div id="loadspot"></div>
    <input  type="submit" name="submit" value="Ieskoti"> 
</form>
</body>
</html>

<强> /core/classes/Database.php

<?php
/*
** @description This class is your new database which replaces your `mysql_`
** **RESOURCE:** http://php.net/manual/en/pdo.connections.php
*/
class Database
    {
        // static elements are kind of like a global
        private static  $singleton;
        private static  $con;
        // This will save the class for reuse
        public  function __construct()
            {
                if(self::$singleton instanceof Database)
                    return self::$singleton;

                self::$singleton    =   $this;
            }
        // This is the connection to the database
        public  function connect()
            {
                if(self::$con instanceof PDO)
                    return self::$con;
                // Review the PDO class for instruction how to make this
                // connection better using some PDO presets (Emulation of prepares, etc)
                // **RESOURCE** http://php.net/manual/en/pdo.constants.php
                self::$con  =   new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME,DB_USERNAME,DB_PASSWORD);

                return self::$con;
            }
    }

<强> /core/classes/qEngine.php

<?php
/*
** @description This class is what you use to safely query your database
** **RESOURCE:** http://php.net/manual/en/pdo.prepare.php
** **RESOURCE:** http://php.net/manual/en/pdo.query.php
** **RESOURCE:** http://php.net/manual/en/pdostatement.fetch.php
** 
*/
class qEngine
    {
        private static  $con;
        private $query;

        public  function query($sql = false,$bind = false)
            {
                // This checks if the connection is already saved
                // You can also use "dependency injection" to pass your
                // database connection to this class. I prefer to use
                // a static connection but here is how that dependency works:
                // **RESOURCE** http://code.tutsplus.com/tutorials/dependency-injection-in-php--net-28146
                // **RESOURCE** https://en.wikipedia.org/wiki/Dependency_injection
                if(!(self::$con instanceof PDO)) {
                    // Makes connection
                    $dbEngine   =   new \Database();
                    self::$con  =   $dbEngine->connect();
                }
                // Creates a bind array
                // **RESOURCE** http://php.net/manual/en/pdostatement.bindvalue.php
                // **RESOURCE** http://php.net/manual/en/pdostatement.execute.php (Example #2)
                // **RESOURCE** http://php.net/manual/en/pdostatement.bindparam.php
                if(!empty($bind)) {
                    $bArray =   false;
                    foreach($bind as $key => $value) {
                        $bKey           =   ":{$key}";
                        $bArray[$bKey]  =   $value;
                    }
                }
                // If there is a bind array, it will run a prepare
                if(!empty($bArray)) {
                    $this->query    =   self::$con->prepare($sql);
                    $this->query->execute($bArray);
                }
                // If no bind, it will run a straight query
                else {
                    $this->query    =   self::$con->query($sql);
                }
                // This returns the object for method chaining
                // **RESOURCE** http://stackoverflow.com/questions/3724112/php-method-chaining
                return $this;
            }

        public  function getResults()
            {
                // This will check that a query has been made
                if(empty($this->query))
                    return 0;
                // This will loop through the results and save to 1D array
                while($result = $this->query->fetch(PDO::FETCH_ASSOC))
                    $row[]  =   $result;
                // This will return either the array or a "0"
                return (!empty($row))? $row : 0;
            }
    }

<强> /core/functions/getListByDate.php

<?php
/*
** @description This function will query your database safely
** @param $date [string] Receives a date by string
*/
function getListByDate($date)
    {
        $bind   =   array('%'.$date.'%','%'.$date.'%');
        return (new \qEngine()) ->query("SELECT `ID`,`data`,`laikas`,`laikas2`
                                        FROM `vizitai4`
                                        WHERE `darb_stat`
                                        NOT LIKE 'Atlikta'
                                        AND `data`
                                        LIKE :0
                                        OR `darb_stat`
                                        IS NULL AND `data`
                                        LIKE :1
                                        GROUP BY `laikas`",$bind)
                                ->getResults();
    }

<强> /page2.php

<?php
// Include our config file
require_once(__DIR__.DIRECTORY_SEPARATOR.'config.php');
// Include the function to query the database
include_once(FUNCTION_DIR.DS.'getListByDate.php');
// This is the page that the AJAX queries from page1.php

// See if the post has been made
if(!empty($_POST['name'])) {
    // Fetch data from database
    $vizitai4   =   getListByDate($_POST['name']);
?>
<table id="t01">
    <tr>
        <th>Data</th>
        <th>Remonto pradžia</th>
        <th>Remonto pabaiga</th>
    </tr>
<?php
    if($vizitai4 != 0) {
        foreach($vizitia4 as $row) { 
?>  <tr>
        <td><?php echo $row['data']; ?></td>
        <td>Remontas prasideda nuo <?php echo $row['laikas']; ?></td>
        <td>Numatomas remonto baigimo laikas <?php echo $row['laikas2']; ?> </td>
        <td style="display: none;"><input name="id[]" type="hidden" value="<?php echo $row['id']; ?>" /></td>
    </tr>
<?php
        }
    }
    else {
?>
<script>
    alert('Šios dienos įrašų nėra');
</script>
<?php
    }
?>
</table>                
<?php
}

以下是正在发生的事情的基本构造:

enter image description here