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) {
Related
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.
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;
?>
I am trying to add all the query values to an array.
here is my code:
$value = $_POST['hospitalname'];
$from = $_POST['from'];
$to = $_POST['to'];
if($_POST["Submit"]=="Submit") {
for ($i=0; $i<sizeof($value); $i++) {
$sql = "SELECT sl_id from mfb_servicelog where h_id LIKE ('".$value[$i]."')";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
$slid = $row["sl_id"];
for ($x=0; $x<sizeof($slid);$x++) {
echo $slid[$x];
}
}
}
}
If I print the result of $slid, it gives me this
1333853863873885215251126112711281129113023392488248924902491249224932494249524962497
These all are sl_id, and result of the query $sql. This is fine.
Now I want to put all these value into an array so that I can call this from a query like I am calling the $value in the above $sql query.
But my echo $slid($x) gives me this output, whic is the first digit of each value.
13333551111122222222222
Please suggest me the right way to do this.
Just store them in an array instead of a normal variable. Try with -
$slid[] = $row["sl_id"];
Update
if (!in_array($row["sl_id"], $slid)) {
$slid[] = $row["sl_id"];
}
And define $slid before the loop starts - $slid = array();
Or you can use array_unique()
For your code it should be -
$slid = array();
while ($row = mysql_fetch_assoc($result)) {
if (!in_array($row["sl_id"], $slid)) {
$slid[] = $row["sl_id"];
}
}
foreach($slid as $id) {
echo $id."<br>";
}
I have a function query:
function query() {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
} else {
//error
return array('error'=>'Database error');
}
}
The function works just fine when I use it like this:
$g = "05%";
$result = query("SELECT * FROM table_name WHERE table_column LIKE '%s'", $g);
print json_encode($result);
However I am getting no result when $g is a value retrieved from a method. For example lets say I have a method getMonth() from a class Date that returns the current month of May as 05% when echoed. I try the code below and get nothing from the database:
$time = new Date();
//$g = "05%"; this would definitely get results from the db
$h = $time->getMonth();
echo $h; //this displays 05% on the screen
$result = query("SELECT * FROM table_name WHERE table_column LIKE '%s'", $h);
print json_encode($result);
I am pretty sure that I am making a simple mistake, but I can't seem to figure it out. How can I fix this? Any help would be greatly appreciated.
Do something that your method return only 05 part from 05%. and append % after that for example
$h = $time->getMonth();
$h = "$h%";
and then it should work
I wanted the logic is if there is data in the database then query the data. Or else if there is no data then it will show an error message.
Here is my code:
$stmt = $db->prepare($query);
$stmt->execute(array('date' => $myFormat));
$data = $stmt->fetchAll();
if ( !$data ) {
echo 'No data found in database!';
} else {
return $data = $query;
}
Before this code, if the code that query from database:
//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";
}
I tried input a non data to execute the code but somehow it didn't show error and straight process to the scripting area.
The script below:
//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;
//add all initial data into the matrix variable for easier access to them later
$rows[0]
$rows = array(
array($r1),
array($r2),
array($r3),
array()
);
}
//incoporate modulo value as an argument.
function incmod($a, $m)
{
return ($a % $m) + 1;
}
//Population each row, with $populationCount number of elements, where each element is added with incmod(X, $mod)
function populateRow($rowId, $populationCount, $mod)
{
//function to access the global variable.
global $rows;
$row = $rows[$rowId];
while (sizeof($row) < $populationCount) {
$rowInd = sizeof($row) - 1;
$m = incmod($row[$rowInd], $mod);
array_push($row, $m);
}
//set the row back into the global variable.
$rows[$rowId] = $row;
}
$stmt = $db->prepare($query);
$stmt->execute(array('date' => $myFormat));
$data = $stmt->fetchAll();
if ( !$data ) {
echo 'No data found in database!';
}