I have a code in PHP where a field value entered should match with the values in a table in a database. If match found it must do some work, or else it must say "match was not found".
But whenever I check with values which are not in the table (database), it says "match has been found".
Here is the code:
<?php
include"conn.php";
if($_SERVER['REQUEST_METHOD'] == "POST"){
// Get data
// Vehicle Number
$vehicle_number = isset($_POST['VehicleNumber']) ?mysql_real_escape_string($_POST['VehicleNumber']) : "";
//ID card Nos.
$idcardno1= isset($_POST['idno1']) ? mysql_real_escape_string($_POST['idno1']) : "";
$idcardno2= isset($_POST['idno2']) ? mysql_real_escape_string($_POST['idno2']) : "";
//Text Messages
$Textmsg = isset($_POST['yourtext']) ? mysql_real_escape_string($_POST['yourtext']) : "";
if($idcardno1 == NULL )
{
//echo "Blank Fields";
$json = array("status" => "Failure", "msg" => "User has entered one or more than one null values so couldn't go for database operations");
}
else
{
$q=mysql_query("SELECT * FROM profile WHERE IDcardno1 ='$idcardno1' OR IDcardno2 = '$idcardno2' OR VehicleNumber ='$vehicle_number'" )or die(mysql_error());
if($q)
{
$num=mysql_num_rows($q);
if($num==0)
{
$json = array("status" => "Failure", "msg" => "Information not found");
print $num;
}
else{
$json = array("status" => "success", "msg" => "Information is stored and match has been found");
}
}
}
}
else{
$json = array("status" => "Failure", "msg" => "POST_Request method not accepted");
}
mysql_close($con);
/* Output header */
//header('Content-Type: application/json');
echo json_encode($json);
?>
Because you are using OR in your SQL query, it will return any database rows where there is an empty database value and empty form value. This may return rows where you were not expecting them (depending on your intention)
If that's the case, you may want to ONLY match on field values that are actually populated by changing the query to something like this:
$q = mysql_query("SELECT * FROM profile WHERE (IDcardno1 ='$idcardno1' AND '$idcardno1' <> '') OR (IDcardno2 = '$idcardno2' AND '$idcardno2' <> '') OR (VehicleNumber ='$vehicle_number' AND '$vehicle_number' <> '')" )or die(mysql_error());
(This is just one way to approach it)
Related
I am currently working on a JSON Api project using php and mysql database I have been able to create a post and get function successfully i am trying to implement a filter feature but only able to retrieve one result even when more than one of the result has similar names Example my database contains "chuck", and "chuck Morris" when i search for "chuck" i want to be able to retrieve both names but am only getting the result with the exact name i.e "chuck" just one result
Here is my code for the search function
public function read_singleName() {
$sql_query = "SELECT * FROM ".$this->table_name . " WHERE name = ?";
$obj = $this->conn->prepare($sql_query);
$obj->bind_param("s", $this->name);
$obj->execute();
$data = $obj->get_result();
return $data->fetch_assoc();
}
Here is the code to display the results
if($_SERVER['REQUEST_METHOD'] === "GET"){
$artist_name = isset($_GET['name']) ? strval($_GET['name']) : "";
if(!empty($some_name)){
$some->name = $some_name;
$some_data = $some->read_singleName();
if(!empty($some_data)){
http_response_code(200);
echo json_encode(array(
"status" => 1,
"data" => $some_data
));
} else{
http_response_code(500);
echo json_encode(array(
"status" => 0,
"message" => "Name Not Found"
));
}
}
} else{
http_response_code(503);
echo "Access Denied";
echo json_encode(array(
"status" => 000,
"message" => "Failed"
));
}
No sure what $this->conn is but I think you should call fetch_assoc() in a while loop until there are no more records
while($record = $data->fetch_assoc()){
// do something with $record
}
Also the query should be like this: SELECT * FROM ".$this->table_name . " WHERE name LIKE '%chuck%'
You need to use LIKE, not =.
When you do this:
$sql_query = "SELECT * FROM ".$this->table_name . " WHERE name = ?";
You will only get exact matches.
What you need is this:
$sql_query = "SELECT * FROM ".$this->table_name . " WHERE name LIKE ?";
And then use % characters as wild cards.
This will find everything that begins with "chuck"
WHERE name LIKE 'chuck%'
Another example where "chuck" can be anywhere.
WHERE name LIKE '%chuck%'
if ($_GET['category'] == "ebooks")
{ $tableName = $smallsubcodewithoutspace.'_ebooks';
$sectionTitle = "Ebook";
}
elseif ($_GET['category'] == "syllabus")
{ $tableName = $smallsubcodewithoutspace.'_syllabus';
$sectionTitle = "Syllabus";
}
elseif ($_GET['category'] == "pnotes")
{ $tableName = $smallsubcodewithoutspace.'_pnotes';
$sectionTitle = "Practical Note";
}
elseif ($_GET['category'] == "assignments")
{ $tableName = $smallsubcodewithoutspace.'_assignments';
$sectionTitle = "Assignment";
}
elseif ($_GET['category'] == "tnotes")
{ $tableName = $smallsubcodewithoutspace.'_tnotes';
$sectionTitle = "Theory Notes";
}
//if form has been submitted process it
if(isset($_POST['submit'])){
$_POST = array_map( 'stripslashes', $_POST );
//collect form data
extract($_POST);
//very basic validation
if($contentTitle ==''){
$error[] = 'Please enter the Content Title !';
}
if($contentLink ==''){
$error[] = "Please enter the Content Link !";
}
if(!isset($error)){
try {
//insert into database
$stmt = $db->prepare("INSERT INTO `$tableName` (contentTitle,contentLink,contentAuthor) VALUES (:contentTitle, :contentLink, :contentAuthor)") ;
$stmt->execute(array(
':contentTitle' => $contentTitle,
':contentLink' => $contentLink,
':contentAuthor' => $contentAuthor
));
//redirect to index page
header('Location: add-content.php?notallowed=true');
exit;
} catch(PDOException $e) {
echo $e->getMessage();
}
}
}
//check for any errors
if(isset($error)){
foreach($error as $error){
echo '<div align="center" class="alertpk"><div class="alert alert-warning" role="alert">'.$error.'</div></div>';
}
}
Actually, problem started when I tried inserting Table name with variable. Tables exist in database. total 5 databases are there in which I will insert data according to users selection, but when form executed, a error is thrown saying:
SQLstate[42000]: SYNTAX ERROR OR ACCESS VIOLATION 1103, INCORRECT TABLE NAME ' '
The error INCORRECT TABLE NAME '' error means you don't have a value in $tableName. Your $_GET['category'] is not picking up a recognized value or the extract($_POST) is changing $tableName to an empty value.
I got the solution, I shifted tableVariables section inside try and its now working.
var dump your variable, post to see what value comes up.
I have a database in which there are NOT NULL and NULL fields (the NULLs are of the VARCHAR type).
When I try to enter data in the NULL fields via my query, it does not insert them.
The data isn't entered all at the same time:
with a form I insert the data in the NOT NULL fields
with another form insert the data in the NULL fields.
Why doesn't the query for entering data in the NULL fields sork?
I tried to find an answer to similar questions, but they don't work or are not suitable for my problem:
MySQL Insert Select - NOT NULL fields
Insert NULL into DATE field MySQL 5.6
FIRST FORM register.php
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
// echo $_SERVER["DOCUMENT_ROOT"]; // /home1/demonuts/public_html
//including the database connection file
include_once("config.php");
$id_akR = $_POST['id_akR'];
$numero_telefonoR = $_POST['numero_telefonoR'];
if($id_akR == '' || $numero_telefonoR == '' ){
echo json_encode(array( "status" => "false","message" => "Parameter missing!") );
}else{
$query= "SELECT * FROM RistoratoreAK WHERE id_akR='$id_akR' OR numero_telefonoR ='$numero_telefonoR' ";
$result= mysqli_query($con, $query);
$query2 = "SELECT ak_id, numero_telefono FROM AccountKit WHERE ak_id = '$id_akR' OR numero_telefono = '$numero_telefonoR'";
$result2= mysqli_query($con, $query2);
if(mysqli_num_rows($result) > 0){
echo json_encode(array( "status" => "false","message" => "User already exist in Ristoratore!") );
}else if(mysqli_num_rows($result2) > 0) {
echo json_encode(array( "status" => "false","message" => "User already exist in Cliente!") );
}else{
$query = "INSERT INTO RistoratoreAK (id_akR, numero_telefonoR) VALUES ('$id_akR','$numero_telefonoR')";
if(mysqli_query($con,$query)){
$query= "SELECT * FROM RistoratoreAK WHERE numero_telefonoR ='$numero_telefonoR'";
$result= mysqli_query($con, $query);
$emparray = array();
if(mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_assoc($result)) {
$emparray[] = $row;
}
}
echo json_encode(array( "status" => "true","message" => "Successfully registered!" , "data" => $emparray) );
}else{
echo json_encode(array( "status" => "false","message" => "Error occured, please try again!") );
}
}
mysqli_close($con);
}
} else{
echo json_encode(array( "status" => "false","message" => "Error occured, please try again!") );
}
?>
SECOND FORM register2.php
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
include 'config2R.php';
$con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName);
$nome = $_POST['nomeR'];
$cognome = $_POST['cognomeR'];
$data_nascita = $_POST['data_nascitaR'];
$sesso = $_POST['sessoR'];
$nome_ristorante = $_POST['nome_ristoranteR'];
$CheckSQL = "SELECT nome_ristorante FROM RistoratoreAK WHERE nome_ristorante='$nome_ristorante'";
$check = mysqli_fetch_array(mysqli_query($con,$CheckSQL));
if(isset($check)){
echo 'Ristorante già registrato';
}
else{
$Sql_Query = "INSERT INTO RistoratoreAK (nomeR,cognomeR,data_nascitaR,sessoR,nome_ristorante) values ('$nome','$cognome','$data_nascita','$sesso','$nome_ristorante')";
if(mysqli_query($con,$Sql_Query))
{
echo 'Registration Successfully';
}
else
{
echo 'Something went wrong';
}
}
}
mysqli_close($con);
?>
My DB contains a table called "RistoratoreAK", the fields are :
id INT PrimaryKey
id_ak VARCHAR NOT NULL
number VARCHAR NOT NULL
nomeR VARCHAR NULL
cognomeR VARCHAR NULL
sessoR VARCHAR NULL
data_nascitaR VARCHAR NULL
nome_ristorante VARCHAR NULL
note: Excuse me if the code isn't secure (I didn't use PDO), this code is just a test to learn how to upload data to the database.
After the first form, you INSERT a new entry into your table with the id and id_ak. This is fine, and it works.
But after the second form, you should not INSERT another entry, but UPDATE an existing one instead (the one that you created before).
To update it, you need to know the id of the existing entry.
Having that, you can make an UPDATE query like this:
UPDATE
RistoratoreAK
SET
nomeR = '$nome',
cognomeR = '$cognome',
data_nascitaR = '$data_nascita',
sessoR = '$sesso',
nome_ristorante = '$nome_ristorante'
WHERE
id = $existing_id
Trying to implement a post webservice in PHP so that finally it can be used in ios app for communicating to DB. Can you please identify the mistake.
Please find the code below. It is saying that "Request Method not accepted" status 0 returned
<?php
// Create connection
$con=mysqli_connect("myhost.com","myuser","mypassword","mydb");
if($_SERVER['REQUEST_METHOD'] == "POST"){
// Get data
$lat= isset($_POST['lat']) ? mysql_real_escape_string($_POST['long']) : "";
$long= isset($_POST['long']) ? mysql_real_escape_string($_POST['long']) : "";
$timeStamp = isset($_POST['timeStamp']) ? mysql_real_escape_string($_POST['timeStamp']) : "";
$deviceId = isset($_POST['deviceId']) ? mysql_real_escape_string($_POST['deviceId']) : "";
// Insert data into data base
$sql = "INSERT INTO `gpsReporting` (`lat`, `long`, `timeStamp`, `deviceId`) VALUES ('$lat', '$long', '$timeStamp', '$deviceId');";
$qur = mysql_query($sql);
if($qur){
$json = array("status" => 1, "msg" => "Done User added!");
}else{
$json = array("status" => 0, "msg" => "Error adding user!");
}
}else{
$json = array("status" => 0, "msg" => "Request method not accepted");
}
#mysql_close($conn);
/* Output header */
header('Content-type: application/json');
echo json_encode($json);
I have this script that checks a submitted form. It checks if all fields are all filled out, and checks if the user has submitted the form before. It also checks if the entered data is already in the database or not. When I try to check if the entered data is in the database, it always returns false. My question is: How can I efficiently check if the POST values are the same?
Code:
<?php
error_reporting(E_NOTICE ^ E_ALL);
$Name = $_POST['name'];
$ID = $_POST['id'];
$Topic_1 = $_POST['1'];
$Topic_2 = $_POST['2'];
$Topic_3 = $_POST['3'];
$Topic_4 = $_POST['4'];
$Topic_5 = $_POST['5'];
$Topic_6 = $_POST['6'];
$Topic_7 = $_POST['7'];
$Topic_8 = $_POST['8'];
$Topic_9 = $_POST['9'];
$Topic_10 = $_POST['10'];
$Topic_11 = $_POST['11'];
$Topic_12 = $_POST['12'];
$Topic_13 = $_POST['13'];
$Topic_14 = $_POST['14'];
$Topic_15 = $_POST['15'];
$IP = $_SERVER['REMOTE_ADDR'];
$Connect = new mysqli("127.0.0.1", "root", "", "Data");
$Check = 'SELECT * FROM Submissions WHERE School_ID = "'.$ID.'" AND IP = "'.$IP.'"';
$Insert = 'INSERT INTO Submissions (Name, School_ID, Topic_1, Topic_2, Topic_3, Topic_4, Topic_5, Topic_6, Topic_7, Topic_8, Topic_9, Topic_10, Topic_11, Topic_12, Topic_13, Topic_14, Topic_15, IP) VALUES ("'.$Name.'", "'.$ID.'", "'.$Topic_1.'", "'.$Topic_2.'", "'.$Topic_3.'", "'.$Topic_4.'", "'.$Topic_5.'", "'.$Topic_6.'", "'.$Topic_7.'", "'.$Topic_8.'", "'.$Topic_9.'", "'.$Topic_10.'", "'.$Topic_11.'", "'.$Topic_12.'", "'.$Topic_13.'", "'.$Topic_14.'", "'.$Topic_15.'", "'.$IP.'")';
if($Name && $ID != "")
{
if($Result = $Connect->query($Check))
{
$Rows = $Result->num_rows;
if($Rows == 0)
{
if($_POST != $_POST)
{
if($Go = $Connect->prepare($Insert))
{
if($Go->execute())
{
echo 'Thanks';
}
else
{
echo 'There Was An Error';
}
}
else
{
echo 'There Was An Error';
}
}
else
{
echo 'No Two Values Can Match.';
}
}
else
{
echo 'You Cant Vote Twice.';
}
$Result->close();
}
else
{
echo 'There Was An Error.';
}
}
else
{
echo 'Please Fill Out All Fields';
}
$Connect->close();
Your if statement should look like
if($name != "" && $check != "")
Here's the error:
if($_POST != $_POST)
You do probably want to compare the result from the db with the $_POST instead.
$Row = $Result->fetch_assoc();
if($Row != $_POST)
Prior to doing a comparison use var_dump() on the variables to check what they actually contain.
var_dump($Name);
var_dump($ID);
exit();
Then check for a negative or positive match.
if( !empty($Name) && empty($ID) ){
exit('ah, name filled in but not id ...');
}
You can even spoof that in a separate file.
<?php
$Name = 'Bob';
$ID = ''; // or use 0 or any test you want
var_dump($Name);
var_dump($ID);
if( !empty($Name) && empty($ID) ){
exit('ah, name filled in but not id ...');
}
Isolating problems like this will help you develop incrementally, get something working, then add more lines till you arrive at your destination.
To check if not two POST values are the same:
array_diff($_POST, array_unique($_POST));
What you looking for is following
$_POST['1'] = 'a';
$_POST['2'] = 'b';
$_POST['3'] = 'c';
$_POST['4'] = 'a';
$_POST['5'] = 'd';
$results = array_unique($_POST);
var_dump($results);
returns:
array
1 => string 'a' (length=1)
2 => string 'b' (length=1)
3 => string 'c' (length=1)
5 => string 'd' (length=1)
You can't really so easily check if a person did submit a form before.
One way is to add one more hidden field to form if the request came with POST.
Something like that:
<form method="POST" action="">
<?php
if(isset($_POST['submit'])) {
echo '<input type="hidden" name="second_post" value="1">';
} ?>
<!-- Other form items -->
<input type="submit" name="submit" value="1">
</form>
Then you can check is it a second time with:
if(isset($_POST['second_post'])) {
// Second time of form post;
} else {
// First (or zero) time post.
}