I've hired Cloudatcost, and I've configured an Ubuntu server, installed LAMP and uploaded my web page.
I have a section where I upload some text fields and an an image, the problem is that the image is not being uploaded, but when I run my page locally it works.
My insert code goes like this:
function insert($title, $intro, $body, $data ,$date, $someid, $Myimage, $somesection){
$ID = null;
$mysqli = openConnection(); <- starts connection
$query = "INSERT INTO columnsa (title, intro, body, data, date, someid) VALUES (?, ?, ?, ?, ?, ?)";
if ($stmt = $mysqli->prepare($query))
{
$stmt->bind_param(
'sssssi', $title, $intro, $body, $data, $date, $someid);
/* Execution*/
$stmt->execute();
$ID = $mysqli->insert_id;
/* Close query */
$stmt->close();
}
if($ID)
{
if ($image != null) {
insertImg($image, $ID, $section);
closeConnection($mysqli);
return true;
}
}
else
{
closeConnection($mysqli);
return false;
}
}
And my Insert image is:
function insertImg($image, $ID, $section)
{
switch ($seccion) {
case "journey":
move_uploaded_file($imagen['tmp_name'], "../../img/journeys/".$ID.".jpg");
break;
case "column":
move_uploaded_file($imagen['tmp_name'], "../../img/bolumns/".$ID.".jpg");
break;
case "blog":
move_uploaded_file($imagen['tmp_name'], "../../img/blogs/".$ID.".jpg");
break;
}
}
I'm guessing that maybe I forget to install an php5 module, because the lines
$ID = $mysqli->insert_id;
/* Close query */
$stmt->close();
}
if($ID)
{
if ($image != null) {
insertImg($image, $ID, $section);
closeConnection($mysqli);
return true;
}
}
else
{
closeConnection($mysqli);
return false;
}
Don't seem to work. Any Idea which php5 module includes insert_id?
Thanks!
1.Check if the row inserted to the database. if it didn't insert, you did something wrong. like wrong query (for example field name or,...) or connecting problem. if you have not database problem go to #2.
2.check if your folder that you are trying to upload has proper permission by:
ls -l
if it has not proper permission. read this:
https://help.ubuntu.com/community/FilePermissions
3.If it has no problem with database and permission, it means you are trying to insert to the wrong folder. try it with dirname(__FILE__). it will get your current file directory. for example, change this line:
move_uploaded_file($imagen['tmp_name'], "../../img/journeys/".$ID.".jpg");
to the
move_uploaded_file($imagen['tmp_name'], dirname(__FILE__)."/../../img/journeys/".$ID.".jpg");
For Checking Log
go to this file
sudo nano /var/log/apache2/error.log
if you couldn't find log file there, go to this file to find where is your log file:
sudo nano /etc/php_version/apache2/php.ini
*replace php_version with proper folder
In order to retrieve the Last inserted ID as per the Question you have made you have made is is compulsory that you have run the
Executed Statement
Queried Statement
after Insertion in-order to get the last inserted ID in mysqli.* or in PDO top.
In your code you have to change of how to get the last inserted ID since you have not run the query after Execution.
Replace:
$ID = $mysqli->insert_id;
With:
$ID = $stmt->insert_id;
Note: Since you have executed the query using $stmt alone and not with the $mysqli you need to change it to as i have mentioned.
Below are the Example of how to get the last inserted ID based on Mysqli and PDO
Scenario 1: (Mysqli)
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
Here you have run the query after the query is being executed.
Scenario 2: (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
// use exec() because no results are returned
$conn->exec($sql);
$last_id = $conn->lastInsertId();
echo "New record created successfully. Last inserted ID is: " . $last_id;
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
I've solved it by assigning the proper permissions.
As this questions says
Make sure all files are owned by the Apache group and user. In Ubuntu it is the www-data group and user
chown -R www-data:www-data /path/to/webserver/www
Next enabled all members of the www-data group to read and write files
chmod -R g+rw /path/to/webserver/www
I gave read and write permissions to my Images folder outside my web page's folder (due to good security practices).
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.
I'm trying to upload an image to my server using the following form by Sanwebe.
Can be found here.
However when I'm pressing upload, the new thumb loads perfectly fine. However, my image can't be uploaded to the database using the exact same variables from which the image is being viewed. How come?
I tried putting the db information just infront of the query. Like this:
echo '<div align="center">';
echo '<img src="images/profile-pictures/'.$thumb_prefix . $new_file_name.'" alt="Thumbnail">';
echo '</div>';
$profile_pic_temp = "../images/profile-pictures/" . $thumb_prefix . $new_file_name;
$profile_pic_full_temp = "../images/profile-pictures/" . $new_file_name;
$session_user = $_SESSION['user_confirm'];
require 'database.php';
$profile_pic_db_upload = $db->prepare("UPDATE login SET profile_picture_temp = :profile_pic_temp, profile_picture_full_temp = :profile_pic_full_temp WHERE user_session = :session_user");
$profile_pic_db_upload->bindParam(':session_user', $session_user, PDO::PARAM_STR);
$profile_pic_db_upload->bindParam(':profile_pic_temp', $profile_picture_temp, PDO::PARAM_STR);
$profile_pic_db_upload->bindParam(':profile_pic_full_temp', $profile_picture_full_temp, PDO::PARAM_STR);
$profile_pic_db_upload->execute();
$confirm_upload_db = $profile_pic_db_upload->rowCount();
if($confirm_upload_db != 0){
$popup_message = "Profile picture has been uploaded.";
echo $popup_message;
}
else{
$popup_message = "Profile picture could not be uploaded.";
echo $popup_message;
}
EDIT TWO:
The query now runs, however, I get the feedback "Profile picture could not be uploaded.". How come the query does not run properly?
EDIT FOUR:
I have tried changing the user_session = :session_user to id = 1 instead. I then get upload successfull, however, the value is only inserted into profile_picture_temp and is set to 0. Somehow the bindParam changes the value. Why?
EDIT THREE:
I have now tried using mysqli aswell. Same results here. Returning could not be uploaded. However, does not change value in DB.
$sql = "UPDATE login SET profile_picture_temp = ? AND profile_picture_full_temp = ? WHERE user_session = ?";
$stmt = $mysqli->prepare($sql) or die ("Database error<br>" . $sql . "<br><b>Error message:</b> " . $mysqli->error);
$stmt->bind_param("sss", $profile_picture_temp, $profile_picture_full_temp, $session_user);
$stmt->execute() or die("Something went wrong");
if($stmt->fetch()){
$popup_message = "Profile picture has been uploaded.";
echo $popup_message;
}
else{
$popup_message = "Profile picture could not be uploaded.";
echo $popup_message;
}
$stmt->free_result();
$stmt->close();
Are you sure this line isn't throwing a PHP error...
$confirm_upload_db = $$profile_pic_db_upload->rowCount();
^^
The $$ (two dollar signs) are how we reference a variable variable; but $profile_pic_db_upload doesn't contain the name of another variable, it's a reference to a PDO statement object.
Another note. The rowCount() function returns the number of rows affected by the UPDATE statement; if the UPDATE statement succeeds, but no actual changes are made to the row (because the values assigned to the columns are the same as what's already stored in the columns), then rowCount() will return 0.
(To change that behavior, to have it return the number of matched rows, you can use PDO::MYSQL_ATTR_FOUND_ROWS).
The problem was fixed using the following query:
$profile_picture_temp = "../images/profile-pictures/" . $thumb_prefix . $new_file_name;
$profile_picture_full_temp = "../images/profile-pictures/" . $new_file_name;
$session_user = $_SESSION['user_confirm'];
$sql = "UPDATE login l SET l.profile_picture_temp = ?, l.profile_picture_full_temp = ? WHERE l.user_session = ?";
$stmt = $mysqli->prepare($sql) or die ("Database error<br>" . $sql . "<br><b>Error message:</b> " . $mysqli->error);
$stmt->bind_param("sss", $profile_picture_temp, $profile_picture_full_temp, $session_user);
$stmt->execute() or die("Something went wrong");
$result = $stmt->affected_rows;
if($result == 1){
$popup_message = "Profile picture has been uploaded.";
echo $popup_message;
}
else{
$popup_message = "Profile picture could not be uploaded.";
echo $popup_message;
}
$stmt->free_result();
$stmt->close();
I can't identify the problem itself, however, I managed to fix it by adding UPDATE login l. Using alias fixed it somehow.
Here's what the situation is: I am trying to use PHP to call scanimage on a Linux host, then save the resulting file to a web directory for future use.
The below code produces no errors, but when I check out the /tmp directory, file.pnm is blank, and the scanner never starts.
<?php
require('/var/www/olin/includes/functions.php');
$con = connect_db();
//setup the POST variables
if (isset($_POST['submit'])) {
$fname = mysqli_real_escape_string($con, $_POST['fname']);
$lname = mysqli_real_escape_string($con, $_POST['lname']);
$license_no = mysqli_real_escape_string($con, $_POST['license_no']);
$comments = mysqli_real_escape_string($con, $_POST['comments']);
}
if ($license_no == '') {
$license_no = "None on File";
}
if ($fname == '' || $lname == '') {
echo '<h1 class="message">Can\'t submit visitor: you are missing information!</h1>';
} else {
//setup the query and prepare it for exection
$query= "insert into visitors (fname, lname, license_no, redsheet, comments)" .
" values (?, ?, ?, 'Allow', ?) on duplicate key update fname = values(fname)," .
"lname = values(lname), license_no = values(license_no), redsheet = values(redsheet)," .
"comments = values(comments)";
$stmnt= mysqli_prepare($con, $query);
//bind the statement parameters to variables
mysqli_stmt_bind_param($stmnt, "ssss", $fname, $lname, $license_no, $comments );
//execute, then close the statment
if (!mysqli_stmt_execute($stmnt)) {
echo "Failed to ececute the query: " . mysqli_error($con);
header('Refresh: 10; url=http://localhost/olin/visitor.php');
}
}
// we'll `try` to scan the license if the checkbox is selected
if (isset($_POST['pic_id'])) {
// get the info from the db
$query = 'select id from visitors where license_no = "'.$license_no.'"';
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result)) {
$id = $row['id'];
// set up the path to save the id to (and put path into db for further look up
// and display)
$dir = ( $id % 30 );
$path = '/var/www/olin/images/licenses/'.$dir.'/'.$id.'-license.png';
$path = addslashes(mysqli_real_escape_string($con, $path));
$path1 = '/images/licenses/'.$dir.'/'.$id.'-license.png';
// start the scan, and save image
$command = '/home/jmd9qs/bin/scan.sh "'.$path.'"';
$update = 'update visitors set id_pic = "'.$path1.'" where id="'.$id.'"';
mysqli_query($con, $update) or die ('Error: ' . mysqli_error($con));
exec($command);
header('Location: http://localhost/olin/visitor.php');
}
}
?>
Can anybody provide any hints?
UPDATE:
I have the server running the command now (I know it's failing because of the Apache2 error log).
Here's the error I get:
scanimage: open of device brother3:bus2;dev1 failed: Invalid argument
I've tried adding the www-data user to the scanner and lp groups, but it seems to have no effect... The scanimage command I'm using works under my normal user and as root, so I'm now positive the command I'm using should work. I am still at a loss...
UPDATE (again):
I've fixed some errors in my code... now the server will scan and successfully save images! However, it only works once and then for some odd reason I have to run the scan.sh (which I put the scanimage command into) through my shell for it to run again... otherwise I get the same error message!
Very weird, I have NO clue why, suggestions wanted!
When I ran this piece of code
<?php
include '../bin/config.php';
connect();
if (isset($_GET['id']) && is_numeric($_GET['id'])){
$id = $_GET['id'];
$stmt = $conn->prepare("DELETE FROM noteline WHERE Nid = ?");
$stmt->bindParam(1, $id, PDO::PARAM_INT);
$outcome = $stmt->execute();
if ($outcome){
echo 'it was successfully deleted';
header("Location: ../noteline");
}else {
echo 'it was not successful due to something';
}
}
?>
it echoed "it was successfully deleted" but nothing was deleted from my database...
but when I started a transaction by modified this code like this:
<?php
include '../bin/config.php';
connect();
if (isset($_GET['id']) && is_numeric($_GET['id'])){
$id = $_GET['id'];
$stmt = $conn->prepare("DELETE FROM noteline WHERE Nid = ?");
$stmt->bindParam(1, $id, PDO::PARAM_INT);
$conn->beginTransaction();
$outcome = $stmt->execute();
if ($outcome){
$conn->commit();
echo 'it was successfully deleted';
header("Location: ../noteline");
}else {
echo 'it was not successful due to something';
}
}
?>
My data was finally deleted from my MySQL database!
I want to know why?
Because the PDO connection is operating with auto-commit mode disabled. Look into the connect() function to ensure that you don't disable this mode.
(Also, I see you're using a global variable to store the connection object. Avoid global variables where possible.)
Sounds like your server might have autocommit turned off?
http://dev.mysql.com/doc/refman/5.0/en/commit.html
By default, MySQL runs with autocommit mode enabled. This means that
as soon as you execute a statement that updates (modifies) a table,
MySQL stores the update on disk to make it permanent.
There might be a line in your code somewhere that sends
SET autocommit=0;
to your server.