connect to FTP using array values - php

I am new to php and struggling to get the data from a table in mysql and using it to connect to an ftp server. The table contains the external ip address of the ftp server, the base directory to change into and login credentials to use. I fetched the data from mysql and stored it in an array but while looping through it I get
php notice: trying to access array offset on type null.
Code:
$now = time();
$yesterday = $now - (24 * 60 * 60);
$date = date("Y-m-d", $yesterday);
if (isset($_GET['date'])) {
$date = $_GET['date'];
}
$startDate = "$date 00:00:00";
$endDate = "$date 23:59:59";
//$conn = &newEtConn();
$sql= "SELECT stager_usr, stager_pwd, stager_ip, basedir, view_direction from et_devices.cameras as a inner join et_params.stagers as b on a.stagerid = b.idstagers ";
$result = mysqli_query($conn,$sql);
$datas = array();
if (!$result) {
die ("table Connection problem");
}
if (mysqli_num_rows($result)>0){
while ($row = mysqli_fetch_assoc($result)){
$datas[] = $row;
}
print_r($datas);
}
if ($row!= "") {
foreach ($datas as $values) {
$ip_addr = $values['stager_ip'];
$login = $values['stager_usr'];
$password = $values['stager_pwd'];
$basedir = $values['basedir'];
if ($rows != "") {
$gotFtpConn = True;
$ftp_obj = ftp_connect($ip_addr, 21, 10) or $gotFtpConn = False;
if ($gotFtpConn) {
if (ftp_login($ftp_obj, $login, $passwd)) {
echo "could not connect" . $login;
return false;
}
return $newEtConn;
}
}
}

There are a few things that I don't like (and can improve)...
It looks like you intend to filter your database data based on a date, but then you never actually apply that value to the array. I'll help to clean up that process.
Your if ($row != '') check after the loop will always fail because the loop ONLY stops when $row becomes falsey.
The rest of your code looks like it only intends to process a single row in the result set (because it returns). I am going to assume that you have more conditional logic in your query's WHERE clause which ensures that only one row is returned -- otherwise, you shouldn't be using return in your loop.
$date = !empty($_GET['date']) && preg_match('/^\d{4}-\d{2}-\d{2}$/', $_GET['date'])
? $_GET['date']
: date('Y-m-d', strtotime('yesterday'));
$sql = "SELECT stager_usr, stager_pwd, stager_ip
FROM et_devices.cameras AS a
JOIN et_params.stagers AS b ON a.stagerid = b.idstagers
WHERE DATE(a.some_datetime_column) = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $date);
$stmt->execute();
foreach ($stmt->get_result() as $row) {
$ftp = ftp_connect($row['stager_ip'], 21, 10);
if (!$ftp) {
throw new Exception('Failed to establish FTP connection');
}
if (!ftp_login($ftp, $row['stager_usr'], $row['stager_pwd'])) {
throw new Exception('Incorrect FTP login credentials');
}
return $ftp;
}
throw new Exception('FTP connection data not found');
If you experience a noticeable performance bottleneck with DATE() in your sql, then there are other techniques that may be faster, but they use longer/uglier syntax.

Related

all retrieve data from ms accesss database in php

Data retrieve from the ms access database 2007 in php using odbc driver. ALL data retrieve using query but its get only one record retrieve other data is not retrieve.
below query three records but its retrieved only one data. which problem below code in php?how get all data using query from this code what's changes it?
<?PHP
include 'Connection2.php';
$sql = "select FYearID,Description,FromDate,ToDate from mstFinancialyear";
$stmt = odbc_exec($conn, $sql);
//print_r($stmt);
$rs = odbc_exec($conn, "SELECT Count(*) AS counter from mstFinancialyear");
//print_r($stmt);
$arr = odbc_fetch_array($rs);
$arr1 = $arr['counter'];
$result = array();
//print_r($arr);
if (!empty($stmt)) {
// check for empty result
if ($arr1 > 0) {
// print_r($stmt);
$stmt1 = odbc_fetch_array($stmt);
$year = array();
$year['FYearID'] = $stmt1['FYearID'];
$year['Description'] = $stmt1['Description'];
$year['FromDate'] = $stmt1['FromDate'];
$year['ToDate'] = $stmt1['ToDate'];
// success
$result["success"] = 1;
// user node
$result["year"] = array();
array_push($result["year"], $year);
echo json_encode($result);
//return true;
} else {
// no product found
$result["success"] = 0;
$result["message"] = "No product found";
echo json_encode($result);
}
odbc_close($conn); //Close the connnection first
}
?>
You return only a single record in the JSON data because you do not iterate through the recordset. Initially I misread that you had called odbc_fetch_array twice on the same recordset but upon closer inspection see that one query is imply used, as far as I can tell, to see if there are any records likely to be returned from the main query. The re-written code below has not been tested - I have no means to do so - and has a single query only but does attempt to iterate through the loop.
I included the count as a sub-query in the main query if for some reason the number of records was required somehow - I don't think that it is however.
<?php
include 'Connection2.php';
$result=array();
$sql = "select
( select count(*) from `mstFinancialyear` ) as `counter`,
`FYearID`,
`Description`,
`FromDate`,
`ToDate`
from
`mstFinancialyear`";
$stmt = odbc_exec( $conn, $sql );
$rows = odbc_num_rows( $conn );
/* odbc_num_rows() after a SELECT will return -1 with many drivers!! */
/* assume success as `odbc_num_rows` cannot be relied upon */
if( !empty( $stmt ) ) {
$result["success"] = $rows > 0 ? 1 : 0;
$result["year"] = array();
/* loop through the recordset, add new record to `$result` for each row/year */
while( $row=odbc_fetch_array( $stmt ) ){
$year = array();
$year['FYearID'] = $row['FYearID'];
$year['Description'] = $row['Description'];
$year['FromDate'] = $row['FromDate'];
$year['ToDate'] = $row['ToDate'];
$result["year"][] = $year;
}
odbc_close( $conn );
}
$json=json_encode( $result );
echo $json;
?>

