I'm looking for since few days to create a API Restful in PHP to add record on my sqlite database. But when I use POSTMAN to try it, my php code doesn't work, but it's work (with little modifies) with mysql databases.
Could you help me please ? (This code is just a test)
<?php
header('Content-Type: application/json');
try{
$pdo = new PDO('sqlite:database.db');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$retour["success"] = true;
$retour["message"] = "Connexion OK";
} catch(Exception $e){
$retour["success"] = false;
$retour["message"] = "Connexion impossible";
}
if ( !empty($_POST["ville_depart"]) && !empty($_POST["ville_destination"]) && !empty($_POST["date"]) && !empty($_POST["nb_heure"]) && !empty($_POST["prix"]) ) {
$requete = $pdo->prepare('INSERT INTO api (id, ville_depart, ville_destination, date_depart, nb_heure_vol, prix) VALUES (?, :ville1, :ville2, :date_vol, :nb, :prix)');
$requete->bindParam(':ville1', $_POST["ville_depart"]);
$requete->bindParam(':ville2', $_POST["ville_destination"]);
$requete->bindParam(':date_vol', $_POST["date_depart"]);
$requete->bindParam(':nb', $_POST["nb_heure_vol"]);
$requete->bindParam(':prix', $_POST["prix"]);
$requete->execute();
$retour["success"] = true;
$retour["message"] = "add flight";
$retour["results"] = array();
} else {
$retour["success"] = false;
$retour["message"] = "manque infos";
}
echo json_encode($retour);
// close the database connection
$pdo = NULL;
?>
The result from POSTMAN is not really "speaking", but I can't to find other informations (in the log files) to help me...
[edit to be conform at the previous code]
I think my problem come from my "$_POST" because, when I tried to put some values into the "INSERT" line, that works well.
ex:
$requete = $pdo->prepare("INSERT INTO api (id,ville_depart, ville_destination, date_depart, nb_heure_vol, prix) VALUES ('123', 'LYON', 'TLS', '2019-09-09', '13', '132')");
$requete->execute();
Related
My code:
<?php
try {
$t = '040485c4-2eba-11e9-8e3c-0231844357e8';
if (array_key_exists('t', $_REQUEST)) {
$t = $_REQUEST["t"];
}
if (!isset($_COOKIE['writer'])) {
header("Location: xxx");
return 0;
}
$writer = $_COOKIE['writer'];
$dbhost = $_SERVER['RDS_HOSTNAME'];
$dbport = $_SERVER['RDS_PORT'];
$dbname = $_SERVER['RDS_DB_NAME'];
$charset = 'utf8' ;
$dsn = "mysql:host={$dbhost};port={$dbport};dbname={$dbname};charset={$charset}";
$username = $_SERVER['RDS_USERNAME'];
$password = $_SERVER['RDS_PASSWORD'];
$pdo = new PDO($dsn, $username, $password);
$stmt = $pdo->prepare("select writer from mydbtbl where writer=? and t=?");
$stmt->execute(array($writer, $t));
$num = $stmt->fetch(PDO::FETCH_NUM);
if ($num < 1) {
header("Location: login.php");
return 0;
}
$dbMsg = "Authorized";
$dbname = 'imgs';
$dsn = "mysql:host={$dbhost};port={$dbport};dbname={$dbname};charset={$charset}";
$pdo = new PDO($dsn, $username, $password);
if (isset($_FILES['filename'])) {
$name = $_FILES['filename']['name'];
// set path of uploaded file
$path = "./".basename($_FILES['filename']['name']);
// move file to current directory
move_uploaded_file($_FILES['filename']['tmp_name'], $path);
// get file contents
$data = file_get_contents($path, NULL, NULL, 0, 60000);
$stmt = $pdo->prepare("INSERT INTO file (contents, filename, t) values (?,?,?)");
$stmt->execute(array
($data,
$name,
$t)
);
$dbMsg = "Added the file to the repository";
// delete the file
unlink($path);
}
} catch (Exception $e) {
$dbMsg = "exception: " . $e->getMessage();
}
In the code you will see that the first part is for doing authentication. Then I create a new PDO object on the img schema, and do my file insert query after that.
Later, where I am printing out $dbMsg, it is saying "added file to the repository". But when I query the database (MySQL on Amazon AWS using MySQL Workbench) nothing has been inserted.
I don't understand why if nothing is getting inserted I am not getting an error message. If it says "added file to the respository", doesn't that mean the insert was successful? The only thing I can think is that using a different schema for this is mucking things up. All of my inserts to ebdb are going through fine
--- EDIT ---
This question was marked as a possible duplicate on my query about not getting an error message on my insert / execute code. This was a useful link and definitely something I will be aware of and check in the future, but ultimately the answer is the one I have provided regarding the terms of service for my aws account
The answer is that the (free) amazon account policy I am working under only allows me to have 1 database / schema. When I switched the table over to ebdb it worked right away. I am answering my own question (rather than deleting) so hopefully others using AWS / MySQL can learn from my experience.
Can someone point the fault in this code? I'm unable to update data to the database. We are sending a text message to the server, and this file here decodes and sets it in the database. But this case over here is not working for some reason. I checked and tried to troubleshoot, but couldn't find a problem.
case 23:
// Gather Variables
$Message = preg_replace("/\s+/","%20", $Message);
$UnixTime = time();
$cycle = explode(":", $Message);
$machine_press = $cycle[0];
$machine_pct_full = $machine_press/20;
$machine_cycles_return = $cycle[1];
$machine_cycles_total = $cycle[2];
// Build SQL Statement to update static values in the machine table
$sql = "UPDATE `machines` SET `machine_last_run`=".$UnixTime.",`machine_press`=".$machine_press.",`machine_pct_full`=".$machine_pct_full.",`machine_cycles_return`=".$machine_cycles_return.",`machine_cycles_total`=".$machine_cycles_total." WHERE `machine_serial`='$MachSerial'";
// Performs the $sql query on the server to update the values
if ($conn->query($sql) === TRUE) {
// echo 'Entry saved successfully<br>';
} else {
echo 'Error: '. $conn->error;
}
$sql = "INSERT INTO `cycles` (`cycle_sequence`,`cycle_timestamp`,`cycle_did`,`cycle_serial`,`cycle_03_INT`,`cycle_14_INT`,`cycle_15_INT`,`cycle_18_INT`)";
$sql = $sql . "VALUES ($SeqNum,$UnixTime,'$siteDID','$MachSerial',$machine_press,$machine_cycles_total,$machine_cycles_return,$machine_pct_full)";
// Performs the $sql query on the server to insert the values
if ($conn->query($sql) === TRUE) {
// echo 'Entry saved successfully<br>';
} else {
echo 'Error: '. $conn->error;
}
break;
More information is required to help you out with your issue.
First, to display errors, edit the index.php file in your Codeigniter
project, update where it says
define('ENVIRONMENT', 'production');
to
define('ENVIRONMENT', 'development');
Then you'll see exactly what the problem is. That way you can provide the information needed to help you.
I just saw that you are inserting strings when not wrapping them in apostrophe '. So you queries should be:
$sql = "UPDATE `machines` SET `machine_last_run`='".$UnixTime."',`machine_press`='".$machine_press."',`machine_pct_full`='".$machine_pct_full."',`machine_cycles_return`='".$machine_cycles_return."',`machine_cycles_total`='".$machine_cycles_total."' WHERE `machine_serial`='$MachSerial'";
and
$sql = "INSERT INTO `cycles` (`cycle_sequence`,`cycle_timestamp`,`cycle_did`,`cycle_serial`,`cycle_03_INT`,`cycle_14_INT`,`cycle_15_INT`,`cycle_18_INT`)";
$sql = $sql . " VALUES ('$SeqNum','$UnixTime','$siteDID','$MachSerial','$machine_press','$machine_cycles_total','$machine_cycles_return','$machine_pct_full')";
For any type of unknown problems I can recommend turning on PHP and SQL errors and use a tool called postman that i use to test my apis. You can mimic requests with any method, headers and parameters and send an "sms" just like your provider or whatever does to your API. You can then see the errors your application throws.
EDIT
I tested your script using a fixed version with ' and db.
$Message = "value1:value2:value3";
$MachSerial = "someSerial";
$SeqNum = "someSeqNo";
$siteDID = "someDID";
$pdo = new PDO('mysql:host=someHost;dbname=someDb', 'someUser', 'somePass');
// Gather Variables
$Message = preg_replace("/\s+/","%20", $Message);
$UnixTime = time();
$cycle = explode(":", $Message);
$machine_press = $cycle[0];
$machine_pct_full = (int)$machine_press/20; // <----- Note the casting to int. Else a warning is thrown.
$machine_cycles_return = $cycle[1];
$machine_cycles_total = $cycle[2];
// Build SQL Statement to update static values in the machine table
$sql = "UPDATE `machines` SET `machine_last_run`='$UnixTime',`machine_press`='$machine_press',`machine_pct_full`='$machine_pct_full',`machine_cycles_return`='$machine_cycles_return',`machine_cycles_total`='$machine_cycles_total' WHERE `machine_serial`='$MachSerial'";
try {
$pdo->query($sql);
} catch (PDOException $e) {
echo 'Query failed: ' . $e->getMessage();
}
$sql = "INSERT INTO `cycles` (`cycle_sequence`,`cycle_timestamp`,`cycle_did`,`cycle_serial`,`cycle_03_INT`,`cycle_14_INT`,`cycle_15_INT`,`cycle_18_INT`)";
$sql = $sql . "VALUES ('$SeqNum','$UnixTime','$siteDID','$MachSerial','$machine_press','$machine_cycles_total','$machine_cycles_return','$machine_pct_full')";
try {
$pdo->query($sql);
} catch (PDOException $e) {
echo 'Query failed: ' . $e->getMessage();
}
It totally works. Got every cycle inserted and machines updated. Before i fixed it by adding wrapping ' i got plenty of errors.
Alright so this is the solution:
i replaced the line:
$Message = preg_replace("/\s+/","%20", $Message);
with:
$Message = preg_replace("/\s+/","", $Message);
This removes all blank spaces in my text message and makes it a single string before breaking and assigning it to different tables in the database.
I understand this wasnt really a problem with the script and no one around would have known the actual problem before answering. and thats why i am posting the solution just to update the team involved here.
Have a look through the code below. This is supposed to check whether or not a database contains a given user. If the it does, it just returns true. If it doesn't, then it returns false.
Anyway, regardless of the user and password existing in the database, for some reason it will not evaluate to true! ! !
function databaseContainsUser($email, $password)
{
include $_SERVER['DOCUMENT_ROOT'].'/includes/db.inc.php';
try
{
$sql = 'SELECT COUNT(*) FROM wl_user
WHERE email = :email AND password = :password';
$s = $pdo->prepare($sql);
$s->bindValue(':email', $email);
$s->bindValue(':password', $password);
$s->execute("USE $dbname");
}
catch (PDOException $e)
{
$error = 'Error searching for user. ' . $e->getMessage();
include $_SERVER['DOCUMENT_ROOT'].'/includes/error.html.php';
exit();
}
$row = $s->fetch(PDO::FETCH_NUM);
if ($row[0] > 0)
{
return TRUE;
}
else
{
return FALSE;
}
}
Any help would be appreciated
For some unknown reason you are passing "USE $dbname" string to execute.
remove that string.
Also, you are trying to catch an exception but apparently don't tell PDO to throw them.
And you are catching it only to echo a message, which is a big no-no.
I've explained the right way recently in this answer
If your problem is different, you have to ask (or better - google for this very problem).
Refer to PDO tag wiki for the proper connect options including database selection and error reporting.
Try this
try
{
$pdo = new PDO('mysql:host=localhost;dbname=yourDbName;', 'root', '',
array(PDO::ATTR_PERSISTENT => true));
$sql = 'SELECT count(*) FROM user WHERE email = :email AND password = :password';
$s = $pdo->prepare($sql);
$s->bindValue(':email', $email);
$s->bindValue(':password', $password);
$s->execute();
}
This is local server example, just change yourDbName to your db name. I just run this code on my local server and it is working.
I do not have any other option, but to ask here again... and problem is killing me for the past 5 hours. I got button that call javascript function, and then javascript opens another php page and does insert in MySQL database.
HTML code:
<ul>
<li id="ConfirmButton" name="Insert" onclick="GetAllIDs()"><a>Potvrdi</a></li>
</ul>
Javascript code:
var request_type;
var browser = navigator.appName;
if (browser == "Microsoft Internet Explorer") {
request_type = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
request_type = new XMLHttpRequest();
}
var http = request_type;
http.open('get', 'insert.php?MatchID='+MatchID+'&TipID='+TipID+'&UserID=' + 1,true);
http.send(null);
PHP code:
include('config.php');
$matchID = $_GET['MatchID'];
$tipID = $_GET['TipID'];
$userID = $_GET['UserID'];
// Escape User Input to help prevent SQL Injection
$MatchID = mysql_real_escape_string($matchID);
$TipID = mysql_real_escape_string($tipID);
$UserID = mysql_real_escape_string($userID);
$insertTicket_sql = "INSERT INTO
betslips(DateTime,MatchID,TipID,UserID)
VALUES(".$MatchID.",".$TipID.",'".date("Y-m-d H:i:s")."',".$UserID.")";
$insertTick= mysql_query($insertTicket_sql) or die(mysql_error());
So after I run this code and I use break point I see in my php code all parameters I sent over forms normally and it's all there, but when I reach code $insertTick I get error
web server exited unexpectedly, restarting new instance.
Has anyone seen this problem before, and how can I deal with it?
Thanks
did anyone seen this problem before?
Not me, I dont use the mysql_* functions.
Your INSERT query parameter and values dont match.
So ive ported your example code to PDO perhaps its some interest:
<?php
//PDO Connect
try{
$con = new PDO('mysql:host=127.0.0.1;dbname=yourDB','root','password');
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$con->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
}catch (Exception $e){
die('Cannot connect to database. Details:'.$e->getMessage());
}
//Check that the variables are set
if(isset($_GET['MatchID']) && isset($_GET['TipID']) && isset($_GET['UserID'])){
//Prepare your query
$query = $con->prepare("INSERT INTO betslips (DateTime,MatchID,TipID,UserID)
VALUES ('".date("Y-m-d H:i:s")."', :matchID, :tipID, :userID)");
//Bind your values with the placeholders
$query->bindParam(":matchID", $_GET['MatchID']);
$query->bindParam(":tipID", $_GET['TipID']);
$query->bindParam(":userID", $_GET['UserID']);
//Execute
$query->execute();
die('Success!');
}else{
die('Error: Parameter not set.');
}
?>
I have an app that reads in Json data from phpmyadmin thru a php script and displayed in a list activity. Once a store name is clicked, +1 is added to the vote count for that store and is supposed to be sent back to the php server to store the new vote count in phpmyadmin. After the selection, I check the db vote count value and it is not updated. Although I get HTTP/1.1 200 ok in logcat, I don't think the data is being passed or taken in correctly. Can someone help, I'm stuck and have no direction.
Android code:
public void writeJSON() {
String convertedID;
String convertedVote;
//convert int to string value to passed
convertedID = new Integer(selectedID).toString();
convertedVote = new Integer(selectedVote).toString();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/kcstores.php");
try {
//writes the output to be stored in creolefashions.com/test2.php
ArrayList <NameValuePair> nvps = new ArrayList <NameValuePair>(2);
nvps.add(new BasicNameValuePair("storeUpdate", "update"));
nvps.add(new BasicNameValuePair("storeID", convertedID));
nvps.add(new BasicNameValuePair("storeVote", convertedVote));
httppost.setEntity(new UrlEncodedFormEntity(nvps));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
Log.i("writeJSON", response.getStatusLine().toString());
} catch(Exception e) {
Log.e("log_tag", "Error in http connection"+e.toString());
}
}
PHP Code:
<?php
$link = mysql_connect("localhost", "root", "") or die (mysql_error());
mysql_select_db("king_cake_stores")or die (mysql_error());
$query = "SELECT * FROM storeInfo";
$result = mysql_query($query);
$getUpdate = "noupdate";
if (isset($_POST['storeUpdate'])) {
echo "receiving data from app";
$getUpdate = $_POST['storeUpdate'];
$getStoreID = $_POST['storeID'];
$getStoreVote = $_POST['storeVote'];
}
// If command == getStoreID, it updates the table storeVote value
// with the android storeVote value based upon correct storeID
if ($getUpdate == "update") {
mysql_select_db("UPDATE storeInfo SET storeVote = $getStoreVote
WHERE storeID == $getStoreID");
} else {
// stores the data in an array to be sent to android application
while ($line = mysql_fetch_assoc($result)) $output[]=$line;
print(json_encode($output));
}
mysql_close($link);
?>
I suggest you start debugging from the server end and start working your way backwards.
First, start logging the response text from your HttpResponse.
Echo the mysql query text in your php file, and make sure it looks the way you're expecting it to.
If it looks correct, check your database structure.
If not, try doing a var_dump($_POST), and check to see if your parameters are being sent correctly.
If you run through these steps, you should have a better idea of where the problem is.
This might not be the whole problem, but:
mysql_select_db("UPDATE storeInfo SET storeVote = $getStoreVote
WHERE storeID == $getStoreID");
That should be mysql_query.
Here try this, using PDO:
<?php
//Db Connection Class
Class db{
private static $instance = NULL;
private function __construct() {}
public static function getInstance($DBUSER,$DBPASS) {
if (!self::$instance){
try {
self::$instance = new PDO("mysql:host=localhost;dbname=king_cake_stores", $DBUSER, $DBPASS);
self::$instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch (Exception $e){
die('Cannot connect to mySQL server.');
}
}
return self::$instance;
}
private function __clone(){}
}
//Connect to PDO
$db = db::getInstance('username','password');
//Inser Update
if (isset($_POST['storeUpdate'])) {
try {
/*** UPDATE data ***/
$query = $db->prepare("UPDATE storeInfo
SET storeVote = :storeVote
WHERE storeID = :storeID");
$query->bindParam(':storeVote', $_POST['storeVote'], PDO::PARAM_STR);
$query->bindParam(':storeID', $_POST['storeID'], PDO::PARAM_INT);
/*** execute the prepared statement ***/
$query->execute();
}catch(PDOException $e){
echo $e->getMessage();
}
//Output Current
}else{
$result = $db->query('SELECT * FROM storeInfo')->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result);
}
/*** close the database connection ***/
$db = null;
?>
Try using or die after every PHP command. Also use try catch blocks in Android
This will reduce errors in the code.