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
Related
I have table named books, this table will store the data of each book . each book has 5 pages only and each page has different details which belong to the same book. the name of the book stored in a column named "jalad" and the pages stored in a column named "sanad"
I want PHP allows to me inserted a new book after totally completing the insertion of the first book which has five-page and in case I entered less than 5 pages then will stop me to insert a new book before completing the first one. Any idea, please. I used this code but it does not work perfectly. Please any help.
table here :
The code:
<?php
// connect to the database
// $serverName = "SALARY_SERVER\SALARY_SERVER";
//$database = "roatb";
$serverName = "LENOVO";
$database = "tt";
$connectionInfo = array( "Database"=>$database );
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn )
{
echo "Connection established.\n";
}
else
{
echo "Connection could not be established.\n";
die( print_r( sqlsrv_errors(), true));
}
$jalad1 = $_POST['jalad'];
$sanad2 = $_POST['sanad'];
$sql = "SELECT count(Sanad) as countnumber FROM books where Jalad='$jalad1' ";
$stmt = sqlsrv_query( $conn, $sql );
while($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)) {
$rowc= $row['countnumber'];
echo $rowc;
if ($rowc <=5) {
$sql = "INSERT INTO books (Jalad,Sanad)
VALUES ('$jalad1','$sanad2' )";
// echo $sql;
if (sqlsrv_query($conn, $sql)) {
echo "your data saved";
}
else {echo "error";}
}
else {
echo"you have to complete the page of the current book";
}
}
?>
You need to select 'jalad' of the last uploaded book. you can do that however you want, but let's say you store the column value in a variable named $jalad_last
you just need to make your if statement like this
if ($rowc == 0 || $rowc < 5 && $jalad1 == $jalad_last) {
YOUR INSERT CODE HERE
} elseif ($rowc == 5) {
echo 'this book is already completed';
} else {
echo 'you have to complete...';
}
I have a problem that I can't solve.
I am creating an Android App where there is a section showing user data.
The data is saved on a MySql database through Register.php and to get them use the Show.php file.
When I open the user activity in the app, there is a hidden field that contains the user's id, the app sends the id to the Php script and shows all the data of that user.
The problem is that the data is shown with a bit of delay, because it has to read the id from the app and show the filtered data.
What I would like is that in the Php file there was already the user id, so the display of the data on the app would be instantaneous, because so I already have the value of the variable that contains the id to use then in the Query.
To do this I thought of using sessions.
But it does not work.
In the Register.php file I inserted a session variable to store the value of the variable id_restaurants that I need in the show.php script to show that user's data through a Query.
But in the Register.php file it seems that the value of the variable $ _SESSION ['varId'] is not saved.
What am I doing wrong?
Here is the registration file: Register.php
<?php
session_start();
if($_SERVER['REQUEST_METHOD']=='POST'){
include_once("config2.php");
$idUser = $_POST['idUser'];
$name = $_POST['name'];
$surname = $_POST['surname'];
$restaurant = $_POST['restaurant'];
$id_restaurant = $_POST['id_restaurant'];
$_SESSION['varId'] = '$id_restaurant';
if($name == '' || $surname == '' || $restaurant =='' ){
echo json_encode(array( "statusr" => "false","message" => "Insert all data") );
}else {
$query= "SELECT * FROM Restaurants WHERE restaurant='$restaurant'";
$result= mysqli_query($con, $query);
if(mysqli_num_rows($result) > 0){
echo json_encode(array( "statusr" => "false","message" => "Name restaurant already exist") );
}else{
$query = "INSERT INTO Restaurants (idUser,name,surname,restaurant,id_restaurant) VALUES ('$idUser','$name','$surname','$restaurant','$id_restaurant')";
if(mysqli_query($con,$query)){
$query= "SELECT * FROM Restaurants WHERE name='$name' AND surname='$surname' AND restaurant='$restaurant' ";
$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( "statusr" => "truer","message" => "Registered succesfully!" , "datar" => $emparray) );
}else{
echo json_encode(array( "statusr" => "false","message" => "Error") );
}
}
mysqli_close($con);
}
} else{
echo json_encode(array( "statusr" => "false","message" => "Errore3") );
}
?>
Here is the show file: Show.php
<?php
session_start();
include 'config.php';
$conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);
$idRestaurant = $_SESSION['varId'];
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM Food WHERE id_restaurant ='$idRestaurant'" ;
$result = $conn->query($sql);
if ($result->num_rows >0) {
while($row[] = $result->fetch_assoc()) {
$tem = $row;
$json = json_encode($tem);
}
} else {
echo "No Results Found.";
}
echo $json;
$conn->close();
?>
And then you think there's a better way to pass the id between Php scripts?
I listen to you willingly.
Thanks a lot.
I want to insert foreign key value in table.I have two tales employee(employee_id) and attendance. Here employee_id is foreign key in attendance table.
I try a lot but value is not inserted.
Here is my code
if(isset($_POST['submit']))
{
$date = date('Y-m-d',strtotime($_POST['daily_date']));
$in = $_POST['daily_in'];
$l_out = $_POST['lunch_out'];
$l_in = $_POST['lunch_in'];
$out = $_POST['daily_out'];
$emp_remarks = $_POST['remarks'];
$sql = "INSERT INTO attendance (atten_id,daily_date,daily_in,lunch_out,lunch_in,daily_out,remarks,employee_id)
VALUES('NULL','$date','$in','$l_out','$l_in','$out','$emp_remarks','".$_REQUEST['employee_id']."')";
$res = mysql_query($sql);
if ($res > 0) {
echo "inserted";
}
If I run below code then
if(isset($_POST['submit']))
{
$date = $_POST['daily_date'];
$in = $_POST['daily_in'];
$l_out = $_POST['lunch_out'];
$l_in = $_POST['lunch_in'];
$out = $_POST['daily_out'];
$emp_remarks = $_POST['remarks'];
if(isset($_REQUEST['employee_id']))
{
echo "Employee Id" .$_REQUEST['employee_id'];
}
else {
echo "Smoething went wrong";
}
$sql = "INSERT INTO attendance (atten_id,daily_date,daily_in,lunch_out,lunch_in,daily_out,remarks,employee_id)
VALUES
('NULL','$date','$in','$l_out','$l_in','$out','$emp_remarks','".$_REQUEST['employee_id']."')";
its gives
Smoething went wrong not inserted error
Before inserting try this , try this to check whether value was passed or not.
isset($_REQUEST['employee_id'])
{ echo "Employee Id" .$_REQUEST['employee_id'];
} else {
echo "Smoething went wrong";
}
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)
i want to insert my table in sql server from php. but i don't understand how to fix it form my query. is there any suggest that can help my query. is that correct that case statement can be put into php code like i did?
this is my code :
<?
include "new.php";
$ID_Person = $_POST['IDPerson'];
$Number_Phone_Person = $_POST['NumberPhonePerson'];
$Piority_Phone_Person = $_POST['PiorityPhonePerson'];
$response = array();
if (isset($ID_Person) &&
isset($Number_Phone_Person) &&
isset($Piority_Phone_Person)
)
{
$query = "INSERT INTO T_Person_Phone
(
ID_Person,
Number_Phone_Person,
Piority_Phone_Person
)
VALUES
(
'$ID_Person',
'$Number_Phone_Person',
'$Piority_Phone_Person
CASE When PiorityPhonePerson = 1 Then 'Default'
ELSE 'Priority' + CONVERT (Varchar(5),Piority_Phone_Person) END');";
$hasil = sqlsrv_query($conn,$query,$response);
if($hasil)
{
$response["success"] = 1;
$response["message"] = "User successfully created.";
} else
{
$response["success"] = 0;
$response["message"] = "Eksekusi error.";
die( print_r( sqlsrv_errors(), true));
}
} else
{
$response["success"] = 0;
$response["message"] = "Data gagal disimpan.";
}
// echoing JSON response
echo json_encode($response);
?>
i try any any suggest from google but can help me a lot.
$sql = "INSERT INTO T_Person_Phone
(ID_Person, Number_Phone_Person, Piority_Phone_Person)
VALUES ( '$ID_Person','$Number_Phone_Person','$emailid','$team_name' )";
Your MySql Query is not proper, there is a syntactical mistake.
You can run this query directly to phpMyAdmin or Sql prompt, you will get error.
beacoze you have missed single quotes here
'$Piority_Phone_Person
CASE When PiorityPhonePerson = 1 Then 'Default'
ELSE 'Priority' + CONVERT (Varchar(5),Piority_Phone_Person) END'
you can try below one and customise it according to your requirements.
INSERT INTO T_Person_Phone
(
ID_Person,
Number_Phone_Person,
Piority_Phone_Person
)
VALUES
(
'$ID_Person',
'$Number_Phone_Person',
'$Piority_Phone_Person
CASE When PiorityPhonePerson = 1 Then `Default`
ELSE `Priority` + CONVERT (Varchar(5),Piority_Phone_Person) END');";