I've made this code but for some reason when i submit the form the data is not inserted to the table name posts. here's my code, i might have a typo or something, it'd be great if someone could have a look.
$fnames = Array("","","","","");
$fcnt = 0;
if (isset($_POST['submit']))
{
$allowedExts = array("gif", "jpeg", "jpg", "pjpeg", "x=png","png",);
// do all 5 files!
for ( $fnum = 1; $fnum <= 5; ++$fnum )
{
$curfile = $_FILES["uploaded_file" . $fnum];
if ($curfile["error"] > 0) {
echo "Return Code: " . $curfile["error"] . "<br>\n";
} else {
$ftype = explode( "/", $curfile["type"])[1]; // get the part after the /
$fsize = $curfile["size"];
if ( in_array($ftype, $allowedExts) && $fsize < 20000000 )
{
echo "Upload: " . $curfile["name"] . "<br>\n";
echo "Type: " . $ftype . "<br>\n";
echo "Size: " . ($fsize/1024) . " KB<br>\n";
echo "Temp file: " . $curfile["tmp_name"] . "<br>\n";
$fname = $_SESSION["userid"] . "_" . $curfile["name"];
if (file_exists("uploads/$fname"))
{
echo "$fname already exists.<br>\n";
} else {
move_uploaded_file($curfile["tmp_name"], "uploads/$fname");
$fnames[$fnum-1] = $fname;
++$fcnt;
}
}
else
{
echo "No valid file in slot $fnum<br>\n";
}
}
}
if ( $fcnt > 1 )
{
$sql = "INSERT INTO posts (picture1, picture2, picture3, picture4, picture5) VALUES( ". "'" . implode("','", $fnames) . "')";
echo "DEBUG SQL: $sql <hr>\n";
mysqli_query($sql);
}
}
With a quick glance:
A) error in your mysqli_query($sql);.
The mysqli_ extensin needs the connection pointer, something like: mysqli_query($dbConn, $sql);
B) Also, modify your query to look like mysqli_query($dbConn, $sql) or die(mysqli_error($dbConn));. It will show you the sql errors, if any.
EDIT 1
If no errors appear after you put the mysqli_error(), then i think your script never gets to the sql part. Something stops it before that if.
Put on top of your script:
error_reporting(E_ALL);
ini_set('display_errors', '1');
and check if any php errors appear on the page.
Most of the time is a string/integer mismatch. Double check all your string escape characters. Copy your final query string and use some external tool to submit the query. You could start hardcoding all your data in the query and then proceed by adding one parameter at a time. Eventually you'll find the field (or fields) that causes the problem.
However, read carefully the error message first instead of guessing blindly what's causing the problem :-)
Make sure your fields count and values count are the same. Also correct this as well:
"'".implode("','", $fnames)."'"
in values passed.
Related
I am trying to get the contents of the MySQL table to a CSV file. Everything works fine except that a blank row is being inserted before the heading label that I pass through Array.
<?php
error_reporting(0);
ob_start();
session_start();
include 'auto_logout.php';
//echo $_SESSION['fullname'];
if ((!isset($_SESSION['ufullname'])) && (!isset($_SESSION['fullname']))) {
/* Redirect browser */
header("Location: index.php");
/* Make sure that code below does not get executed when we redirect. */
exit();
}
$output = "";
require_once('config/config.php');
require_once("includes/ftp_settings.php");
$table = "Download CSV"; // Enter Your Table Name
if (is_array($new_exist) && (is_array($ftp1))) {
$ressd_new = 'select filename from files where uploaded_by IN ("' . implode('","', $new_exist) . '")';
$resd_new = mysql_query($ressd_new);
while ($kkk_new = mysql_fetch_array($resd_new)) {
$gotit_new = $kkk_new[0];
}
$resultka_new = $ftp1;
$sql = 'SELECT slno, filename, uploaded_by, dateadded, timeadded, size FROM files where uploaded_by IN ("' . implode('","', $new_exist) . '") and filename IN ("' . implode('","', $resultka_new) . '") and size != "0"';
} else {
$sql = "SELECT slno, filename, uploaded_by, dateadded, timeadded, size FROM files where ftp_file = '$ftp_server' and ftp_u_file = '$ftp_user_name' and ftp_p_file = '$ftp_user_pass' and size != '0'";
}
$sql = mysql_query($sql);
$columns_total = mysql_num_fields($sql);
// Get The Field Name
$heading1 = array(
"Sl. No.",
"File Name",
"Uploaded By",
"Date Added",
"Time Added",
"Size"
);
$inc = 0;
for ($i = 0; $i < $columns_total; $i++) {
$heading = $heading1[$inc];
$output .= '"' . $heading . '",';
$inc = $inc + 1;
}
$output .= "\n";
// Get Records from the table
while ($row = mysql_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {
$output .= '"' . $row["$i"] . '",';
}
$output .= "\n";
}
// Download the file
$filename = "myFile.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename=' . $filename);
echo $output;
exit;
?>
Not really sure where is the blank line coming from.
Including files will often add unwanted whitespaces if not cared properly.
Suppressing errors will make the things worse in every case.
The reason you need ob_start() is because the script between ob_start() and "echo $output;" is printing some content (your empty line probably). And therfore you can't set headers. I'll bet it's in your included files (auto_logout, config, ftp_settings).
Allow errors, remove ob_start, solve all warnings, profit.
And btw: Do not use mysql extension, use mysqli instead.
I am writing a script to try and help make my day to day work easier. It works in parts, sending requests to an API and receiving responses. I then want it to save said responses in a text file that will be automatically emailed to a defined mailbox. The bit I am stuck with, is actually making my script save to a text file.
This is my script: (I'm not very experienced.. the include files aren't relevant, as they send requests the the API and contain nothing else.) I'm hoping that i can literally add a line at the bottom after the SQL connection closes to tell it to save to the text file. Also, I would like the text file to take the name of the "$CorrectCLI" variable.
Any help is appreciated. Cheers.
// Check connection
if(mysqli_connect_errno()) {
echo "Could Not Connect, Contact Support.";
exit;
} else {
echo "Connected to Database Successfully.<br><br>";
}
//Required Information:
$CorrectCLI = $CLIrow[0];
$CorrectSitename = $SiteNamRow[0];
$CorrectSiteNumber = $SiteNumRow[0];
$CorrectIP = $IProw[0];;
$xrefFromKF = "503269";
echo nl2br("Affected XREF: " . $xrefFromKF . "\n");
$CLIquery = "select primary_cli from customers where xref = " . $xrefFromKF . "";
$CLIresult = mysqli_query($con,$CLIquery);
if(!$CLIresult) {
echo "Could Not Locate CLI In Database.<br>";
}
$CLIrow = mysqli_fetch_row($CLIresult);
$CLI = $CLIrow[0];
echo nl2br("Circuit CLI: 0" . $CLIrow[0] . "<br>");
if(!$CLI > 0 ) {
echo " Could Not Locate CLI.<br>";
}
$IPquery = "select manufacturers_ip_prim from customers where primary_cli = " . $CLIrow[0] . "";
$result = mysqli_query($con,$IPquery);
if(!$result) {
echo "Could Not Locate Management IP.<br>";
}
$IProw = mysqli_fetch_row($result);
$IPcount = $IProw[0];
echo nl2br("Circuit IP: " . $IProw[0] . "");
if(!$IPcount > 0 ) {
echo " Could Not Locate Management IP.<br>";
}
echo nl2br("\n\nPinged " . $IPcount . "...\n");
exec("ping -c 2 " . $IPcount, $output1, $result1);
if ($result1 == 0) {
echo nl2br("Circuit Recovered - Cancelled Diagnostics.");
} else {
echo nl2br("Circuit Down - Starting Diagnostics");
// Perform Sync Check
include '../diags/SyncStatus.php';
// Perform Data Port Reset
include '../diags/DataPortReset.php';
// sleep(10);
echo nl2br("\nPinged " . $IPcount . "...\n");
exec("ping -c 2 " . $IPcount, $output2, $result2);
if ($result2 == 0) {
echo nl2br("Circuit Recovered - Stopping Diagnostics.");
} else {
echo nl2br("Circuit Still Down - Continuing Diagnostics\n\n");
include '../diags/Metascript.php';
include '../diags/TAMtestSubmit.php';
include '../diags/TAMtestRetrieve.php';
echo "<br>";
include '../diags/GetProfile.php';
echo "<br>";
include '../diags/ProfileOverride.php';
echo "<br>";
// sleep(300);
include '../diags/RevertProfile.php';
echo "<br>";
echo nl2br("\nPinged " . $IPcount . "...\n");
exec("ping -c 2 " . $IPcount, $output4, $result4);
//print_r($output4);
if ($result4 == 0) {
echo nl2br("Circuit Recovered - Stopping End Of Diagnostics.");
} else {
echo nl2br("Circuit Still Down - Requires Attention.\n\n");
}
}
}
// Close the Database Connection
$conn->close();
?>
I would use the PHP output buffer.
Add this code to the top of this PHP script
ob_start("process_output");
function process_output($buffer){
$pageContent = $buffer;
// $pageContent is all the output of your web page,
// put your email logic here
return $pageContent;
}
In your logic I would reference http://php.net/manual/en/function.file-put-contents.php
I have a database that has around 700 terms. I would just like to write a single php file called internationalize that would check the mysql database and return the proper translation. All the PHP variables have been setup and there is view that contains the translation of all the languages. There are about 11 languages. I have looked in a lot of places, but there isn't one that fits my situation. Any suggestions would be greatly appreciated.
if (!isset($_SESSION))
{
session_start();
}
if (isset($setup))
{
$lang=$_SESSION['setupLang'];
}
elseif (isset($_SESSION['lang']))
{
$lang=$_SESSION['lang'];
}
else
{
require("fetchMainConfig.php");
}
$lang_code = $lang;
//file_dir contains the language codes for example: il,fr,pt,ge and so on
$sql = "SELECT file_dir FROM `hydroserver_translation`.`language_file_dir`";
if($lang_code = $sql){
// What should go in here??? What is the best way to
// dynamically translate the database?
}
I am also attaching a copy of the database view. I plan to write the code is such a way that if there is no language translation the default translation is in english.
This is what I have done and it works. Thank you for your help!
<?php
//Connects to the database
$mysqlserver="servername";
$mysqlusername="langreader";
$mysqlpassword="readHSLlang#9";
$error=0;
$link=mysqli_connect($mysqlserver, $mysqlusername, $mysqlpassword) or $error=1;
$dbname = 'translation';
mysqli_select_db($link, $dbname) or $error=1;
if(!$error)
{//check which is the session language
$language = $lang_code;
//language file path
$file_path = "languages/" .$language. ".php";
//Check if file exists
$file_exists = file_exists($file_path);
if($file_exists){
// The file exists. Now just check when it was last time created.
$file_created_time = filemtime($file_path);
$timezone = date_default_timezone_set('UTC');
$current_time = time();
//Time lapse to check the difference between the current time and the last created time
$time_lapse = (abs($current_time-$file_created_time)/60/60);
//SQL statement to access the view from the database
$sql = "SELECT * FROM translation.translations_by_language";
$terms = mysqli_query($link, $sql);
//Will create a new file if it has been more than four hours
if($time_lapse >= '4.0'){
//Deleting the existing file to avoid any parsing errors
unlink($file_exists);
//Writing the new language_file
$lang_file= fopen("languages/" .$language. ".php","c+");
//Loops through the query and shows the translated terms
//and english terms if there are no translations for the term
$new_file = "<?php" . "\n ";
fwrite($lang_file, $new_file);
while($row = mysqli_fetch_array($terms)) {
if ($row[$language] != "")
fwrite($lang_file,$row['php_variable']. " = " . '"' . addslashes($row[$language]) . '"' . ";" . "\n ");
else
fwrite($lang_file,$row['php_variable']. " = " . '"' . addslashes($row['english_phrase']) . '"' . ";" . "\n ");
}
$last_line = "?>";
fwrite($lang_file, $last_line);
fclose($lang_file);
}
}
else{
// Creating a new file if the file doesn't exist
$sql = "SELECT * FROM hydroserver_translation.translations_by_language";
$terms = mysqli_query($link, $sql);
$lang_file= fopen("languages/" .$language. ".php","c+");
$new_file = "<?php" . "\n ";
fwrite($lang_file, $new_file);
while($row = mysqli_fetch_array($terms)) {
print_r($row);
if ($row[$language] != "")
//Provide the translation
fwrite($lang_file,$row['php_variable']. " = " . '"' . addslashes($row[$language]) . '"' . ";" . "\n ");
//If translation doesn't exist, just use the english phrase
else
fwrite($lang_file,$row['php_variable']. " = " . '"' . addslashes($row['english_phrase']) . '"' . ";" . "\n ");
}
$last_line = "?>";
fwrite($lang_file, $last_line);
fclose($lang_file);
//New language file succesfully created!!!!
}
}
I am trying to output my PHP code to a downloadable CSV file and so far i am able to do this however at the moment, the output does not place the field data into separate columns. Instead it puts everything into one column and in addition to that, it displays the postcodes in its neighbouring columns. Does anyone know why this is?
<?php
header("Content-type: text/csv");
header("Cache-Control: no-store, no-cache");
header('Content-Disposition: attachment; filename="filename.csv"');
$outstream = fopen("php://output",'w');
if ($db_found) {
// Select all fields from bodyshops_master_network table
$SQL = "SELECT * FROM bodyshops_master_network";
$result = mysql_query($SQL);
while ( $db_field = mysql_fetch_assoc($result) ) {
// Splits the arrays
$row = explode(",", $db_field['postcodes_covered']);
$dealer_code = $db_field['dealer_code'];
$dealer_name = $db_field['dealer_name'];
$bodyshop_id = $db_field['bodyshop_id'];
$bodyshop_name = $db_field['bodyshop_name'];
$address1 = $db_field['address1'];
$address2 = $db_field['address2'];
$address3 = $db_field['address3'];
$address4= $db_field['address4'];
$address5 = $db_field['address5'];
$postcode = $db_field['postcode'];
$bo_tel = $db_field['BO_tel'];
$bo_email = $db_field['BO_email'];
$bc_name = $db_field['BC_name'];
$equity_contract = $db_field['equity_contract'];
echo "<pre>";
foreach ($row as $value) {
echo $dealer_code . " ";
echo $dealer_name . " ";
echo $bodyshop_id . " ";
echo $bodyshop_name . " ";
echo $address1 . " ";
echo $address2 . " ";
echo $address3 . " ";
echo $address4 . " ";
echo $address5 . " ";
echo $postcode . " ";
echo $bo_tel . " ";
echo $bo_email . " ";
echo $bc_name . " ";
echo $equity_contract . " ";
echo $value. "<BR>";
fputcsv($outstream, $row, ',', '"');
}
echo "</pre>";
}
mysql_close($db_handle);
} else {
print "Database NOT Found ";
mysql_close($db_handle);
fclose($outstream);
}
?>
OK, you're doing something really weird here. You're outputting content in two ways.
First, you output content in the normal way using echo. Fair enough!
Second, you output content using fputcsv where the file handler leads to php://output. Also fair enough!
But you shouldn't do both and expect it to work seamlessly. You want a CSV file, so the best way is to output all your data using fputcsv. At the moment, some of your data is encapsulated as a CSV file, and some of it isn't. This leads to output that you don't really want.
I think you want something like this:
foreach ($row as $value) {
$output = array(
$dealer_code,
$dealer_name,
$bodyshop_id,
$bodyshop_name,
$address1,
$address2,
$address3,
$address4,
$address5,
$postcode,
$bo_tel,
$bo_email,
$bc_name.
$equity_contract,
$value
);
fputcsv($outstream, $output, ',', '"');
}
fputcsv expects the data to be an array, so that's what we give it. The separate array fields will be separate columns in the CSV output. We don't echo any data: we store it in an array and then supply it to fputcsv.
The second mistake you made was to send $row rather than $value to fputcsv. This meant that you were sending all the postcodes as received from the database row.
Finally, you don't need <pre>.
On a separate note, you really should have a better database structure. If you had a table of postcodes and a separate table of bodyshops and a foreign key linking them, the code to retrieve data would be a lot simpler, as would searching and updating it in future.
Okay I have this syntax for an UPDATE to a table in mysql inside a php script:
mysqli_query($con,"UPDATE ted SET description=$line[5]
WHERE speaker='$speaker' AND event='$event'");
Is there somehting wrong with it? it runs properly in my scriipt (no error's) however no updates are made even though: it is called multiple times (and has lines which match the WHERE condition) heres the entire script
<?php
$contents = file_get_contents('ted_csv.txt');
$con=mysqli_connect("localhost","root","admin","Media2net");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM ted");
$i=0;
while($row = mysqli_fetch_array($result))
{
$speaker =$row['speaker'];
$event =$row['event'];
$pattern2 = preg_quote($speaker, '/');
$pattern1 = preg_quote($event, '/');
$pattern1 = "/^.*$pattern1.*\$/m";
$pattern2 = "/^.*$pattern2.*\$/m";
if(preg_match_all($pattern1, $contents, $matches)){
$submatch = implode("\n", $matches[0]);
if (preg_match_all($pattern2, $submatch, $better)){
echo "got match" . $i . "\n";
$line =str_getcsv( $better[0][0] );
$a_bool = mysqli_query($con,"UPDATE ted SET description=$line[5]
WHERE speaker='$speaker' AND event='$event'");
if ($a_bool){
echo "got match" . $i . "\n";
}else{
echo "query unsuccesful for match" . $i . "\n";
}
}
}
$i++;
}//end of while loop results
mysqli_close($con);
?>
As you can see a match should be available as same string's $speaker and $event were pulled from table ted
So clearly there's something wrong with my syntax as for each query $a_bool is false resulting in echo "query unsuccessful for match" . $i . "\n" being called for each query . Any explanation of what I have done wrong would be greatly appreciated!
SET description=$line[5] should be in quotes
like
mysqli_query($con,"UPDATE ted SET description='{$line[5]}'
WHERE speaker='$speaker' AND event='$event'");