简体   繁体   中英

PHP prepared statement -> only returns first letter from a column in database

I have this Code

        $sql = "SELECT name FROM data WHERE id=? LIMIT 0,1";
        //prepares statement 
        $stmt = self::getConnection()->prepare($sql);
        $stmt->bind_param("i", $id);
        $ids = array(1,2,3);
        foreach ($ids as $key => $id) {
            $stmt->execute();
            $stmt->bind_result($name);
            $stmt->fetch();
            $stmt->store_result();

            var_dump($name);
        }

My database table looks like this

id | name
1  | First Name
2  | Second Name
3  | Third Name

Now the output looks like this:

string(10) "First Name" 
string(1) "S" 
string(1) "T"

The first name is correct. But then it just outputs the first letter of the following rows. I don't know why. I tried it out with another column that is an integer-type. That worked. Just this string-type column doesn't.

I also tried to change the $ids-Array in something like this: $ids = array(2,3,1) . Then it outputs

string(11) "Second Name" 
string(1) "T" 
string(1) "F"

I have no clue what to do. Does anyone see my mistake?

EDIT:

PHP 5.5 and Mysql 5.5.31 and var_dump:

EDIT 2:

-- phpMyAdmin SQL Dump
-- version 4.0.5
-- http://www.phpmyadmin.net
--
-- Host: rdbms
-- Erstellungszeit: 07. Jun 2014 um 19:21
-- Server Version: 5.5.31-log
-- PHP-Version: 5.3.27

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 utf8 */;

--
-- Datenbank: `DB1673555`
--

-- --------------------------------------------------------


CREATE TABLE IF NOT EXISTS `data` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` tinytext NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;


INSERT INTO `data` (`id`, `name`) VALUES
(1, 'First Name'),
(2, 'Second Name'),
(3, 'Third Name');

/*!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 */;

I just saw that the dump says I use PHP 5.3. But on the website of strato they say 5.5

Here's what I found. I think reason it's in type tinytext . Because when I use your database dump then the error reproduced on my local PC. But as soon as I changed the column type to varchar 255 then code work fine.

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