我是一名 Android 开发人员,对 php 几乎一无所知。我有一个使用 Google 推送通知并且运行良好的应用程序。我遇到的问题是,当同一部手机向谷歌注册时,来自谷歌的 regID 必须存储在我的数据库中。如果我将应用程序推到手机上说 4 次,那么我将在数据库中有 4 行指向一部手机。
我正在尝试检查数据库以查看给定 regID 是否存在记录。我正在尝试使用 sqlsrv_has_rows() 来执行此操作。如果记录存在与否,下面的代码会编译但不会插入记录。
任何人都可以看到问题是什么?
提前致谢,
马特
public function storeUser($companyid, $gcm_regid) {
$strCompanyID = strval($companyid);
$strRegID = strval($gcm_regid);
$serverName = "LOCALHOST\SQLEXPRESS";
$uid = "gcm";
$pwd = "gcm";
$databaseName = "gcm";
$connectionInfo = array(
"UID" => $uid,
"PWD" => $pwd,
"Database" => $databaseName
);
$db = sqlsrv_connect($serverName, $connectionInfo)
or die("Unable to connect to server");
$query = "
SELECT *
FROM GcmUsers
WHERE gcuRegID = " . $strRegID;
$resultQueryRegID = sqlsrv_query($db, $query);
if ($resultQueryRegID) {
$rows = sqlsrv_has_rows($resultQueryRegID);
if ($rows === true) {
//echo "There are rows. <br />";
} else {
// echo "There are no rows. <br />";
$queryInsert = "
INSERT INTO GcmUsers
(gcuCompanyID, gcuRegID)
VALUES
('$strCompanyID','$strRegID')
";
$result = sqlsrv_query($db, $queryInsert);
}
}
}
[编辑 1]
public
function storeUser($companyid, $gcm_regid) {
$strCompanyID = strval($companyid);
$strRegID = strval($gcm_regid);
$serverName = "LOCALHOST\SQLEXPRESS";
$uid = "gcm";
$pwd = "gcm";
$databaseName = "gcm";
$connectionInfo = array("UID" => $uid, "PWD" => $pwd, "Database" => $databaseName);
$db = sqlsrv_connect($serverName, $connectionInfo) or die("Unable to connect to server");
$sql = "SELECT * FROM GcmUsers where gcuRegID = ?";
// Initialize parameters and prepare the statement.
// Variables $qty and $id are bound to the statement, $stmt.
$stmt = sqlsrv_prepare($db, $sql, array(&$strRegID));
if (!$stmt) {
die(print_r(sqlsrv_errors(), true));
}
$result = sqlsrv_execute($stmt);
$rows = sqlsrv_has_rows($result);
if ($rows === true) {
// echo "There are rows. <br />";
} else {
// echo "There are no rows. <br />";
$queryInsert = "INSERT INTO GcmUsers ( gcuCompanyID, gcuRegID) values ('$strCompanyID','$strRegID')";
$result = sqlsrv_query($db, $queryInsert);
}
}
[编辑2]
$sql = "SELECT * FROM GcmUsers where gcuRegID = ?";
// Initialize parameters and prepare the statement.
// Variables $qty and $id are bound to the statement, $stmt.
$stmt = sqlsrv_prepare( $db, $sql, array( &$strRegID));
if( !$stmt ) {
die( print_r( sqlsrv_errors(), true));
}
$result = sqlsrv_execute( $stmt );
if (sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
// Got rows
}else{
// Not rows
$queryInsert = "INSERT INTO GcmUsers ( gcuCompanyID, gcuRegID) values ('$strCompanyID','$strRegID')";
$result = sqlsrv_query($db, $queryInsert);
}