I have a form and 2 input fields one for ID and one for Information, when I'm storing a values I need to check if the ID exists in table num 1 or not if it's exist then store the information in table num 2 if isn't exist then say it's an invalid ID, and here is my code.
Ps the ID is already exist in another table and I want to store the information in another table, and I don't have any problems with join or something else I can store immediately if the second condition doesn't exist and in database it will check by auto if the id exists or not but I want to check here if I write invalid or not.
<?php
if (isset($_POST['submitInfo'])) {
require 'dbh.php';
$ID = $_POST['ID'];
$Info = $_POST['DataInfo'];
$check = "SELECT ID FROM info";
$cresult = mysqli_query($conn, $check);
$cresult1 = mysqli_store_result($cresult);
if (!preg_match("/^[0-9]*$/", $ID)) {
header("Location: ../Data.php?error=invalidID");
exit();
} else if (mysqli_num_rows($cresult1) == 0 ) {
header("Location: ../Data.php?error=invalidID2");
exit();
} else {
$sql = "INSERT into datainfo (ID,Information) values (?,?)";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../Data.php?error=sqlerror");
exit();
} else {
mysqli_stmt_bind_param($stmt, "is", $ID, $Info);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
header("Location: ../Data.php?signup=success");
exit();
}
}
}
i fixed it:)
<?php
if (isset($_POST['submitInfo'])) {
require 'dbh.php';
$ID = $_POST['ID'];
$Info = $_POST['DataInfo'];
if (empty($ID) || empty($Info)) {
header("Location: ../Data.php?error=emptyFields");
exit();
} else if (!preg_match("/^[a-zA-Z0-9- ]*$/", $Info)) {
header("Location: ../Data.php?error=invalidChar");
exit();
} else if (!preg_match("/^[0-9]*$/", $ID)) {
header("Location: ../Data.php?error=invalidID");
exit();
} else {
$sql = "select ID from info where ID=?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../Data.php?error=sqlerror");
exit();
} else {
mysqli_stmt_bind_param($stmt, "i", $ID);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$resultCheck = mysqli_stmt_num_rows($stmt);
if ($resultCheck > 0) {
$sql = "insert into datainfo (ID,Information) values (?,?);";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../Data.php?error=sqlerror");
exit();
} else {
mysqli_stmt_bind_param($stmt, "is", $ID, $Info);
mysqli_stmt_execute($stmt);
header("Location: ../Data.php?signUp=success");
exit();
}
} else {
header("Location: ../Data.php?error=thisIDdoesntExist");
}
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.