Cannot insert to MySql database - post

I'm working with a gsm shield and try to post data to my server and then show it to website but have a problem when insert to the table. It's just Null (0). I try all the method that I found on the internet but still doesn't work. These are some code I tried
<?php
$server = "localhost";
$username = "id1342*****nhchuot";
$password = "*******";
$dbname = "id134****ta";
$conn = mysqli_connect($server, $username, $password, $dbname);
$Data = $_POST['data'];
$Received = $_POST['received'];
$query = "INSERT INTO DATA(data, received)
VALUES ('".$Data."','".$Received."')";
mysqli_query($conn, $query);
if (mysqli_query($conn, $query)) {
echo "New record created successfully";
} else {
echo "Error: " . $query . "<br>" . mysqli_error($conn);
mysqli_close($conn);?>
and database just 0 and 0

Related

Parsing Info to exe to clear the fields in Hashtag Tables

I'm trying to clear the Fields with values defined in Hash Tables by parsing it to the ipmiutil.exe utility. The script output shows it clear the fields but actually it is not when I manually check it. To clear the Fields values, each of those fields used different parameters as below. Can someone check my wipe code and help with the fix.
This is what I tried and expected the Field Values to clear when found but it is not clearing
Chassis Serial Number = .\ipmiutul.exe fru -G " "
Product Serial Number = .\ipmiutil.exe fru -s " "
Product Asset Tag = .\ipmiutil.exe fru -a " "
Powershell Code:
$fields_to_wipe = [ordered]#{
"Chassis Serial Num" = "fru -G";
"Product Serial Num" = "fru -s";
"Product Asset Tag" = "fru -a"
}
$input = $fru | Select-String -Pattern $fields_to_check | Tee-Object -FilePath "X:\output\fru_result.txt"
Write-Host "Checking FRU Fields for WIPE"
foreach($field in $input)
{
$field = "$field".Substring(0,"$field".IndexOf(":")).Trim()
if($value -eq "")
{
Write-Host $field "is BLANK. WIPE Not Needed."
Write-Host "`n"
}
else
{
if($fields_to_wipe.keys -contains $field)
{
Write-Host "$field Need WIPING"
Write-Host "WIPING $field"
Set-Location "Z:\Tools\Ipmi"
$cmd = .\ipmiutil.exe + {$fields_to_wipe}[$field] + " " + ('" "')
}
else
{
Write-Host $field_to_check ":" $value
}
}
}

PhpSpreadsheet Notice: Undefined offset: 4

I have been struggling with finding a way to read excel files in a directory, copy the worksheet called "Division" into a new file, then number the new worksheets increment by one - Division1, Division2, etc...
The following is my code, which I am receiving a warning for undefined index, which is not a big deal, but it only creates a new excel file with only four worksheets, when there should be over 240 worksheets.
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
use PhpOffice\PhpSpreadsheet\Helper\Sample;
use PhpOffice\PhpSpreadsheet\IOFactory;
$exportedFiles = scandir('PhpSpreadsheet/Export');
$inputFileNames = [];
$sheetnames = [];
$outfile = 'all-together-now.xlsx';
foreach($exportedFiles as $key=> $value) {
if ($value == '.' || $value == '..') {
} else {
array_push($inputFileNames, 'PhpSpreadsheet/Export/' . $value);
array_push($sheetnames, 'Division');
}
}
$inputFileType = 'Xlsx';
$reader = IOFactory::createReader($inputFileType);
$reader->setLoadSheetsOnly($sheetnames);
$contador = 1;
foreach ($inputFileNames as $book => $inputFileName) {
echo ('$inputFileName: ' . $inputFileName) . '</br>';
$reader = IOFactory::createReader("Xlsx");
$spreadsheet = $reader->load($inputFileName);
$clonedWorksheet = clone $spreadsheet->getSheetByName('Division');
$clonedWorksheet->setTitle('Division' . $contador);
$spreadsheetMain = $reader->load($outfile);
$spreadsheetMain->addSheet($clonedWorksheet);
$writer = IOFactory::createWriter($spreadsheetMain, "Xlsx");
$writer->save($outfile);
$contador++;
}
The following are the warning notices:
Notice: Undefined offset: 4 in
PhpOffice\PhpSpreadsheet\Writer\Xlsx->save( )
PhpOffice\PhpSpreadsheet\Spreadsheet->garbageCollect( )
As usual, thanks in advance
Part of the solution was bumping up the memory and the other was to use addSheet()
The following is the code that works:
ini_set('memory_limit','32768M');
use PhpOffice\PhpSpreadsheet\IOFactory;
require_once 'PhpSpreadsheet/src/Bootstrap.php';
$exportedFiles = scandir('PhpSpreadsheet/Export');
$inputFileNames = [];
$sheetnames = [];
$outfile = 'all-together-now.xlsx';
foreach($exportedFiles as $key=> $value) {
if ($value == '.' || $value == '..') {
} else {
array_push($inputFileNames, 'PhpSpreadsheet/Export/' . $value);
array_push($sheetnames, 'Division');
}
}
$inputFileType = 'Xlsx';
$reader = IOFactory::createReader($inputFileType);
$reader->setLoadSheetsOnly($sheetnames);
$contador = 1;
foreach ($inputFileNames as $book => $inputFileName) {
echo ('$inputFileName: ' . $inputFileName) . '</br>';
$reader = IOFactory::createReader("Xlsx");
$spreadsheet = $reader->load($inputFileName);
$spreadsheet->getSheetByName('Division')->getStyle('Division');
$clonedWorksheet = clone $spreadsheet->getSheetByName('Division');
$clonedWorksheet->setTitle('Division' . $contador);
/* open new file for writing spread sheets to it */
$spreadsheetMain = $reader->load($outfile);
$spreadsheetMain->addSheet($clonedWorksheet);
$writer = IOFactory::createWriter($spreadsheetMain, "Xlsx");
$writer->save($outfile);
$contador++;
}
$spreadsheet->disconnectWorksheets();
echo "The process has completed";
die();
The aforementioned script created an excel workbook with 247 worksheets from the 247 excel files

