PHP PDO MySQL: Insert statement runs without error, no insert occurs - php

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.

Related

Unable to post API Rest PHP SQLITE

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();

PHP/mySQL - INSERT INTO not working but also no error

one specific php/mydql command is not working. the sql will not be executed, nor do I get an error message. The sql command executed by HEIDI SQL gives me no error. Query before this command are executed correct. Only this one specific isn't working. I wrote it done one by one as the others which worked perfect before. Heres the code:
$sql = "INSERT INTO users (username,password,email) VALUES(?,?,?)";
$stmt = $conn->prepare($sql);
$stmt->execute(array($username, $hash, $email));
The connection.php file code:
global $conn;
$config = [
$dbname = "mysql:host=localhost; dbname=starwardb;",
$login = "root",
$password = ""
];
try {
$conn = new PDO(...$config);
} catch (Exception $ex) {
echo "ERROR: " . $ex;
}
Thank you for any advice!
The mistake was, that the hashing of the password extends the string. The Database length of the password was by 50. I have increased it to 64 and now it works fine.
From: https://stackoverflow.com/revisions/45147068/3

HTTP Error 500 when trying to execucute INSERT INTO sql query

I'm fairly new to php and SQL and just can't figure out the problem. Note that this is a school project, therefore the vulnerability to SQL Injections and saving the blank passwords are nothing to worry about.
After the User filled out the Login-form, he's redirected to this page:
[Some html]
<?php
if(isset($_POST['submit']))
{
ConnectSQL();
}
//Retrieve POSTed Login information
$Username = htmlspecialchars($_POST['RegUsername']);
$Email = htmlspecialchars($_POST['RegEmail']);
$Password = htmlspecialchars($_POST['RegPassword']);
function ConnectSQL() {
// SQL Server Extension Sample Code:
// (ConnectionInfo, obviously it's there in the real file)
$conn = sqlsrv_connect($serverName, $connectionInfo);
// PHP Data Objects(PDO) Sample Code:
try {
$conn = new PDO('sqlsrv:server = tcp:xxx.database.windows.net,1433; Database = userdb', 'arechon', '{NotTheRealPassword}');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Successfully connected to SQL Server and DB";
Register();
}
catch (PDOException $e) {
print('Error connecting to SQL Server.');
die(print_r($e));
}
}
function Register($Username, $Email, $Password) {
$regquery = "INSERT INTO dbo.Users (Username, Email, Password) VALUES ('UsernameTest', 'EmailTest', 'PasswordTest')";
$conn->query($regquery);
echo '<script type="text/javascript">window.open("http://xxx.azurewebsites.net/Login.html", "_self");</script>';
The Code always seems to stop at $conn->query($regquery); and doesn't return any error messages. Sometimes it just stops, when I slightly modify the Code (e.g. replacing $conn->query($regquery); with $conn->exec($regquery); or using " instead of ') I get a HTTP500 error.
I found some similiar questions here on stackoverflow as well as on other plattforms, but none of the provided answers could solve this error. Note that I use SQL and NOT MySQL (though it wouldn't be a lot of work to change that if you think that could solve my problem).

PHP mysqli insert return error invalid request

I've been having a bit of trouble with my PHP code.
I'm trying to insert a new row in table gebruikers.
I'm using a JSON API to post the data from my C# Android app to the server.
running the code returns an invalid request error.
PHP:
function registerUser($api_data)
{
// connection
$servername = "xxx";
$username = "xxx";
$password = "xxx";
$database = "test";
$mysqli = new mysqli($servername, $username, $password, $database);
//check connection
if(mysqli_connect_errno())
{
API_Response(true, 'connection error');
}
$register_data = json_decode($api_data);
$leerlingnummer = intval($register_data->leerlingnummer); //passed as string, int in database
$wachtwoord = $register_data->wachtwoord; //string
$email = $register_data->email; //string
$result = $mysqli->query("INSERT INTO `gebruikers` (`Leerlingnummer`, `Wachtwoord`, `Email`) VALUES ({$leerlingnummer}, {$wachtwoord}, {$email})");
if ($result == false)
{
API_Response(true, "{$mysqli->error}");
}
else
{
API_Response(false, 'SUCCESS');
}
$mysqli->close();
}
database is looking as follows:
database layout
I've never felt this stupid before, but the error came from the fact that I was still referencing to an older .php file. I was so focussed on the PHP script that I didn't notice this error in my app before.
the quotes advised by Sean and fuso were needed later on though so thanks for that.
Problem solved, sorry for wasting some of your time :/
You should quote your data in the insert query.
... VALUES ('{$email}','{$other}')

Insert values from csv file to MySQL table

I'm trying to insert values extracted from a csv file to a mysql table. It runs but the table is not populated. I've tried to debug for the last XXXX but just can't see my error. Echo-ing out the values give me the correct SQL but when it comes to the INSERT - no dice.
Thanks very much for your help.
<?php
$host = 'localhost';
$user = 'fulltime_admin';
$pass = 'secret';
$database = 'fulltime_db';
$db = mysql_connect($host, $user, $pass);
mysql_query($database, $db);
//////////////////////////////// EDIT ////////////////////////////////////
$redirect_num = 500; // Select how many rows to insert each time before refresh.
// More rows = faster insertion. However cannot be too high otherwise it will timeout.
$filename = "ps4_emails.csv"; // The file we are going to get the data from...
$table = "`ps4_emails`";
////////////////////////////// END EDIT //////////////////////////////////
$file = file($filename);
$lines = count($file);
// Have we just redirected?
$nextline = $_GET['nextline'];
if (!isset($nextline)){
$nextline = 0;
}
$query = "INSERT INTO ".$table." (email) VALUES ('".$final_line[0]."')";
for ($line=$nextline; $line<=$lines; $line++){
$final_line = explode(",", $file[$line]);
if ($line!=$lines){
mysql_query($query,$db);
}
if ($line % $redirect_num){
// something needs to go here
} else {
$nextline = $line+1;
exit ('<meta http-equiv="refresh" content="0;url=texttomysqlemails.php?nextline='.$nextline.'" />');
}
echo ( $line==$lines ) ? "Done" : "";
}
?>
Put your query inside loop in order use it with variable $final_line.
Try this :
$final_line = explode(",", $file[$line]);
if ($line!=$lines){
$query = "INSERT INTO ".$table." (email) VALUES ('".$final_line[0]."')";
mysql_query($query,$db);
}
Don't use mysql_*. It's deprecated and removed from PHP 7. Use mysqli_* or PDO.
This seems like a perfect script to run from the command line PHP CLI and therefore you can forget about all the refresh complexity.
If the file is huge, like your comment suggest, loading all the file into memory may also bring you up against the PHP memory limits, so it might be better to read a line at a time rather than the whole file using fgetcsv() which is intended for reading csv files.
<?php
$host = 'localhost';
$user = 'fulltime_admin';
$pass = 'secret';
$database = 'fulltime_db';
$db = mysql_connect($host, $user, $pass);
mysql_query($database, $db);
$filename = "ps4_emails.csv";
$table = "";
$handle = fopen('ps4_emails.csv', 'r');
if ( ! $handle ) {
echo 'File does not exists in this location';
exit;
}
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$query = "INSERT INTO `ps4_emails` (email) VALUES( '{$data[0]}')";
mysql_query($query,$db);
}
?>
You now just run this script from the command line/terminal like
>php script.php
And it can run for minutes/hours/days with no likleyhood of blowing any limits.
I have to mention this or someone will nag me for not saying it
Please dont use the mysql_ database extension, it is deprecated (gone for ever in PHP7)
Especially if you are just learning PHP, spend your energies learning the PDO or mysqli_ database extensions,
and here is some help to decide which to use
When you need to upload the real file, it would also be a good idea to add a restart mechanism, so you can restart the process from whereever a problem happened or someone shut the database down for a backup or some other unforseen hiccup.
<?php
$host = 'localhost';
$user = 'fulltime_admin';
$pass = 'secret';
$database = 'fulltime_db';
$restart_from = 0;
$db = mysql_connect($host, $user, $pass);
mysql_query($database, $db);
$filename = "ps4_emails.csv";
$table = "";
$handle = fopen('ps4_emails.csv', 'r');
if ( ! $handle ) {
echo 'File does not exists in this location';
exit;
}
// is it a restart?
if ( file_exists('restart.txt') ) {
// its a restart
$restart_from = file_get_contents('restart.txt');
// read up the file to the last good row inserted
for ( $i=0; $i<=$restart_from; $i++ ) {
$data = fget($handle, 1000);
}
}
$upd_cnt = restart_from;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$query = "INSERT INTO `ps4_emails` (email) VALUES( '{$data[0]}')";
mysql_query($query,$db);
$upd_cnt++;
file_put_contents('restart.txt', $upd_cnt);
}
?>
The above restart code is not tested, but I have used something very like this in the past very successfully. So you will have to check I have not made any silly mistakes, but it should give you an idea of how to do a restart from the last row successfully updated before a crash.
You can use LOAD DATA INFILE to insert from file.
refer http://dev.mysql.com/doc/refman/5.7/en/load-data.html
insert csv file data into mysql

Categories