Insert date check into function

I have this function that loads an array from a table called 'customer' it works fine, but I also want it to check if the customer has expired and if so display an error
So I have code below that to check if the id_expiry_date is over, but I'm having difficulty working out where to put it in the function. Tried a few things, but just seems to break. Please assist.
function customer_load_by_id($id)
{
$dbh = dbh_get();
$id = array();
$sql = 'select c.* ' .
'from customer c ' .
'where c.cust_id = (select max(cust_id) from customer where id = ?)';
$stmt = $dbh->prepare($sql);
$stmt->execute(array($id));
$r = $stmt->fetch();
if (!is_bool($r)) {
$fields = id_get_fields();
foreach ($fields as $field) {
$n = $field['name'];
$id[$n] = $r[$n];
}
}
dbh_free($dbh);
$exp_date = "$id_expiry_date";
$todays_date = date("Y-m-d");
$today = strtotime($todays_date);
$expiration_date = strtotime($exp_date);
if ($expiration_date > $today) {
//continue happily
} else
{
//don't continue
}
return $id;
}
// One of the fields in the array above is id_expiry_date
I do not really get how you SQL schema is but, using Pomm, I would write the following code:
<?php
use PommProject\Foundation\Pomm;
$loader = require __DIR__ . '/vendor/autoload.php'; //<- setup autoloading
$pomm = new Pomm(…); // <- connection params go there
$sql = <<<"SQL"
select
c.*,
c.expiry_date < now() as is_expired
from customer c
where c.cust_id = (select max(cust_id) from customer where id = $*)
SQL;
$result = $pomm
->getDefaultSession()
->getQueryManager()
->query($sql, [$id])
->current() // <- Take the first row if exist
;
if ($result) {
if ($result['is_expired']) { //<- 'is_expired' is converted as boolean
echo "expired";
} else {
echo "not expired";
}
} else {
echo "no result";
}

Show numbers and names of connected users