Combining Email code with if statement

I'm new to Powershell and am having trouble joining together two scripts I have.
What I want to do is check the length of all the csv files within a particular folder and if any of them are 0 Kb, I want to send off an alert email. So far I have a script which sends an email successfully and I have a script which checks the size successfully, but I am having trouble joining the two together.
Ideally it would send the name of the files which are empty in the body of the email.
The code below checks the file size and if it is greater than 1Kb it returns true.
$file = 'FilePath\File1.csv'
$Result = if (Test-Path $file) { (Get-Item $file).length -gt 1kb }
if ($Result -eq "True") {"File1.csv Contains Data"} ELSE {"File1.csv is Empty!"}
$file = 'FilePath\File2.csv'
$Result = if (Test-Path $file) { (Get-Item $file).length -gt 1kb }
if ($Result -eq "True") {"File2.csv Contains Data"} ELSE {"File2.csv is Empty!"}
$file = 'FilePath\File3.csv'
$Result = if (Test-Path $file) { (Get-Item $file).length -gt 1kb }
if ($Result -eq "True") {"File3.csv Contains Data"} ELSE {"File3.csv is Empty!"}
$file = 'FilePath\File4.csv'
$Result = if (Test-Path $file) { (Get-Item $file).length -gt 1kb }
if ($Result -eq "True") {"File4.csv Contains Data"} ELSE {"File4.csv is Empty!"}
$file = 'FilePath\FileName5.csv'
$Result = if (Test-Path $file) { (Get-Item $file).length -gt 1kb }
if ($Result -eq "True") {"File5.csv Contains Data"} ELSE {"File5.csv is Empty!"}
$file = 'FilePath\FileName6.csv'
$Result = if (Test-Path $file) { (Get-Item $file).length -gt 1kb }
if ($Result -eq "True") {"File6.csv Contains Data"} ELSE {"File6.csv is Empty!"}
Below is the email portion
$subject = "Emailtest"
$body = "test"
$emailTo = "jbloggs#Madeup.com"
$emailFrom ="JohnSmith#123.com"
$smtpServer = “mail.madeup.com”
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$credentials=new-object system.net.networkcredential(”username”,”password”)
$smtp.credentials=$credentials.getcredential($smtpserver,"25","basic")
$smtp.Send($emailFrom, $emailTo, $subject, $body)
Thank you for any help.
That's an awful lot of (manual) work just to check for empty files. What happens when you add a seventh - do you have to edit the script?
$EmptyFiles = (Get-childItem -Path $FilePath -Filter *.csv | `
where-object {$_.length -eq 0}|select-object -expandproperty Name)
$MsgBody = "The following files are empty:";
$EmptyFiles | foreach{$MsgBody+="`n$_";};
$MsgBody; # Just to output to console
$secpasswd = ConvertTo-SecureString "password" -AsPlainText -Force
$credentials= New-Object System.Management.Automation.PSCredential ("username", $secpasswd)
$subject = "Emailtest"
$body = "test"
$emailTo = "jbloggs#Madeup.com"
$emailFrom ="JohnSmith#123.com"
$smtpServer = “mail.madeup.com”
send-mailmessage -smtpserver $smtpServer -subject $subject -to $emailto -Credential $credentials -body $MsgBody

How to detect if the path of a url starts with a certain word

I'm trying to figure out how to get the page name from a facebook page and although I've figured out how to get it from the http://www.facebook.com/pagename version, I can't figure out how to test and get it from the longer version that looks like this http://www.facebook.com/pages/pagename/433425324544. How can I test to see if the path starts with /pages and how can I extract the pagename from it all using one function. Here's what I use to get the page name in the standard form.
function get_facebook_username( $facebook_url ) {
$url = $facebook_url;
$result = preg_match("/(https|http)?:\/\/(www\.)?facebook\.com\/?([^\/]*)/", $url, $matches);
$fb_username = 'default value';
if($result == 1){
$fb_username = $matches[3];
} else {
return;
}
echo "$fb_username";
}
I found a better way to do this I think except it cuts the last letter off the username if the url is in it's shortened version. For example.
//---short
$url = http://www.facebook.com/pagename
//---long
$url = http://www.facebook.com/pages/pagename/7532527927346
<?php
$url = $facebook_username;
$path = parse_url($url, PHP_URL_PATH);
$pathTrimmed = trim($path, 'pages/../0123456789');
echo $pathTrimmed;
?>
//---short
pagenam
//---long
pagename
Why is the short version missing the last letter?
The way I would go about this is to use explode to place the url into an array using the below code:
$url = "http://www.facebook.com/pages/pagename/7532527927346";
$result = explode("/", $url);
You get the following array:
array(6) {
[0]=>
string(5) "http:"
[1]=>
string(0) ""
[2]=>
string(16) "www.facebook.com"
[3]=>
string(5) "pages"
[4]=>
string(8) "pagename"
[5]=>
string(13) "7532527927346"
}
Then a simple if $result[3] == "pages" will allow you to check if the url contains pages.
Ninja Edit
In place of explode, you can also use the preg_split which will return no empty array elements:
$result = preg_split("~/~", $url, -1, PREG_SPLIT_NO_EMPTY);

jquery autocomplete remote source tried EVERYTHING !! but no good

i have been trying to implement jquery ui autocomplete feature.. and the basic html code is xactly the same as given on-
http://jqueryui.com/demos/autocomplete/#remote
I have tried all combinations/ code snippets for "search.php" such as-
1)
<?php
if ( !isset($_REQUEST['term']) )
exit;
// connect to the database server and select the appropriate database for use
$dblink = mysql_connect('localhost', 'root', '') or die( mysql_error() );
mysql_select_db('research');
$rs = mysql_query('select uname,email,password from login where uname like "'. mysql_real_escape_string($_REQUEST['term']) .'%" order by uname asc limit 0,10', $dblink);
// loop through each zipcode returned and format the response for jQuery
$data = array();
if ( $rs && mysql_num_rows($rs) )
{
while( $row = mysql_fetch_array($rs, MYSQL_ASSOC) )
{
$data[] = array(
'label' => $row['uname'] .', '. $row['password'] .' '.$row['uname'] ,
'value' => $row['uname']
);
}
}
// jQuery wants JSON data
echo json_encode($data);
flush();
?>
2)
<?php
include("includes/connect.php");
$query = "SELECT uname from login WHERE uname LIKE '%" . addslashes($_GET['term']) . "%'";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)) {
foreach($row as $val)
$tab[] = $val;
}
print json_encode($tab);
?>
3)
<?php
include("includes/connect.php");
$term = $_REQUEST['m']; // where name of the text field is 'm'
$query = "SELECT * FROM login WHERE uname LIKE '%$term%'";
$result = $mysqli->query($query);
$arr = array();
while($obj = $result->fetch_assoc()) {
$arr[] = $obj['nome'];
}
echo json_encode($arr);
?>
But still nothing is working !! that is when i type into the text box for autocomplete there are no results shown. what could be the error ? are there any alternative solutions ?? Please help !!!
The variable that you pass into json_encode must be an array of strings.
e.g. ["red","green","blue"]
or an array of object literals e.g. [{"value" : "red"},{"value" : "green"},{"value" : "blue"}]
Each time through the loop you need to append the item to the existing items.
I notice, in all 3 code snippets, that you assign the current item to your array variable, instead of appending it. When the loop completes, the only item in your array will be the item processed most recently by the loop.
So unless what you type in the field matches that one item, the autocomplete isn't going to show anything.
Here is my PHP code to build an array of strings before sending it back to the file that made the request.
$fetchedArtists = $db->query($queryToGetArtists );
$json = '[';
$first = true;
while($row = $fetchedArtists->fetch_assoc())
{
if (!$first)
{
$json .= ',';
}
else
{
$first = false;
}
$artist = $row['artistName'];
$json .= '{"value":"'.$artist.'"}';
}
$json .= ']';
echo $json;

Resources