我是Angular和PHP的新手。我试图修改教程http://phpenthusiast.com/blog/ajax-with-angular-and-php。我希望第二个值是一个复选框,并使用Angular和PHP读取它的值。我现在遇到的问题是复选框在单击时读取值,但在未选中时无法输入0(即false)。我试图将PHP的布尔值转换为整数,但它没有帮助。我的代码如下(原始教程的更改):
的index.html
<div>
<label>Phone</label>
<input type="checkbox" ng-model="newPhone">
</div>
post.php中
<?php
require 'connect.php';
$connect = connect();
// Add the new data to the database.
$postdata = file_get_contents("php://input");
var_dump($postdata);
if(isset($postdata) && !empty($postdata))
{
$request = json_decode($postdata);
$newName = preg_replace('/[^a-zA-Z ]/','',$request->newName);
//old code to get number
//$newPhone = preg_replace('/[^0-9 ]/','',$request->newPhone);
//new code to get boolean converted to int
$newPhone = (int)$request->newPhone;
if($newName == '' || $newPhone == '') return;
$sql = "INSERT INTO `people`(`name`, `phone`) VALUES ('$newName','$newPhone')";
mysqli_query($connect,$sql);
}
exit;
感谢您的帮助
答案 0 :(得分:1)
使用break
打破IF
条件或FOR
循环。
return
的情况下使用 functions
if($newName == '' || $newPhone == '') break;
另一种干净的方法是扭转你的状况,即仅在两个值都存在时才更新。
if(!empty($newName) && !empty($newPhone))
{
$sql = "INSERT INTO `people`(`name`, `phone`) VALUES ('$newName','$newPhone')";
mysqli_query($connect,$sql);
}
empty会检查blank
和null
值。
<强>更新强>
要在用户未选择值的情况下插入空白或0值,请删除检查空白值的条件并将其设置为不足。
if(isset($postdata) && !empty($postdata))
{
$request = json_decode($postdata);
$newName = preg_replace('/[^a-zA-Z ]/','',$request->newName);
// Assign blank value in case its empty
$newName = !empty($newName) ? $newName: '';
$newPhone = (int)$request->newPhone;
// Assign blank value in case its empty
$newPhone = !empty($newPhone) ? $newPhone : '';
$sql = "INSERT INTO `people`(`name`, `phone`) VALUES ('$newName','$newPhone')";
mysqli_query($connect,$sql);
}