I am trying to return an error message for my react native register screen. The .php script called is :
<?php
include 'DBConfig.php';
// Creating connection.
$con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName);
if ($con == false) {
$ShitMSG = "Can't connect to database" ;
$ShitJson = json_encode($ShitMSG);
echo $ShitJson ;
}
// Getting the received JSON into $json variable.
$json = file_get_contents('php://input');
// decoding the received JSON and store into $obj variable.
$obj = json_decode($json,true);
// Populate User name from JSON $obj array and store into $name.
$name = $obj['name'];
// Populate User email from JSON $obj array and store into $email.
$email = $obj['email'];
//Checking Email is already exist or not using SQL query.
$CheckSQL = "SELECT * FROM UserRegistrationTable WHERE email='$email'";
$check = mysqli_fetch_array(mysqli_query($con,$CheckSQL));
if(isset($check)) {
$EmailExistMSG = "L'E-mail est déja utilisé !";
$EmailExistJson = json_encode($EmailExistMSG);
echo $EmailExistJson ;
}
else {
// Creating SQL query and insert the record into MySQL database table.
$Sql_Query = "insert into UserRegistrationTable (name,email) values ('$name','$email')";
if(mysqli_query($con,$Sql_Query)) {
$MSG = 'Utilisateur enregistré !' ;
$json = json_encode($MSG);
echo $json ;
}
else {
echo 'Réessayez';
}
}
mysqli_close($con);
?>
When called, it receives a body looking like
body: JSON.stringify({
name: UserName,
email: UserEmail
})
Consisting of inputs for my user's name and email. DBconfig.php is another PHP file where my db's ids are, to connect to it.
My script is launched by my react native app, from this function :
class LoginScreen extends React.Component {
constructor (props) {
super(props)
this.state = {
UserName: '',
UserEmail: ''
}
}
UserRegistrationFunction () {
const { UserName } = this.state
const { UserEmail } = this.state
fetch('http://c2isante.fr/appsante/login.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: UserName,
email: UserEmail
})
}).then((response) => response.json())
.then((responseJson) => {
Alert.alert(responseJson)
}).catch((error) => {
console.error(error)
})
}
render () {
return (
<View style={styles.MainContainer}>
<Text style={{ fontSize: 20, color: '#000', textAlign: 'center', marginBottom: 15 }}>User Registration Form</Text>
<TextInput
placeholder='Entrez votre nom'
onChangeText={UserName => this.setState({...this.state, UserName})}
underlineColorAndroid='transparent'
/>
<TextInput
placeholder='Entrez votre E-mail'
onChangeText={UserEmail => this.setState({...this.state, UserEmail})}
underlineColorAndroid='transparent'
/>
<Button title="M'enregistrer" onPress={this.UserRegistrationFunction.bind(this)} color='#2196F3' />
</View>
)
}
}