使用php mysqli扩展从数组绑定动态数据

时间:2016-03-18 09:11:34

标签: php mysql mysqli

我有一个html表单,我尝试动态搜索数据库中的数据 这是缩小的html,其中包含表单和div,类结果区域包含一些显示数据库结果的php:

<div class=container><div class=row><div class="col-lg-12 center-block"><div id=top><h1>Advanced Search Form</h1><h3>Website Design Tutorial</h3></div><form action=""id=search_form class=form-horizontal><fieldset><legend>Search for Book</legend><div class=col-lg-6><div class=form-group><label for=book class="col-sm-2 control-label">Book:</label><div class=col-sm-10><input name=book id=book class=form-control placeholder=Book....></div></div><div class=form-group><div class="lb col-sm-2 control-label">Cover:</div><div class=col-sm-10><label for=any-cover class=inline-label><input type=radio name=cover id=any-cover value=0 checked> Any</label><label for=Hard class=inline-label><input type=radio name=cover id=Hard value=2> Hard</label><label for=Soft class=inline-label><input type=radio name=cover id=Soft value=1> Soft</label></div></div><div class=form-group><label for=language class="col-sm-2 control-label">Language:</label><div class=col-sm-10><select name=language id=language class=form-control><option value=""selected>Any Language&hellip;<option value=1>English<option value=2>French<option value=3>German<option value=5>Italian<option value=6>Polish<option value=4>Spanish</select></div></div><div class=form-group><div class="lb col-sm-2 control-label">Location:</div><div class=col-sm-10><label for=Bournemouth class=inline-label><input type=checkbox name=location[] id=Bournemouth value=3> Bournemouth</label><label for=Brighton class=inline-label><input type=checkbox name=location[] id=Brighton value=2> Brighton</label><label for=Chichester class=inline-label><input type=checkbox name=location[] id=Chichester value=6> Chichester</label><label for=London class=inline-label><input type=checkbox name=location[] id=London value=1> London</label><label for=Portsmouth class=inline-label><input type=checkbox name=location[] id=Portsmouth value=4> Portsmouth</label><label for=Southampton class=inline-label><input type=checkbox name=location[] id=Southampton value=5> Southampton</label></div></div></div><div class=col-lg-6><div class=form-group><label for=category class="col-sm-2 control-label">Category:</label><div class=col-sm-10><select name=category id=category class=form-control><option value=""selected>Any Category&hellip;<option value=2>Art<option value=3>Comedy<option value=4>Horror<option value=1>Romance</select></div></div><div class=form-group><label for=author class="col-sm-2 control-label">Author:</label><div class=col-sm-10><select name=author id=author class=form-control><option value=""selected>Any Author&hellip;<option value=1>Darren Shan<option value=2>M.R. James<option value=4>Nora Roberts<option value=3>Stephenie Meyer</select></div></div><div class=form-group><label for=year class="col-sm-2 control-label">Year:</label><div class=col-sm-10><select name=year id=year class=form-control><option value=""selected>Any Year&hellip;<option value=2001>2001<option value=2005>2005<option value=2007>2007</select></div></div></div><div class="col-lg-12 submit"><button type=submit class="btn btn-primary"><i class="fa fa-search"></i>Search</button></div></fieldset></form><div class=results-area> <?php if ( $total_rows > 0 ) { ?> <table class="table table-bordered table-striped"><thead><tr class=bg-info><th>Title<th>Category<th>Author<th>Year Released<th>Price<tbody> <?php while ( $stmt->fetch() ) { ?> <tr><td><?php echo htmlspecialchars($title); ?><td><?php echo htmlspecialchars($category_name); ?><td><?php echo htmlspecialchars($author_name); ?><td><?php echo htmlspecialchars($year_released); ?><td>&pound;<?php echo htmlspecialchars($price); ?></tr> <?php } ?> <?php $stmt->free_result(); ?> </table> <?php } else { ?> <p>No results to display.</p> <?php } ?> </div></div></div></div>

这是我处理表单请求的doctype上面的php代码:

<?php

