如何使用php用逗号分隔mysql行值?

时间:2014-05-02 13:18:35

标签: php mysql string

我尝试使用以下代码输出每个学生father_contact,首先合并它们,然后用逗号分隔每个数字,但无法使其正常工作。请帮帮我。

$sql = "SELECT Fathers_Contact FROM student WHERE Class ='$class' AND Section='$s' and Year='$y'";
$result = mysql_query($sql);

if (!$result) {
    die("Query not working");
} 

$mbno_arr = array();

while ($row = mysql_fetch_array($result)) {
    $mbno_arr[] = $row[0];
}

$mbno_list = implode(',', $mbno_arr);//expect here is: 9867656543,9867656443,9867654543

if(empty($mbno_list)){
    echo "No number is there";
    exit;
}

if(empty($msg)){
    echo "Message empty!";
    exit;
}

Father_contact是十位数的手机号码。

2 个答案:

答案 0 :(得分:1)

// Escapes special characters in a string for use in an SQL statement
$SQL = sprintf(
        "SELECT Fathers_Contact 
         FROM student 
         WHERE Class = '%s' AND Section = '%s' and Year = '%s'", 
        mysql_real_escape_string($class), 
        mysql_real_escape_string($s), 
        mysql_real_escape_string($y)
);

// Result or die (print mysql error)
$result = mysql_query($SQL) or die( mysql_error() );

// Check if result has rows
if( mysql_numrows($result) > 0 )
{
    $mbno_arr = array();

    while ( $row = mysql_fetch_array($result) )
        $mbno_arr[] = $row[0];

    if( count($mbno_arr) > 0)
        echo implode(',', $mbno_arr);
    else
        echo 'No number is there';
}
else
{
    echo 'No result for query';
}

// free result
mysql_free_result($result);

NB 使用PDOmysqli。不推荐使用mysql_ *

答案 1 :(得分:0)

首先,mysql_*现已正式弃用。请使用PDOMySQLi

你可以试试这个:

<?php

// Connect
$mysqli = new mysqli("localhost", "my_user", "my_password", "my_database");
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

// Query
$query = "SELECT Fathers_Contact FROM student WHERE Class = ? AND Section = ? and Year = ?";
if ($stmt = $mysqli->prepare($query)) {
{
    // Bind params
    $stmt->bind_param("sss",
        $class,
        $s,
        $y);

    // Execute statement
    $stmt->execute();

    // fetch associative array
    $mbno_arr = array();
    $result = $stmt->fetch_result();
    while ($row = $result->fetch_assoc())
    {
        // Build data
        $mbno_arr[] = $row['Fathers_Contact'];
    }

    // close statement
    $stmt->close();

    // Debug?
    $mbno_list = implode(',', $mbno_arr);
    if (empty($mbno_list)) {
        echo "No number is there";
    } else {
        echo "Query Results: $mbno_list";
    }
}

// Close Connection
$mysqli->close();

?>