1
我有以下注冊腳本,其中我的名字,電子郵件等通過簡單的html表單插入到數據庫中。從PHP獲取JSON
<?php
include("connect.php");
$error = "";
$response[]=array();
if(isset($_POST['submit'])){
$firstName = $_POST['fname'];
$lastName = $_POST['lname'];
$email = $_POST['email'];
$password = $_POST['password'];
$passwordConfirm = $_POST['passwordConfirm'];
$image = $_FILES['image']['name'];
$temp_image = $_FILES['image']['tmp_name'];
$imageSize = $_FILES['image']['size'];
//echo $firstName."<br/>".$lastName."<br/>".$email."<br/>".$password."<br/>".$passwordConfirm."<br/>".$image."<br/>".$imageSize."<br/>";
if(strlen($firstName)<3){
$error = "First name is too short";
}else if(strlen($lastName)<3){
$error = "Last name is too short";
}else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$error = "Please enter valid email address";
}else if(strlen($password)<8){
$error = "Password must be greater than 8 characters";
}else if($password !== $passwordConfirm){
$error = "Password does not match";
}else if($image == ""){
$error = "Please upload your image";
}else{
$insertQuery = "INSERT INTO users(firstName,lastName,email,password,image) VALUES('$firstName','$lastName','$email','$password','$image')";
$result = mysqli_query($con,$insertQuery);
if($result){
//upload image in images forlder
$sql = "SELECT * FROM users";
$selectQuery = mysqli_query($con,$sql);
if($selectQuery){
while($row = mysqli_fetch_assoc($selectQuery)){
$response[] = $row;
}
}
if(move_uploaded_file($temp_image,"images/$image")){
$error = "You are successfully regirestered";
}else{
$error = "Image is not uploaded";
}
}
}
}
?>
<?php
echo $error."<br/>";
echo json_encode($response);
?>
我所做的只是驗證表單,插入數據並最終從數據庫中選擇所有數據,以便它們可以表示爲JSON格式。
我得到的JSON是這個。
[[],{"id":"37","firstName":"Theo","lastName":"Tziomakas","email":"[email protected]","password":"testingpass","image":"56a5e6dc-d102-4f9a-bd5b-e6a217e5ad97.png"}]
如何可以採取空數組
[]
出JSON響應即。
[{"id":"37","firstName":"Theo","lastName":"Tziomakas","email":"[email protected]","password":"testingpass","image":"56a5e6dc-d102-4f9a-bd5b-e6a217e5ad97.png"}]
另外我該如何生成這樣的JSON?
{"status":"success","message":"Successfully registered"}
謝謝你這位先生。 – Theo
又如何{「狀態」:「成功」,「消息」:「成功註冊」} JSON響應? – Theo
對不起錯過了第二個問題。我在我的回答中添加了一條建議。 – RiggsFolly