require_once 'includes/database.php';
require_once 'includes/functions.php';

if ( isset($_GET['book']) ) {
    $book_query = "SELECT DISTINCT bk.title AS title, YEAR( bk.date_released) AS year_released, FORMAT( bk.price, 2 ) AS price, ct.category_name AS category, aut.author_name AS author FROM book bk JOIN category ct ON bk.category = ct.id JOIN book_author bk_aut ON bk_aut.book_id = bk.id JOIN author aut ON aut.id = bk_aut.author_id JOIN book_cover bk_cov ON bk_cov.book_id = bk.id JOIN cover cov ON cov.id = bk_cov.cover_id JOIN book_language bk_lng ON bk_lng.book_id = bk.id JOIN language lng ON lng.id = bk_lng.language_id JOIN book_location bk_loc ON bk_loc.book_id = bk.id JOIN location loc ON loc.id = bk_loc.location_id
";

    $book = (isset($_GET['book']) && $_GET['book'] != '') ? '%' . trim( $_GET['book'] ) . '%' : '';
    $cover = (isset($_GET['cover']) && is_numeric($_GET['cover'])) ? $_GET['cover'] : 0;
    $language = (isset($_GET['language']) && is_numeric($_GET['language'])) ? $_GET['language'] : 0;
    $location = isset($_GET['location']) ? $_GET['location'] : array();
    $category = (isset($_GET['category']) && is_numeric($_GET['category'])) ? $_GET['category'] : 0;
    $author = (isset($_GET['author']) && is_numeric($_GET['author'])) ? $_GET['author'] : 0;
    $year = (isset($_GET['year']) && is_numeric($_GET['year'])) ? $_GET['year'] : 0;

    $where = array();
    $execution_params = array();
    $bind_params = array();
    $bind_types = '';

    if ( (boolean)$book )  {
        array_push($where, ' (bk.title LIKE ? OR bk.description LIKE ? OR bk.isbn LIKE ?)' );
        $bind_types .= 'sss';
        array_push($bind_params, $book, $book, $book);
        echo '<pre>' . print_r($bind_params, 1) . '</pre>';
    }
    if ( (boolean)$cover ) {
        array_push($where, ' bk_cov.cover_id=?');
        $bind_types .= 'i';
        array_push($bind_params, $cover);
    }
    if ( (boolean)$language ) {
        array_push($where, ' bk_lng.language_id=?');
        $bind_types .= 'i';
        array_push($bind_params, $language);
    }
    if ( (boolean)$year ) {
        array_push($where, ' YEAR(bk.date_released)=?');
        $bind_types .= 'i';
        array_push($bind_params, $year);
    }
    if ( (boolean)$category ) {
        array_push($where, ' ct.id=?');
        $bind_types .= 'i';
        array_push($bind_params, $category);
    }
    if ( (boolean)$author ) {
        array_push($where, ' bk_aut.author_id=?');
        $bind_types .= 'i';
        array_push($bind_params, $author);
    }
    if ( count($location) > 0 ) {
        $location_query = '';

        $i = 1;
        $len = count( $location );


        foreach( $location as &$loc ) {
            array_push($bind_params, $loc);
            $bind_types .= 'i';
            $location_query .= '?';
            if ( $i != $len ) {
                $location_query .= ', ';
            }
            $i++;
        }

        array_push($where, ' bk_loc.location_id IN (' . $location_query . ')');
    }

    if ( !empty($where) ) {
        $where_clause = implode(' AND ', $where);
    } else {
        $where_clause = '';
    }

    if ( $where_clause !== '' ) {
        $where_clause = substr_replace( $where_clause, ' WHERE ', 0, 0 );
    }

    $book_query .= $where_clause;
    $book_query .= " ORDER BY bk.title";

    $execution_params[] = $bind_types;
    foreach($bind_params as $term) {
        $execution_params[] = $term;
    }

    $stmt = $db->stmt_init();

    if ( $stmt->prepare( $book_query ) ) {
        if ( !empty($where) ) {
            call_user_func_array(array($stmt, 'bind_param'), $execution_params);
        }
        $stmt->execute();
        $stmt->bind_result( $title, $year_released, $price, $category_name, $author_name );
        $stmt->store_result();
    } else {
        echo $stmt->error;
    }

    $total_rows = $stmt->num_rows;
} else {
    $total_rows = 0;
}
?>