I used to code in the old way in php and been introduced through this forum to POO.
I'm rewriting a script that was in mysql into PDO. This script is to show the numbers and the names of connected members on a website. So far it only displays the number but not yet the list of names of connected members
that the script updated:
<?php
session_start();
if(isset($_SESSION['nom'])){
include('class.connect.php');
include('class.user.php');
$db = new DBEngine();
//verify if the name is already in the table
$log = $db->con->prepare('SELECT COUNT(nom) AS name FROM members_connected WHERE nom=?');
$log->execute(array($_SESSION['nom']));
$count = $log->fetchColumn(0);
$time = time();
if ($count == 0)
{
// the user is not in the new table, i add him
$log = $db->con->prepare('INSERT INTO members_connected (nom,timestamp) VALUES(?,?)');
$log->execute(array($_SESSION['nom'],$time));
}
//name already in the table, update the timestamp
else
{
$log = $db->con->prepare('UPDATE members_connected SET timestamp=? WHERE nom=?');
$log->execute(array($_SESSION['name'],$time));
}
//5 min earlier's timestamp
$timestamp_5min = time() - (60 * 5);
$log = $db->con->prepare('DELETE FROM members_connected WHERE timestamp < ?');
$log-> execute(array($timestamp_5min));
$log = $db->con->prepare('SELECT nom FROM members_connected');
$log->execute();
$row = $log->fetch(PDO::FETCH_ASSOC);
echo $count ;
//show the list of connected
if($count > 0)
{
$i=0;
while($count = $log->fetch(PDO::FETCH_ASSOC));
{
$i++;
echo $count['nom'];
if($i<$row)
{
//space between names
echo ',';
}
}
}
}
?>
`
Any thoughts please ?
try adding the following after your second include;
$db = new DBEngine();
Then in the code where you have
$this->db->con->prepare(...
change that to
$db->con->prepare(...
UPDATE
In answer to your second error, it looks like you need to set the variable types in your bindings.
e.g.
$log->bindParam(1, $_SESSION['name'], PDO::PARAM_STR, 25);
$log->bindParam(2, time(), PDO::PARAM_STR, 20);
Alternatively, you don't need to bind variables like that and you could pass them directly into the execute like so (which is what you have in your first query btw)
$log->execute(array($_SESSION['name'], time()));
Create a TimeStamp class that will fetch and update your database like so:
class TimeStamp
{
protected $db;
public $row_count;
public function __construct($db)
{
$this->db = $db;
}
// This should grab all users connected
public function Fetch($_user, $interval = '1')
{
// This is just checking a time range and collecting names
// You may want to make a new function that will then take the return list and query your user info table to get the user info
$connected = $this->db->con->prepare("select * FROM members_connected WHERE timestamp > DATE_SUB(NOW(), INTERVAL $interval MINUTE)");
$connected->execute(array($_user));
if($connected->rowCount() > 0) {
while($result = $connected->fetch(PDO::FETCH_ASSOC)) {
$users[] = $result;
}
}
// This should get the count
$this->row_count = (isset($users))? count($users):0;
// Return if users are available
return (isset($users))? $users:0;
}
public function Record($_user)
{
$connected = $this->db->con->prepare("INSERT INTO members_connected (nom, timestamp) VALUES (:nom,NOW()) ON DUPLICATE KEY UPDATE timestamp = NOW()");
$connected->bindParam(':nom', $_user);
$connected->execute();
}
}
include('class.connect.php');
include('class.user.php');
$db = new DBEngine();
if(isset($_SESSION['nom'])) {
// Start the timestamp, feed database
$u_check = new TimeStamp($db);
// Record into db
$u_check->Record($_SESSION['nom']);
// Check db, print users
$users = $u_check->Fetch($_SESSION['nom']);
print_r($users);
// Display count
echo "USERS: ".$u_check->row_count;
}

$data is not returning result

I need the $data to return from the database if the data was found from the database, but unfortunately, my code is not working to return the data.
I tried to enter non-exist data, it managed to return the error message but if the data exist, the page displays nothing.
May I know where did I go wrong in my if statement?
Below is my code that contain after the $data return the script will execute.
$day = $_POST['day'];
$month = $_POST['month'];
$year = $_POST['year'];
$dob = implode('/', array($day,$month,$year));
if(isset($_POST['submit'])){
if(empty($_POST['day']) || empty($_POST['month']) || empty($_POST['year'])){
echo "You need to fill in each field.<br /><br />Click here to <b>fill in each field</b> again";
exit;
}
}
//Date that user keyin
$userDate = $dob;
$dateTime = DateTime::createFromFormat('d/m/Y', $userDate);
$myFormat = $dateTime->format('Y-m-d');
//Query string and put it in a variable.
if(isset($_POST['dob_chi'])){
$query = "SELECT * FROM $table_n WHERE dob_chi = :date";
} else {
$query = "SELECT * FROM $table_n WHERE dob_eng = :date";
}
$stmt = $db->prepare($query);
$stmt->execute(array('date' => $myFormat));
$data = $stmt->fetchAll();
if ( !$data ) {
echo 'No data found in database!';
exit;
} else {
return $data=$userDate;
}
//Now we create a while loop for every entry in our DB where the date is match.
while ($row = $stmt->fetchObject()) {
$r1 = $row->rowone;
$r2 = $row->rowtwo;
$r3 = $row->rowthree;
$englishdate = $row->dob_eng;
$chinesedate = $row->dob_chi;
$zodiac = $row->zodiac;
//add all initial data into a matrix variable for easier access to them later
//To access rowone use $rows[0][0], rowtwo $rows[1][0] ect.
//The matrix is an array which contains multiple array. eg. 2-dimensional arrays
//To get all the variables with $r1X simply retrieve the first array of the matrix eg $rows[0]
$rows = array(array($r1),array($r2),array($r3),array());
}
//Similarities between row1 and row2 made me incorporate modulo value as an argument.
function incmod($a, $m){
return ($a % $m) + 1;
}
Thank you for your time
Get rid of the line:
return $data=$userDate;
because it's ending your script and also overwriting the $data variable.
Change:
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
Then change the line:
while ($row = $stmt->fetchObject()) {
to:
foreach ($data as $row) {

Checking for an empty result (PHP, PDO, and MySQL) [duplicate]

This question already has an answer here:
How to check fetched result set is empty or not?
(1 answer)
Closed 11 months ago.
What am I doing wrong here? I'm simply retrieving results from a table and then adding them to an array. Everything works as expected until I check for an empty result...
This gets the match, adds it to my array and echoes the result as expected:
$today = date('Y-m-d', strtotime('now'));
$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");
$sth->bindParam(':today', $today, PDO::PARAM_STR);
if(!$sth->execute()) {
$db = null;
exit();
}
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$this->id_email[] = $row['id_email'];
echo $row['id_email'];
}
$db = null;
return true;
When I try to check for an empty result, my code returns 'empty', but no longer yields the matching result:
$today = date('Y-m-d', strtotime('now'));
$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");
$sth->bindParam(':today',$today, PDO::PARAM_STR);
if(!$sth->execute()) {
$db = null;
exit();
}
if ($sth->fetchColumn()) {
echo 'not empty';
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$this->id_email[] = $row['id_email'];
echo $row['id_email'];
}
$db = null;
return true;
}
echo 'empty';
$db = null;
return false;
You're throwing away a result row when you do $sth->fetchColumn(). That's not how you check if there are any results. You do
if ($sth->rowCount() > 0) {
... got results ...
} else {
echo 'nothing';
}
Relevant documentation is here: PDOStatement::rowCount
If you have the option of using fetchAll() then, if there are no rows returned, it will just be an empty array.
count($sql->fetchAll(PDO::FETCH_ASSOC))
will return the number of rows returned.
You should not use rowCount for SELECT statements as it is not portable. I use the isset function to test if a select statement worked:
$today = date('Y-m-d', strtotime('now'));
$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");
// I would usually put this all in a try/catch block, but I kept it the same for continuity
if(!$sth->execute(array(':today'=>$today)))
{
$db = null;
exit();
}
$result = $sth->fetch(PDO::FETCH_OBJ)
if(!isset($result->id_email))
{
echo "empty";
}
else
{
echo "not empty, value is $result->id_email";
}
$db = null;
Of course this is only for a single result, as you might have when looping over a dataset.
I thought I would weigh in as I had to deal with this lately.
$sql = $dbh->prepare("SELECT * from member WHERE member_email = '$username' AND member_password = '$password'");
$sql->execute();
$fetch = $sql->fetch(PDO::FETCH_ASSOC);
// if not empty result
if (is_array($fetch)) {
$_SESSION["userMember"] = $fetch["username"];
$_SESSION["password"] = $fetch["password"];
echo 'yes this member is registered';
}else {
echo 'empty result!';
}
what I'm doing wrong here?
Almost everything.
$today = date('Y-m-d'); // no need for strtotime
$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");
$sth->bindParam(':today',$today); // no need for PDO::PARAM_STR
$sth->execute(); // no need for if
$this->id_email = $sth->fetchAll(PDO::FETCH_COLUMN); // no need for while
return count($this->id_email); // no need for the everything else
Effectively, you always have your fetched data (in this case in $this->id_email variable) to tell whether your query returned anything or not. Read more in my article on PDO.
One more approach to consider:
When I build an HTML table or other database-dependent content (usually via an AJAX call), I like to check if the SELECT query returned any data before working on any markup. If there is no data, I simply return "No data found..." or something to that effect. If there is data, then go forward, build the headers and loop through the content, etc. Even though I will likely limit my database to MySQL, I prefer to write portable code, so rowCount() is out. Instead, check the the column count. A query that returns no rows also returns no columns.
$stmt->execute();
$cols = $stmt->columnCount(); // no columns == no result set
if ($cols > 0) {
// non-repetitive markup code here
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
I only found one way that worked...
$quote = $pdomodel->executeQuery("SELECT * FROM MyTable");
//if (!is_array($quote)) { didn't work
//if (!isset($quote)) { didn't work
if (count($quote) == 0) { //yep the count worked.
echo 'Record does not exist.';
die;
}
Thanks to Marc B's help, here's what worked for me (note: Marc's rowCount() suggestion could work too, but I wasn't comfortable with the possibility of it not working on a different database or if something changed in mine... also, his select count(*) suggestion would work too, but, I figured because I'd end up getting the data if it existed anyway, so I went this way).
$today = date('Y-m-d', strtotime('now'));
$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");
$sth->bindParam(':today', $today, PDO::PARAM_STR);
if(!$sth->execute()) {
$db = null;
exit();
}
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$this->id_email[] = $row['id_email'];
echo $row['id_email'];
}
$db = null;
if (count($this->id_email) > 0) {
echo 'not empty';
return true;
}
echo 'empty';
return false;

Categories