1

我正在从 PHP 文件运行插入语句,然后运行一些代码来检查插入是否有效。PHP 告诉我“成功”。但是当我检查我的数据库以查看记录是否存在时,它不存在。此外,当我直接在 MySQL 管理员中运行 sql 语句时,它工作正常。我很确定我没有插入错误的数据库或表。这是代码的清理版本:

  $sql = "INSERT INTO companies (name, source_id, source_site, seeking_cf, currency, i_target, equity_offered, money_raised, num_investors, raised_pct, descr, city, state, country, categories_id, logo) VALUES (\"XYZ Widgets\", \"31\", 22, 1, \"£\", 250000, 0, 0, 0, 0, \"(Business Plan\", \"London\", \"\", \"UK\", 0, \"http://www.website.com/xyz.jpg\")";
  $rs = mysql_query($sql, $conn);  
  if(mysql_affected_rows($conn) == 0) { 
    $utoh = "fail"; 
  } else { 
    $utoh = "success";      
  }
  echo $utoh;

所以结果显示“成功”,但记录不在数据库中。PHP 是 5.3 版。MySQL是5.5。

4

4 回答 4

2

尽管我讨厌使用mysql_,但您应该对mysql_query语句进行错误检查...

<?php

$sql = "INSERT INTO companies (name, source_id, source_site, seeking_cf, currency, i_target, equity_offered, money_raised, num_investors, raised_pct, descr, city, state, country, categories_id, logo) VALUES (\"XYZ Widgets\", \"31\", 22, 1, \"£\", 250000, 0, 0, 0, 0, \"(Business Plan\", \"London\", \"\", \"UK\", 0, \"http://www.website.com/xyz.jpg\")";
$rs = mysql_query($sql, $conn);  
if (!$rs)
{
    echo mysql_error();
}
else
{
    echo 'success';
}

我们现在可以看到错误是什么。

于 2012-09-05T15:20:29.180 回答
1

使用single quotes而不是双引号。

您的代码容易发生SQL 注入。使用PDOMYSQLI

使用 PDO 扩展的示例:

<?php

    $stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
    $stmt->bindParam(1, $name);
    $stmt->bindParam(2, $value);

    // insert one row
    $name = 'one';
    $value = 1;
    $stmt->execute();

?>

这将允许您使用单引号插入记录。

于 2012-09-05T15:18:12.080 回答
1

尝试这个:

$sql = "INSERT INTO companies (name, source_id, source_site, seeking_cf, currency, i_target, equity_offered, money_raised, num_investors, raised_pct, descr, city, state, country, categories_id, logo) VALUES (\"XYZ Widgets\", \"31\", 22, 1, \"£\", 250000, 0, 0, 0, 0, \"(Business Plan\", \"London\", \"\", \"UK\", 0, \"http://www.website.com/xyz.jpg\")";
  $rs = mysql_query($sql, $conn);  
  if(!$rs) { 
    $utoh = "fail"; 
  } else { 
    $utoh = "success";      
  }
  echo $utoh;
于 2012-09-05T15:20:29.953 回答
0

你试过了吗?:

1:

  mysql_query("set names utf8;");
    before mysql_query($insert)?

2:

在查询中更改引号 " by '

于 2012-09-05T15:32:44.837 回答