PHP数组到字符串转换,mysql_fetch_assoc()需要参数

时间:2014-03-27 12:50:36

标签: php mysql

有人可以帮我解决我的代码,我无法让它工作。

我有一个html输入表单,我输入例如“这是一个样本”。 (数据保存在$ _POST ['Begriff'])

我想实现一个简单的翻译,以便检查“英语”栏中的“饮料”表格是否存在我输入样本句子中的每个单词,如果找到一行中相应行的每个条目,则输出。

现在我有两个问题: 一旦我将“$ wert中的英语”添加到select语句中,我得到:

Notice: Array to string conversion in nachlesen.php on line 34
Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given 

第二个问题:如何从返回的结果中再次将句子放在一起? (现在我得到每个找到的单词的输出,而不是一行)

这是我的代码:

if ( $_POST['Begriff'] <> "") 
{
$wert = explode(' ',$_POST['Begriff']);
$select = mysql_query ("SELECT * FROM drinks where English in $wert");
while ( $row = mysql_fetch_assoc($select))
  {
  echo ("$row[German] <br>");
  echo ("$row[English]<br>");
  }
}

先谢谢,丹尼尔

3 个答案:

答案 0 :(得分:0)

<?php
// premise: the user input in $_POST['Begriff'] is a string like 'This is a sample'
//first split it into single words
// preg_split: \s+ -> one or more whitespaces , PREG_SPLIT_NO_EMPTY -> no "empty" words
// e.g. " Mary had  a      little    lamb" -> array('Mary','had','a','little','lamb')
$words = preg_split('!\s+!', $_POST['Begriff'], -1, PREG_SPLIT_NO_EMPTY);

// now encode each string so that it can be used
// safely as a string-literal within your sql query
// see: sql injection
// this should be:
// $words = array_map(function($e) use($mysql) { return mysql_real_escape_string($e, $mysql); }, $words);
// but apparently you're not storing the resource that is returned by mysql_connect
// mysql_real_escape_string() is applied to each single element in $words
// e.g. array("it's", "been") -> array("it\\'s", "been")
$words = array_map('mysql_real_escape_string', $words);

// now put the string literals into your query 
// format: ... IN ('x','y','z')
// join(",", $words) gives you x,y,z
// join("','", $words) gives you x','y','z
// i.e. the first and the last ' has to be added "manually"
// keep in mind that for an empty array $words this will produce WHERE ... IN ('')
// better test that before even trying to build the query
$query = sprintf("
    SELECT
        German,English
    FROM
        drinks
    WHERE
        English IN ('%s')
", join("','", $words));

// send the query to the MySQL server
// should be: $result = mysql_query($query, $mysql);
$result = mysql_query($query);

// database query -> failure is always an option
if ( !$result ) {
    // add error handling here
}
else {
    // in case there is not a single match in the database
    // your script would print ...nothing
    // I don't like that - but that debatable
    // anway: wrapped in a fieldset
    echo '<fieldset><legend>results:</legends>';
    while( false!==($row=mysql_fetch_array($result, MYSQL_FETCH_ASSOC)) ) {
        printf('%s<br />%s<br />', 
          // just like on the input-side you had to worry about
          // sql injections
          // on the output side you want to avoid
          // that characters from the database can break your html structure
            htmlentities($row['German']),
            htmlentities($row['English'])
        );
    }
    echo '</fieldset>';
}

(脚本未经测试)

答案 1 :(得分:-1)

"SELECT * FROM drinks where English in ('". implode("','", $wert) . "')"

编辑:SQL注入安全查询:

$dsn = 'mysql:dbname=' . $settings['dbname'] . ';host=' . $settings['dbhost'];
$pdo = new PDO($dsn, $settings['dbuser'], $settings['dbpass'], array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

if ( $_POST['Begriff'] <> "") 
{
  $wert = explode(' ',$_POST['Begriff']);

  $placeholders = implode(',', array_fill(0, count($wert), '?'));


  $sth = $pdo->prepare("SELECT * FROM drinks WHERE English in ({$placeholders})");
  $sth->execute($wert);

  $rows = $sth->fetchAll();

  foreach($rows as $row) {
      print_r( $row );
  }

}

答案 2 :(得分:-1)

为什么不尝试implode()并将数组转换为字符串??

 if ( $_POST['Begriff'] <> "") 
 {

  //you'l have to replace all "spaces with ',' "
  $pattern = '/\s*,\s*/';
  $replace = "','";
  $wert = preg_replace($pattern, $replace, $_POST['Begriff']);

 $select = mysql_query ("SELECT * FROM drinks where English in ('$wert')");
 while ( $row = mysql_fetch_assoc($select))
   {
   echo ("$row[German] <br>");
   echo ("$row[English]<br>");
   }
 }

另一种解决方案(防止SQL注入)

 if ( $_POST['Begriff'] <> "") 
 {

  //replace multiple spaces
  $str1 = preg_replace( "/\s+/", " ", $_POST['Begriff'] );
  //convert to array, separated by space
  $arr=explode(" ",$str1);
  $safe_params=array();
  foreach($arr as $param){
     $safe_params[]=mysql_real_escape_string($param);
  }

  $wert=implode("','",$safe_params);

 $select = mysql_query ("SELECT * FROM drinks where English in ('$wert')");
 while ( $row = mysql_fetch_assoc($select))
   {
   echo ("$row[German] <br>");
   echo ("$row[English]<br>");
   }
 }

修改

根据语言处理查询输出

$german_words=array();
while ( $row = mysql_fetch_assoc($select))
{
   $german_words[$row['English']]=$row['Gernam'];
}

//$str1 is having english string
echo "English: ".$str1."<br/>";
echo "German : ";

//$arr is having array of words of $str1
foreach($arr as $eng_word){
   echo $german_words[$eng_word]." ";
}