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.
Related
i'm creating a website that have multiple type of user and each user have a specific homepage, how can i define which page for the user using php?
for example, there are students, superviser, admin
for each of them, there is specific homepage.
in my table, i create a row called role contain number that specify the type of the user
i have wrote my code, but it does not move to the next page.
this is my code:
<?php
session_start();
include 'connect-db.php';
if(isset($_POST['name'],$_POST['pass']))
{
$name = $_POST['name'];
$pwd = $_POST['pass'];
$query = "SELECT * FROM user WHERE name='$name' AND pass='$pwd'";
$result = mysqli_query($con, $query);
$user=array();
while($row = mysqli_fetch_assoc($result))
{
$user[$row['id']] = array(
'ID' => $row['ID'],
'name'=>$row['name'],
'role'=>$row['role'],
'email'=>$row['e-mail'],
'pass' => $row['pass']
);
}
if($result)
{
if((mysqli_num_rows($result) == 1))
{
header('Location: index.php?status=valid');
if($user['role']===1){
header('Location: Student_Home.php?status=valid');
}
if ($user['role']===3){
header('Location: GPC.php?status=valid');
}
}
else
{
header('Location: index.php?status=invalid');
}
}
}
?>
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
<?php
session_start();
include("db.php");//database connectivity
$uid=$_POST['uid'];//user's id
$meeting_id=$_POST['meeting_id'];//meeting id
// Create directory if it does not exist
if(!is_dir("audioupload/".$uid."/".$_SESSION["uid"]."/"))
{
mkdir("audioupload/".$uid."/".$_SESSION["uid"]."/");
}
$info = pathinfo($_FILES['audio']['name']);
$ext = $info['extension'];
$audio_name = "meeting_id".$meeting_id.".".$ext;
// Move the uploaded file
$upload=move_uploaded_file($_FILES["audio"]["tmp_name"], "audioupload/".$uid."/".$_SESSION["uid"] ."/". $audio_name);
$sql="INSERT INTO `audio`(`uid`,`meeting_id`,`audio`) VALUES ('".$uid."','".$meeting_id."','".$audio_name."')";
$result1 = mysqli_query($conn,$sql);
if($result1)
{
$sql1="select * from `audio` where `uid`='$_POST[uid]'";
$result = mysqli_query($conn,$sql1);
$count = mysqli_num_rows($result);
}
if($count>0)
{
$emparray = array();
while($row = mysqli_fetch_array($result))
{
$emparray=array(
'success' => true,
'message' => "Audio saved Successfully!",);
}
}
else
{
$row = mysqli_fetch_array($result);
$emparray=array(
'success' => false,
'message' => "Incorrect Data!",
);
}
echo json_encode($emparray,JSON_PRETTY_PRINT,JSON_FORCE_OBJECT);
mysqli_close($conn);
?>
this is my code for audio api.
i got to different results from same code. postman tool give me proper result whereas app doest give. wts the problem ?
I'm building a php site where i want the user to create his company.
The script is checking if the user has any companies registered already and then it should display if he does or doesn't.
If he doesnt have a registered company, he should see a form where he can register.
If he choose to register a company the script will check for any company with the same name or insert the row.
My only problem is that when there's already a company with that name the echo doesnt display.
I have written inside the code where the problem is.
<?php
$con=mysqli_connect("mysql","USER","PASS","DB");
if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); }
$result_get_companies = mysqli_query($con,"SELECT * FROM companies WHERE userid='". $login_session ."' ORDER BY companyid ASC") or die(mysqli_error());
if (mysqli_num_rows($result_get_companies) >= 1) {
while($row_companies = mysqli_fetch_array( $result_get_companies )) {
$result_get_company_owner = mysqli_query($con,"SELECT username FROM users WHERE userid='". $login_session ."'") or die(mysqli_error());
$company_owner = mysqli_fetch_assoc($result_get_company_owner);
echo 'THIS WORKS';
}
} else {
if (isset($_POST['create_first_company']) && !empty($_POST['company_name'])) {
$company_name_unsafe = mysqli_real_escape_string($con, $_POST['company_name']);
$company_name = preg_replace("/[^a-zA-Z0-9\s]/","",$company_name_unsafe );
$check_companies = "SELECT companyid FROM companies WHERE company_name='". $company_name ."'";
$what_to_do_companies = mysqli_query($con,$check_companies);
if (mysqli_num_rows($what_to_do_companies) != 0) {
echo 'THIS DOESNT WORK
It does register that is should go here
because it does not insert new row.
and when the value is = 0 it does go
to else ELSE below and insert row.';
} else {
$result_create_company = mysqli_query($con,"INSERT INTO companies (companyname)
VALUES ('". $login_session ."')")
or die(mysqli_error());
echo 'THIS WORKS';
}
} else {
echo 'THIS WORKS!';
}
}
?>
Login.php
session_start();
<?php
$username = "root";
$password = "tiger";
$hostname = "localhost";
//connection to the database
$dbhandle = mysqli_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
//select a database to work with
/* #var $selected type */
$selected = mysqli_select_db($dbhandle,"sample")
or die("Could not select sample");
$name=(\filter_input(\INPUT_POST,'name'));
$phone=(\filter_input(\INPUT_POST,'phone'));
$email=(\filter_input(\INPUT_POST,'email'));
//$custno=(\filter_input(\INPUT_POST,'custno'));
if(!empty(\filter_input(\INPUT_POST,'continue')))
{
echo "<script type='text/javascript'>\n";
'check()';
echo "</script>";
$sql="insert into customersignin(name,phone,email)values('$name','$phone','$email')";
$result=mysqli_query($dbhandle,$sql) or die(\mysqli_error($dbhandle));
}
else
{
$sql1="insert into customersignin(custno)values(NULL)";
$result1=mysqli_query($dbhandle,$sql1) or die(\mysqli_error($dbhandle));
}
$sql2="select custno from customersignin";
$result2=mysqli_query($dbhandle,$sql2) or die (mysqli_error($dbhandle));
$row= mysqli_fetch_array($result2);
if(mysqli_num_rows($result2)>0)
{
echo "$_SESSION['custno']";
unset($_SESSION['custno'];
header('Location:customersvsoup.php');
}
mysqli_close($dbhandle);
$_SESSION[name]=(\filter_input(INPUT_POST,'name'));
customer.php
<body>
<?php session_start(); ?>
<input type="text" style="position: absolute;top:200px;" value="<?php echo $_SESSION["custno"]?>">
</body>
In the php file the customer log in is done,the custno is the auto generate field,i have 2 buttons called continue and skip,for both the auto generate works fine,after any of the button action is done,i need to display the custno in the text box of the next page using session.But the problem is the text box is empty when i run this code.But the session['name'] is working..Please help.
Your session_start(); should come at the beginning of the file in login.php. I see you using $_SESSION[custno] before it's called. That's why your textbox is empty.
Also it should be:
$_SESSION['custno']
$_SESSION['name']note the single quotes
Regarding your logical problem (in the comments) try:
$_SESSION['name'] = (filter_input(INPUT_POST, 'name'));
if (!empty(filter_input(INPUT_POST, 'continue')))
{
echo "<script type='text/javascript'>\n";
'check()';
echo "</script>";
$sql = "insert into customersignin(name,phone,email)values('$name','$phone','$email')";
$result = mysqli_query($dbhandle, $sql) or die(mysqli_error($dbhandle));
$sql2 = "select max(custno) as last_custno from customersignin";
$result2 = mysqli_query($dbhandle, $sql2) or die(mysqli_error($dbhandle));
if (mysqli_num_rows($result2) > 0)
{
$row = mysqli_fetch_assoc($result2);
$_SESSION['custno'] = $row['last_custno'];
header('Location:customersvsoup.php');
}
}
else
{
$sql1 = "insert into customersignin(custno)values(NULL)";
$result1 = mysqli_query($dbhandle, $sql1) or die(mysqli_error($dbhandle));
//since this bit of code is repeating,
//you could even use a function to shorten it
$sql2 = "select max(custno) as last_custno from customersignin";
$result2 = mysqli_query($dbhandle, $sql2) or die(mysqli_error($dbhandle));
if (mysqli_num_rows($result2) > 0)
{
$row = mysqli_fetch_assoc($result2);
$_SESSION['custno'] = $row['last_custno'];
header('Location:customersvsoup.php');
}
}
And please put the session_start(); inside after <?php. All php code should be within the PHP tags.
you have error in insert query:
$sql="insertintocustomersignin(name,phone,email)values('$name','$phone','$email')";
should be :
$sql="insert into customersignin(name,phone,email) values ('$name','$phone','$email')";
you should use quotes in array index :
$_SESSION[custno], $_SESSION[name] should be $_SESSION['custno'], $_SESSION['name']