当您在初始页面加载后单击搜索处于默认状态时,表单会返回正确的结果,但是当您尝试提供搜索条件时,请说明在书籍输入字段中键入内容或选择多个位置或任何其他选项,php显示此警告:

Warning: Parameter 2 to mysqli_stmt::bind_param() expected to be a reference, value given

这是数据库和表所需的sql:

-- phpMyAdmin SQL Dump -- version 4.4.12 -- http://www.phpmyadmin.net -- -- Host: 127.0.0.1 -- Generation Time: Mar 18, 2016 at 09:05 AM -- Server version: 5.6.25 -- PHP Version: 5.6.11 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `books` -- -- -------------------------------------------------------- -- -- Table structure for table `author` -- CREATE TABLE IF NOT EXISTS `author`( `id` tinyint(3) unsigned NOT NULL, `author_name` varchar(200) NOT NULL) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1; -- -- Dumping data for table `author` -- INSERT INTO `author` (`id`, `author_name`) VALUES (1, 'Darren Shan'), (2, 'M.R. James'), (3, 'Stephenie Meyer'), (4, 'Nora Roberts'); -- -------------------------------------------------------- -- -- Table structure for table `book` -- CREATE TABLE IF NOT EXISTS `book` ( `id` tinyint(3) unsigned NOT NULL, `isbn` varchar(50) NOT NULL, `title` varchar(255) NOT NULL, `description` text NOT NULL, `category` tinyint(4) NOT NULL, `price` decimal(8,2) NOT NULL, `date_released` date NOT NULL, `date_entered` datetime NOT NULL ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1; -- -- Dumping data for table `book` -- INSERT INTO `book` (`id`, `isbn`, `title`, `description`, `category`, `price`, `date_released`, `date_entered`) VALUES (1, '1405678151', 'Ghost Stories', 'This is the second collection of chilling ghost stories by M. R. James. "A Warning to the Curious" features a young man who excavates an ancient crown - but soon wishes he had let it stay buried. In "The Mezzotint" an engraving of a manor house reveals more than first meets the eye, while in "The Stalls of Barchester Cathedral", an archdeacon''s journal reveals the strange circumstances that led to his death. The final story, "A Neighbour''s Landmark", tells of a gentleman whose curiosity is piqued by a strange rhyme, leading him to take a walk through Betton Woods...Read by BAFTA and Emmy-award winning actor Derek Jacobi ("Cadfael", "Gosford Park", "Doctor Who"), and with eerie, evocative music, these four haunting stories will thrill anyone who loves to be terrified.', 4, '6.99', '2005-10-10', '2009-10-10 19:53:49'), (2, '0007260342', 'Hell''s Heroes', 'The final dramatic conclusion to Darren Shan''s international phenomena, The Demonata. Expect the unexpected! The final dramatic conclusion to Darren Shan''s international phenomena, The Demonata. Expect the unexpected!', 4, '6.49', '2001-10-09', '2009-10-08 19:59:04'), (3, '1904233651', 'Twilight', 'When 17 year old Isabella Swan moves to Forks, Washington to live with her father she expects that her new life will be as dull as the town. But in spite of her awkward manner and low expectations, she finds that her new classmates are drawn to this pale, dark-haired new girl in town. But not, it seems, the Cullen family. These five adopted brothers and sisters obviously prefer their own company and will make no exception for Bella. Bella is convinced that Edward Cullen in particular hates her, but she feels a strange attraction to him, although his hostility makes her feel almost physically ill. He seems determined to push her away ? until, that is, he saves her life from an out of control car. Bella will soon discover that there is a very good reason for Edward''s coldness. He, and his family, are vampires ? and he knows how dangerous it is for others to get too close.', 1, '3.49', '2007-10-29', '2009-10-13 20:01:52'), (4, '074992926X', 'Black Hills', 'Lil Chance fell in love with Cooper Sullivan pretty much the first time she saw him, an awkward teenager staying with his grandparents on their cattle ranch in South Dakota while his parents went through a messy divorce. Each year, with Coop''s annual summer visit, their friendship deepens - but then abruptly ends. Twelve years later and Cooper has returned to run the ranch after his grandfather is injured in a fall. Though his touch still haunts her, Lil has let nothing stop her dream of opening the Chance Wildlife Refuge, but something - or someone - has been keeping a close watch. When small pranks escalate into heartless killing, the memory of an unsolved murder in these very hills has Cooper springing to action to keep Lil safe. They both know the dangers that lurk in the wild landscape of the Black Hills. And now they must work together to unearth a killer of twisted and unnatural instincts who has singled them out as prey', 1, '7.19', '2001-10-08', '2009-10-13 00:00:00'); -- -------------------------------------------------------- -- -- Table structure for table `book_author` -- CREATE TABLE IF NOT EXISTS `book_author` ( `book_id` tinyint(3) unsigned NOT NULL, `author_id` tinyint(3) unsigned NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `book_author` -- INSERT INTO `book_author` (`book_id`, `author_id`) VALUES (2, 1), (1, 2), (3, 3), (4, 4); -- -------------------------------------------------------- -- -- Table structure for table `book_cover` -- CREATE TABLE IF NOT EXISTS `book_cover` ( `book_id` tinyint(3) unsigned NOT NULL, `cover_id` tinyint(3) unsigned NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `book_cover` -- INSERT INTO `book_cover` (`book_id`, `cover_id`) VALUES (3, 1), (4, 1), (1, 2), (2, 2), (3, 2); -- -------------------------------------------------------- -- -- Table structure for table `book_language` -- CREATE TABLE IF NOT EXISTS `book_language` ( `book_id` tinyint(3) unsigned NOT NULL, `language_id` tinyint(3) unsigned NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `book_language` -- INSERT INTO `book_language` (`book_id`, `language_id`) VALUES (1, 1), (2, 1), (3, 1), (4, 1), (1, 2), (3, 2), (4, 2), (2, 3), (3, 3), (2, 4), (3, 4), (2, 5); -- -------------------------------------------------------- -- -- Table structure for table `book_location` -- CREATE TABLE IF NOT EXISTS `book_location` ( `book_id` tinyint(3) unsigned NOT NULL, `location_id` tinyint(3) unsigned NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `book_location` -- INSERT INTO `book_location` (`book_id`, `location_id`) VALUES (1, 1), (3, 1), (4, 1), (1, 2), (2, 2), (3, 2), (3, 3), (4, 3), (2, 4), (3, 5); -- -------------------------------------------------------- -- -- Table structure for table `category` -- CREATE TABLE IF NOT EXISTS `category` ( `id` tinyint(4) NOT NULL, `category_name` varchar(255) NOT NULL ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1; -- -- Dumping data for table `category` -- INSERT INTO `category` (`id`, `category_name`) VALUES (1, 'Romance'), (2, 'Art'), (3, 'Comedy'), (4, 'Horror'); -- -------------------------------------------------------- -- -- Table structure for table `cover` -- CREATE TABLE IF NOT EXISTS `cover` ( `id` tinyint(3) unsigned NOT NULL, `cover_name` varchar(20) NOT NULL ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1; -- -- Dumping data for table `cover` -- INSERT INTO `cover` (`id`, `cover_name`) VALUES (1, 'Soft'), (2, 'Hard'); -- -------------------------------------------------------- -- -- Table structure for table `language` -- CREATE TABLE IF NOT EXISTS `language` ( `id` tinyint(3) unsigned NOT NULL, `language_name` varchar(150) NOT NULL ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1; -- -- Dumping data for table `language` -- INSERT INTO `language` (`id`, `language_name`) VALUES (1, 'English'), (2, 'French'), (3, 'German'), (4, 'Spanish'), (5, 'Italian'), (6, 'Polish'); -- -------------------------------------------------------- -- -- Table structure for table `location` -- CREATE TABLE IF NOT EXISTS `location` ( `id` tinyint(3) unsigned NOT NULL, `location_name` varchar(255) NOT NULL ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1; -- -- Dumping data for table `location` -- INSERT INTO `location` (`id`, `location_name`) VALUES (1, 'London'), (2, 'Brighton'), (3, 'Bournemouth'), (4, 'Portsmouth'), (5, 'Southampton'), (6, 'Chichester'); -- -- Indexes for dumped tables -- -- -- Indexes for table `author` -- ALTER TABLE `author` ADD PRIMARY KEY (`id`); -- -- Indexes for table `book` -- ALTER TABLE `book` ADD PRIMARY KEY (`id`), ADD KEY `fk_category` (`category`); -- -- Indexes for table `book_author` -- ALTER TABLE `book_author` ADD PRIMARY KEY (`book_id`,`author_id`), ADD KEY `fk_author` (`author_id`); -- -- Indexes for table `book_cover` -- ALTER TABLE `book_cover` ADD PRIMARY KEY (`book_id`,`cover_id`), ADD KEY `fk_cover` (`cover_id`); -- -- Indexes for table `book_language` -- ALTER TABLE `book_language` ADD PRIMARY KEY (`book_id`,`language_id`), ADD KEY `fk_language` (`language_id`); -- -- Indexes for table `book_location` -- ALTER TABLE `book_location` ADD PRIMARY KEY (`book_id`,`location_id`), ADD KEY `fk_location` (`location_id`); -- -- Indexes for table `category` -- ALTER TABLE `category` ADD PRIMARY KEY (`id`); -- -- Indexes for table `cover` -- ALTER TABLE `cover` ADD PRIMARY KEY (`id`); -- -- Indexes for table `language` -- ALTER TABLE `language` ADD PRIMARY KEY (`id`); -- -- Indexes for table `location` -- ALTER TABLE `location` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `author` -- ALTER TABLE `author` MODIFY `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=5; -- -- AUTO_INCREMENT for table `book` -- ALTER TABLE `book` MODIFY `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=5; -- -- AUTO_INCREMENT for table `category` -- ALTER TABLE `category` MODIFY `id` tinyint(4) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=5; -- -- AUTO_INCREMENT for table `cover` -- ALTER TABLE `cover` MODIFY `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=3; -- -- AUTO_INCREMENT for table `language` -- ALTER TABLE `language` MODIFY `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=7; -- -- AUTO_INCREMENT for table `location` -- ALTER TABLE `location` MODIFY `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=7; -- -- Constraints for dumped tables -- -- -- Constraints for table `book` -- ALTER TABLE `book` ADD CONSTRAINT `fk_category` FOREIGN KEY (`category`) REFERENCES `category` (`id`) ON UPDATE CASCADE; -- -- Constraints for table `book_author` -- ALTER TABLE `book_author` ADD CONSTRAINT `fk_author` FOREIGN KEY (`author_id`) REFERENCES `author` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `fk_book` FOREIGN KEY (`book_id`) REFERENCES `book` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Constraints for table `book_cover` -- ALTER TABLE `book_cover` ADD CONSTRAINT `fk_book_cover` FOREIGN KEY (`book_id`) REFERENCES `book` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `fk_cover` FOREIGN KEY (`cover_id`) REFERENCES `cover` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Constraints for table `book_language` -- ALTER TABLE `book_language` ADD CONSTRAINT `fk_book_language` FOREIGN KEY (`book_id`) REFERENCES `book` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `fk_language` FOREIGN KEY (`language_id`) REFERENCES `language` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Constraints for table `book_location` -- ALTER TABLE `book_location` ADD CONSTRAINT `fk_book_location` FOREIGN KEY (`book_id`) REFERENCES `book` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `fk_location` FOREIGN KEY (`location_id`) REFERENCES `location` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; 

什么可能导致上述错误,因此没有返回任何结果,最好去做什么?谢谢。

0 个答案:

没有答案