I need to save the data from android into an online SQL database. I made a PHP file for doing the task. I am trying to save the data using GET in a PHP file but it always returns false. Kindly have a look at my code and please help. The file is called using an android application. Tried testing though REST add-ons for browsers.
EDIT : Problem - When I send the data using HTTP GET all I get in return is the JSON result {"result":false}. This means my SQL query does not run properly. I tried running the same code directly in phpMyAdmin and it works.
EDIT : Code corrected.
<?php
$con = new mysqli("HOST","USERNAME","PASSWORD","DATABASE");
$rrequest_status = $_GET['request_status'];
$rstudent_name = $_GET['student_name'];
$rrequest_to = $_GET['request_to'];
$renrollment_no = $_GET['enrollment_no'];
$rout_date = $_GET['out_date'];
$rout_time = $_GET['out_time'];
$rin_date = $_GET['in_date'];
$rin_time = $_GET['in_time'];
$rrequest_time = $_GET['request_time'];
$rapproved_time = $_GET['approved_time'];
$rvisit_place = $_GET['visit_place'];
$rvisit_type = $_GET['visit_type'];
$rcontact_number = $_GET['contact_number'];
$squery = "INSERT INTO `gatepass_requests` (
`gatepass_number` ,
`request_status` ,
`student_name` ,
`request_to` ,
`enrollment_no` ,
`out_date` ,
`out_time` ,
`in_date` ,
`in_time` ,
`request_time` ,
`approved_time` ,
`approved_by` ,
`visit_place` ,
`visit_type` ,
`contact_number`
)
VALUES (
NULL ,
'".$rrequest_status."',
'".$rstudent_name."',
'".$rrequest_to."',
'".$renrollment_no."',
'".$rout_date."',
'".$rout_time."',
'".$rin_date."',
'".$rin_time."',
'".$rrequest_time."',
NULL,
'".$rapproved_by."',
'".$rvisit_place."',
'".$rvisit_type."',
'".$rcontact_number."',
)";
if(mysqli_query($con,$squery)){
$result['result'] = true;
}else{
$result['result'] = false;
}
echo json_encode($result);
mysqli_close($con);
?>
To set the record straight for future readers.
The fact of the matter here is that you have different/undefined variables for the following used in your VALUES:
$rrequest_status
$rrequest_to
$rrequest_time
But have declared them as, and with an extra "r" and assuming that is your real code and not just a bad paste in your question:
Sidenote: Assuming the GET requests as opposed to POST.
$request_status = $_GET['request_status'];
$request_to = $_GET['request_to'];
$request_time = $_GET['request_time'];
And error reporting would have have signaled undefined variables notices but failed to mention that.
http://php.net/manual/en/function.error-reporting.php
Then you stated this comment in an answer given:
"Thank You so much for your reply, I removed it for the time being, but it is not the problem. PHP does allow to have trailing commas so it doesn't matter. – Pradumn Kumar Mahanta"
Maybe for certain PHP operations, but we're dealing with MySQL here and that alone would have thrown you an exception about the trailing comma for:
'".$rcontact_number."', <<<
In regards to the SQL injection you're open to, use a prepared statement:
References:
https://en.wikipedia.org/wiki/Prepared_statement
http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php (MySQLi_)
http://php.net/pdo.prepared-statements (PDO)
Error checking references:
http://php.net/manual/en/function.error-reporting.php (PHP)
http://php.net/manual/en/mysqli.error.php (MySQLi)
As you used $con = new mysqli("HOST","USERNAME","PASSWORD","DATABASE");. So you are following Object oriented style. So, you need to follow Object oriented style for executing query. Right now you mixed Object oriented style & Procedural style
Change
if(mysqli_query($con,$squery)){
$result['result'] = true;
}else{
$result['result'] = false;
}
To
if($con->query($squery)){
$result['result'] = true;
}else{
$result['result'] = false;
}
For more info, please have a look here Object Oriented Style & Procedural Style
Remove extra , from the insert query.
'".$rcontact_number."', <-- this one
To check what error comes, do following:
if(mysqli_query($con,$squery)) {
$result['result'] = true;
} else {
$result['result'] = mysqli_error($con); // instead of false, use mysqli_error($con)
}
Related
I,ve trying to save some data in my DB, but it just don't save, no error thrown, i used the echo query_orcN; to see if the data that was input by the form is valid, and its all fine, the form can input up to 5 services ($servicoN), so the cod is kinda repetetive, as i am new with php and mySql, expect to see some newbie coding.
I also verified and the logic to choose what if statement will be used is working fine too, so i will post just the case with one service:
...
<?php
include('login/conexao.php');
$nome_cli = $_POST['nome_cli'];
$nome_orc = $_POST['nome_orc'];
$obs_trab = $_POST['obs_orc'];
$servico1 = $_POST['serv1'];
$obs_serv1 = $_POST['obs_serv1'];
$total1 = $_POST['total1'];
$servico2 = $_POST['serv2'];
$obs_serv2 = $_POST['obs_serv2'];
$total2 = $_POST['total2'];
$servico3 = $_POST['serv3'];
$obs_serv3 = $_POST['obs_serv3'];
$total3 = $_POST['total3'];
$servico4 = $_POST['serv4'];
$obs_serv4 = $_POST['obs_serv4'];
$total4 = $_POST['total4'];
$servico5 = $_POST['serv5'];
$obs_serv5 = $_POST['obs_serv5'];
$total5 = $_POST['total5'];
//um serviço
if($servico1 != '' && $servico2 == '' && $servico3 == '' && $servico4 == '' && $servico5 == ''){
$query_orc1 = "START TRANSACTION;
SET #cod_cli = (SELECT cod_cliente
FROM CLIENTE
WHERE nome_cliente = '$nome_cli');
INSERT INTO TRABALHO(nome_trabalho, cod_cliente, obs_trabalho, statuspag_trabalho)
VALUES ('$nome_orc', #cod_cli, '$obs_trab', 0);
SET #orc = LAST_INSERT_ID();
SET #cod_serv1 = (SELECT cod_servicos
FROM SERVICOS
WHERE descri_servicos = '$servico1');
INSERT INTO SERV_TRAB(cod_trabalho, cod_servicos, qtt_serv_trab, obs_serv_trab)
VALUES (#orc, #cod_serv1, $total1, '$obs_serv1');
COMMIT;";
if($resultado_query_orc1 = mysqli_multi_query($conexao, $query_orc1))
{
//echo $query_orc1;
header('Location: sucesso_orc.php');
exit();
}
else
{
echo "<h3>Falha </h3>".$valid;
echo $result_msg_cliente;
}}
...
I'm using myawardspace to host my project, and already set de engine of the tables to InnoDB as for what i,ve understood, it's one that can support the TRANSACTION.
Already thanks anyone in advance for any help and attention, its the first time a post a question here, hope it's well structered.
You have two problems.
PROBLEM 1: failure of the script to produce expected results (i.e., the question you asked).
PROBLEM 2: Lack of diagnostic information.
To solve problem 2, put the following three lines at the start of your script:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
Running the script with this change might produce error messages that will lead to a solution for your script. If not, run simple php with a known error, such as:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
echo '1' //no semi colon is an error
echo '2';
If this produces no error messages, it means there is something in the php or web server (such as Apache) configuration stopping them. Find error logs for php and and the web server (probably apache). Exact details for accessing logs are available myawardspace.
SOLVING PROBLEM 1 - Your Script
Whenever running sql through php, there are two major steps involved in getting it to work.
STEP 1: Verify the sql is valid.
The first shot at forming sql within a php script very often contains errors. That means an important milestone in the development of every php script interacting with a database is verifying the sql outside php. An easy way to do this is to put the following statement immediately after setting the value of query_orc1:
echo query_orc1;
exit;
This will put onto your screen the sql the script is attempting to running. Use copy/paste to run the sql using phpmyadmin or whatever interface you have for your database. If there are problems with the sql, you will see them here. If the sql runs as expected, then you know the part of your script creating the sql is working.
STEP 2: Fix php errors that are failing to submit sql correctly to the database.
Maybe someone can spot errors in this script without benefit of error messages. That is fantastic if someone can provide you that information. I would focus on getting your system to show you error message before trying to troubleshoot the php.
I have no experience with mysqli, therefore I use PDO.
At first: Maybe you should overthink the first part with servico1 to servico5. There is maybe a better solution.
My Changes:
Switch from mysqli to PDO
add prepare statements
replace two statements with subselects
I hope I have commented on every change.
The altered Code:
<?php
include('login/conexao.php');
// Build an PDO Instance (Documentation: https://www.php.net/manual/en/book.pdo.php)
// $db = new PDO("mysql:host=localhost;dbname=test;charset=UTF8", "username", "password", [
// PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
// ]);
$nome_cli = $_POST['nome_cli'];
$nome_orc = $_POST['nome_orc'];
$obs_trab = $_POST['obs_orc'];
$servico1 = $_POST['serv1'];
$obs_serv1 = $_POST['obs_serv1'];
$total1 = $_POST['total1'];
$servico2 = $_POST['serv2'];
$obs_serv2 = $_POST['obs_serv2'];
$total2 = $_POST['total2'];
$servico3 = $_POST['serv3'];
$obs_serv3 = $_POST['obs_serv3'];
$total3 = $_POST['total3'];
$servico4 = $_POST['serv4'];
$obs_serv4 = $_POST['obs_serv4'];
$total4 = $_POST['total4'];
$servico5 = $_POST['serv5'];
$obs_serv5 = $_POST['obs_serv5'];
$total5 = $_POST['total5'];
// switch from
// ($servico1 != '') to !empty($servico1)
// optional, if you like the syntax more, you could use: ($servico1 !== '')
// tripple equals or !== prevents type juggeling
// #see https://www.php.net/manual/en/language.types.type-juggling.php
if (!empty($servico1) && empty($servico2) && empty($servico3) && empty($servico4) && empty($servico5)) {
// Prepared statment to prevent sqlinjection
$stmt = $db->prepare("INSERT INTO TRABALHO (
nome_trabalho,
cod_cliente,
obs_trabalho,
statuspag_trabalho
) VALUES (
:nome_orc,
(SELECT cod_cliente FROM CLIENTE WHERE nome_cliente = :nome_cli ), -- with subselects we can remove unnecessary sql statments
:obs_trab,
0
)
");
try {
// Execute the query and bind the named paraments
// All variables a treated as string
$stmt->execute([
'nome_orc' => $nome_orc,
'nome_cli' => $nome_cli,
'obs_trab' => $obs_trab
]);
} catch (Exception $e) {
// #todo handle exception
echo $e->getMessage();
exit;
}
$stmt = $db->prepare("INSERT INTO SERV_TRAB (
cod_trabalho,
cod_servicos,
qtt_serv_trab,
obs_serv_trab
) VALUES (
:orc,
(SELECT cod_servicos FROM SERVICOS WHERE descri_servicos = :servico1),
$total1,
:obs_serv1
)
");
try {
// get last inserted id with pdo: $db->lastInsertId()
$stmt->execute([
'orc' => $db->lastInsertId(),
'servico1' => $servico1,
'obs_serv1' => $obs_serv1
]);
} catch (Exception $e) {
// #todo handle exception
echo $e->getMessage();
exit;
}
// we don't need an if at this point because if an error occures it will throw an exception
// and the try / catch will catch and handle it
header('Location: sucesso_orc.php');
exit;
}
I've been trying to update my data according to the user session (UserLogin) but it kept saying: Data type mismatch in criteria expression. The print_r is just for testing purposes.
Thanks in advance,
Z
function Employee1_BeforeShow(& $sender)
{
$Employee1_BeforeShow = true;
$Component = & $sender;
$Container = & CCGetParentContainer($sender);
global $Employee1; //Compatibility
$Page = CCGetParentPage($sender);
$db = $Page->Connections["PettyCashMDB"];
$sql1 = "UPDATE Employee SET Employee.LastActive = Date() WHERE Employee.[EmpID] = ". $_SESSION['UserLogin'];
$db->query($sql1);
print_r($_SESSION['UserLogin']);
$db->close();
Employee1_BeforeShow #67-67106FAD
return $Employee1_BeforeShow;
}
EDIT: I've tried #NanaPartykar 's method and by accident I've noticed that it does get the value from $_SESSION['UserLogin'], just that somehow the datatype is different.
EDIT: It displays the error Data type mismatch but both of them are string and returns string.
Instead of Employee.[EmpID], use Employee.EmpID
You need some quotes:
$sql1 = "UPDATE Employee SET Employee.LastActive = Date() WHERE Employee.[EmpID] = \'". $_SESSION['UserLogin'] . "\'";
Z - There are a bunch of built-in Codecharge functions to assist with getting values from querystring, sessions and controls.
eg: CCGetSession("UserLogin", "default");
http://docs.codecharge.com/studio50/html/index.html?http://docs.codecharge.com/studio50/html/Components/Functions/PHP/Overview.html
and executing SQL with some validating (from 'Execute Custom SQL' help topic):
$db = new clsDBConnection1();
$SQL = "INSERT INTO report (report_task_id,report_creator) ".
"VALUES (". $db->ToSQL(CCGetFromGet("task_id",0),ccsInteger) .",". $db->ToSQL(CCGetUserID(),ccsInteger) .")";
$db->query($SQL);
$db->close();
The $db->ToSQL (and CCToSQL) functions convert and add quotes for relevant data types (ccsText, ccsDate).
There are many examples in the Manual under 'Examples' and 'Programming Reference' for PHP (and ASP, .NET, etc)
http://support.codecharge.com/tutorials.asp
I strongly suggest looking at some of the examples, as Codecharge will handle a lot of the 'plumbing' and adding a lot of custom code will causing problems with the generation of code. In your example, you should add a 'Custom Code' action to the Record's 'Before Show' Event and add your code there. If you add code just anywhere, the entire section of code (eg: Before Show) will change colour and no longer be updated if you change something.
For example, if you manually edited the 'Update' function to change a default value, then no changes through the IDE/Properties will change the 'Update' function (such as adding a new field to the Record).
Finally got it to work, this is the code $sql1 = "UPDATE Employee SET LastActive = Date() WHERE EmpID = '$_SESSION[UserLogin]' "; Thanks to everyone that helped out.
I have a record that needs to be updated. If the update is successful, then it should insert record into three different tables. I did it with the code below,but one of the table(tab_loan_targetsave)is not inserting.I need a third eye to looked into this, as I have had a lot of pain in fathoming where the problem lies.
Pls i need assistance.Also, I welcome better approach if possible.
<?php
if(isset($_POST["savebtn"])){
$custNo = $_POST["custid"];
$transDate = $_POST["transDate"];
$grpid = $_POST["custgrp"];
$contAmount =$_POST["amtCont"];
$amount = $_POST["amount"];
$disAmount =$_POST["disbAmt"];
$savAmount =$_POST["savAmt"];
$intAmount =$_POST["intAmt"];
$postedBy = $_SESSION["staffid"];
//$preApproved =$_POST["preAmount"];
$loanRef = $_POST["refid"];
$st = "Approved";
$appDate = date("Y-m-d H:i:s");
$appBy = $_SESSION['staffid'];
$counter = 1;
$locate = $_SESSION['location'];
$insure = $_POST["insuAmt"];
$dis = $_POST["DisAmt"];
$update = mysqli_query($connection,"UPDATE tab_loan_request SET approval_status='$st',approvalDate='$appDate',approvedBy='$appBy',loanRef='$loanRef' WHERE custid='$custNo' AND RepayStatus='1'");
if($update && mysqli_affected_rows($connection)>0){
$insertTar = mysqli_query($connection,"INSERT INTO tab_loan_targetsave(custid,grpid,transactionDate,loanRef,savingAmt,status,postedBy,location,appStatus)
VALUES('$custNo','$grpid','$transDate','$loanRef,'$savAmount','Cr','$postedBy','$locate','1')");
$insertInt = mysqli_query($connection,"INSERT INTO tab_loan_interest(custid,requestAmt,transactionDate,interestFees,postedBy,loanRef,InsuranceFees,DisasterFees)VALUES(
'$custNo','$amount','$transDate','$intAmount','$postedBy','$loanRef','$insure','$dis')");
//if($insertInt){
//}if($insertTar){
$insertSav = mysqli_query($connection,"INSERT INTO tab_loan_saving(custid,grpid,transactionDate,loanRef,loanAmount,savingAmt,status,postedBy,location,appStatus)
VALUES('$custNo','$grpid','$transDate','$loanRef','$amount','0','Cr','$postedBy','$locate','1')");
}//first if
if($insertSav){
echo "<span style='font-weight:bold;color:red;'>"." Application Approval is successful!"."</span>";
}else{
//Unable to save
echo "<span style='font-weight:bold;color:black;>"."Error! Application Approval not Successful!"."</span>";
}
}else{
$custid = "";$saving=0.00;$st="";
$transDate = "";
$grpid = "";
$amount = "";
$postedBy = "";$loanRef="";
}
?>
"#Fred: See the error generated when i used mysqli_error($connection). Could you please interprete this: ErrorMessage: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1000.00','Cr','SPL002','Ojo','1')' at line 2 – Dave"
Seeing the error generated by the suggestion I've given you to check for errors.
You're missing a quote here '$loanRef
in your query:
VALUES('$custNo','$grpid','$transDate','$loanRef , '$savAmount'...
^ right there
I suggest to escape all of your incoming data.
I.e.:
$var = mysqli_real_escape_string($connection, $_POST['var']);
and apply that same logic to all your POST arrays.
Plus, as I stated; make sure you started the session, since there is no mention of that in your question and session_start(); wasn't included in your posted code.
The session needs to be started inside all pages using sessions.
Using a prepared statement will is better.
http://php.net/manual/en/mysqli.prepare.php
http://php.net/manual/en/pdo.prepared-statements.php
which is what you really should be using.
Additional references:
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/function.error-reporting
Also make sure there aren't any constraints in your table(s).
Dude make sure you properly escape your variables http://php.net/manual/en/mysqli.prepare.php
i would check the Table Name! make sure it is case sesntive, also just wondering if you could do something to your database design? It seems a lot of duplicate data is going into your tables. Think about a better way to organise and store that data
I got where the error is emanting from . Just because I forgot to add a single quote to one of the values. ie missing the quote- near $loanRef. No closing string. Anyway, I was able to detect that through the error message stated parameter as adviced by Fred nad Mark. Correct
$insertTar = mysqli_query($connection,"INSERT INTO tab_loan_targetsave(custid,grpid,transactionDate,loanRef,savingAmt,status,postedBy,location,appStatus)
VALUES('$custNo','$grpid','$transDate','$loanRef','$savAmount','Cr','$postedBy','$locate','1')");
Thank you all.
I am attempting to create a function that will insert items (and will do the same to edit) items in a database through a form. I have the form and the PHP - and when I run the function, I get the correct database name to pull and the variable names to pull along with the values I input, but I then see a database error? Any help would be great (I'm still newer to PHP really and pulling out some hair)
Config File:
$hostname = 'localhost';
$username = 'DEFINED';
$password = 'DEFINED';
$database = 'DEFINED';
$table = 'recipes';
require('../config.php');
$link = mysql_connect($hostname,$username,$password);
mysql_select_db($database,$link);
/* Get values and submit */
$rid = mysql_real_escape_string($_POST['rid']);
$name = mysql_real_escape_string($_POST['name']);
$category = mysql_real_escape_string($_POST['category']);
$tags = mysql_real_escape_string($_POST['tags']);
$search_tags = mysql_real_escape_string($_POST['search_tags']);
$description = mysql_real_escape_string($_POST['description']);
$description2 = mysql_real_escape_string($_POST['description2']);
$recipeAbout = mysql_real_escape_string($_POST['recipeAbout']);
$ingredients_1 = mysql_real_escape_string($_POST['ingredients_1']);
$directions_1 = mysql_real_escape_string($_POST['directions_1']);
$query = "INSERT INTO $table (name, category, tags, search_tags, description,description2, recipeAbout, ingredients_1,directions_1) VALUES ('$name','$category','$description','$description2' $tags','$search_tags','$description','$recipeAbout','$ingredients_1','$directions_1')";
echo $query;
Besides the missing comma in '$description2' $tags' => '$description2', $tags' which you said had been added afterwards, and signaled by Ryan: there's also a missing quote, so change it to '$description2', '$tags' and having 2x '$description' variables, remove one.
VALUES
('$name','$category','$tags','$description','$description2', '$search_tags','$recipeAbout','$ingredients_1','$directions_1')";
However, the most important part to querying, is that you must use mysql_query() which you are not using => mysql_query() which is why data isn't being inserted, once you've fixed the syntax errors.
mysql_query() is the essential part.
Add the following to your code:
if(mysql_query($sql,$link)){
echo "Success";
}
else{
echo "Error" . mysql_error();
}
Plus, use prepared statements, or PDO with prepared statements.
You're using a deprecated library and open to SQL injection..
Plus make sure you have assigned $table to the table you wish to enter data into. It's not shown in your question.
You also did not show what your HTML form contains. Make sure that you are using a POST method and that all elements are named with no typos.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
Sidenote: Error reporting should only be done in staging, and never production.
EDIT: and using mysqli_
As a quick test, try the following and replacing the values in the line below with your own.
<?php
$link = mysqli_connect("host","username","password","database")
or die("Error " . mysqli_error($link));
$table = "recipes";
$name = mysqli_real_escape_string($link,$_POST['name']);
mysqli_query($link,"INSERT INTO `$table` (`name`) VALUES ('".$name."')")
or die(mysqli_error($link));
?>
If that still does not work, then you need to check your database, table, column name(s), including types and column lengths.
Lot's of stuff wrong here...
You're missing a quote on the second of these two items, as well as either a string concat or a comma: '$description2' $tags'
You've also got your order messed up for tags, search tags, and description 1/2.
$description is in there twice (you have 9 columns defined and 10 values in your statement)
You don't seem to have declared a value for $table
As Fred -ii- has pointed out in his answer, you're missing mysql_query() to actually run it. I assumed you have it further down in your code, but it's missing from the post, which is causing some confusion...
Also, consider updating to use mysqli instead of mysql functions.
what are you echoing $query for?
You do not have any reason to do that except if you just want to use it as a string variable.
it should be mysql_query($query);
What is the exact "database error" error you are getting?
I suggest reading this article about PDO
If you can't insert the data correctly, this might be your problem too.
I'm trying to create an update function in PHP but the records don't seem to be changing as per the update. I've created a JSON object to hold the values being passed over to this file and according to the Firebug Lite console I've running these values are outputted just fine so it's prob something wrong with the sql side. Can anyone spot a problem? I'd appreciate the help!
<?php
$var1 = $_REQUEST['action']; // We dont need action for this tutorial, but in a complex code you need a way to determine ajax action nature
$jsonObject = json_decode($_REQUEST['outputJSON']); // Decode JSON object into readable PHP object
$name = $jsonObject->{'name'}; // Get name from object
$desc = $jsonObject->{'desc'}; // Get desc from object
$did = $jsonObject->{'did'};// Get id object
mysql_connect("localhost","root",""); // Conect to mysql, first parameter is location, second is mysql username and a third one is a mysql password
#mysql_select_db("findadeal") or die( "Unable to select database"); // Connect to database called test
$query = "UPDATE deal SET dname = {'$name'}, desc={'$desc'} WHERE dealid = {'$did'}";
$add = mysql_query($query);
$num = mysql_num_rows($add);
if($num != 0) {
echo "true";
} else {
echo "false";
}
?>
I believe you are misusing the curly braces. The single quote should go on the outside of them.:
"UPDATE deal SET dname = {'$name'}, desc={'$desc'} WHERE dealid = {'$did'}"
Becomes
"UPDATE deal SET dname = '{$name}', desc='{$desc}' WHERE dealid = '{$did}'"
On a side note, using any mysql_* functions isn't really good security-wise. I would recommend looking into php's mysqli or pdo extensions.
You need to escape reserved words in MySQL like desc with backticks
UPDATE deal
SET dname = {'$name'}, `desc`= {'$desc'} ....
^----^--------------------------here
you need to use mysql_affected_rows() after update not mysql_num_rows