Format Date in PHP m/d/y to Y-m-d? - php

I am trying to format a date string i rip from the web the date comes in as m/d/y and I need to insert it into MYSQL currently I get an error PHP Fatal error: Call to a member function format() on a non-object
Code:
<?php
include 'ganon.php';
$id = array(8573, 53816, 7746, 80748, 7714);
for($l=0; $l<sizeof($id); $l++) {
$html = file_get_dom("http://pregame.com/pregamepros/pro-bettor/picks.aspx?id=" . $id[$l]);
$picks = $html('div[class="div-table-col"]');
$array = array();
$j =0;
for($i=0; $i<sizeof($picks); $i+=8) {
$array[$j] = array("date" => trim($picks[$i]->getPlainText()),
"sport" => trim($picks[$i+1]->getPlainText()),
"pick" => trim($picks[$i+2]->getPlainText()),
"score" => trim($picks[$i+3]->getPlainText()),
"odds" => trim($picks[$i+4]->getPlainText()),
"size" => preg_replace('/\$/', "", $picks[$i+5]->getPlainText()),
"winloss" => trim($picks[$i+6]->getPlainText()),
"money" => (int)preg_replace('/\$/', "", $picks[$i+7]->getPlainText()));
$j++;
}
//enter picks into database
//make sure we do not add picks we already have
$mysqli = new mysqli("host", "user", "pass", "db");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
exit();
}
if($id[$l] == 8573) {
//$query = "SELECT `date` FROM `db`.`vegasrunner` where date=" . date('Y-m-d');
for($i=0; $i<sizeof($array); $i++) {
$query = "SELECT `date`,`pick` FROM `db`.`vegasrunner` where date=" . "'" . $array[$i]["date"] . "'" . " AND pick=" . "'" . $array[$i]["pick"] . "'";
$result = $mysqli->query($query);
$row = $result->fetch_row();
if(sizeof($row) < 1) {
$result->close();
$date = new DateTime();
$date = DateTime::createFromFormat('m/d/y', $array[$i]["date"]);
//$date = $array[$i]["date"];
$sport = $array[$i]["sport"];
$pick = $array[$i]["pick"];
$score = $array[$i]["score"];
$odds = $array[$i]["odds"];
$size = $array[$i]["size"];
$winloss = $array[$i]["winloss"];
$money = $array[$i]["money"];
echo $date->format('Y-m-d');
$query = "INSERT INTO `db`.`vegasrunner` (`date`, `sport`, `pick`, `score`, `odds`, `size`, `winloss`, `money`) VALUES (" . "'" . $date->format('Y-m-d') . "'" . ", '$sport', '$pick', '$score', '$odds', '$size', '$winloss', '$money')";
$mysqli->query($query);
}
} }

The only plausible explanation I can see is if createFromFormat() is failing, which might happen if the input date isn't in the format you're expecting.
Check that the input string is in the format you think, and alter your code to include a check for failure at the createFromFormat() call.

I ended up writing my own function to parse the date. It turns out there was a hidden space before the month.
function formatDate($date) {
//date = 07/12/13
$date = explode('/', $date);
//for some reason in ubuntu month had a space had to get last 2 characters
$month = substr($date[0], -2);
$day = trim($date[1]);
$year = date('y') == $date[2] ? date('Y') : date('Y');
return $year . "-" . $month . "-" . $day;
}

Related

Validating Date of birth using data from API call

I'm adding date of birth validation to my Twilio flow. Format is mm/dd/yyyy. So user would input 01021999 for Date of Birth: 01-02-1999.
I pass the input as a parameter to my validation script (PHP) on my VPS via and http request.
The problem is that if I manually set the $dob variable in my script it works, but if I pull that info from twilio there's an issue and the http request sends an error.
I know php treats numbers leading with zeros different and you have to pass them as strings. Tried using strval() to the dob variable to be able to use the input but haven't had any luck.
Works:
$account_number = 1234;
$dob = "01021999";
$dob_length = strlen($dob);
if ($dob_length = 8) {
echo $dob_month = substr($dob, 0, 2);
echo $dob_day = substr($dob, 2,2);
echo $dob_year = substr($dob, 4, 4);
echo $dob_full = $dob_month . "-" . $dob_day . "-" . $dob_year;
$sql1 = "SELECT * FROM accounts WHERE Acct_Nbr = '".$account_number."' AND Guar_DOB LIKE '%".$dob_full."%' ";
$rows = getRows($sql1);
Doesn't work (with or without turning the $dob to a string using strval() :
require_once('logs.php');
require_once('db.php');
require_once('rest.php');
$data = $_REQUEST;
start_log();
$filename = basename(__FILE__);
echo "<pre>".print_r($data,true)."</pre>";
end_log();
header("Content-Type: application/json; charset=UTF-8");
$rfields = explode(",","client_id,account_number,dob");
foreach($rfields as $rf){
if(!isset($data[$rf])){
$message = $rf." is required.";
$status = "error";
echo json_encode(compact('status','message')); die();
}
}
extract($data);
$dob_str = strval($dob);
$dob_length = strlen($dob_string);
if ($dob_length = 8) {
echo $dob_month = substr($dob_str, 0, 2);
echo $dob_day = substr($dob_str, 2,2);
echo $dob_year = substr($dob_str, 4, 4);
echo $dob_full = $dob_month . "-" . $dob_day . "-" . $dob_year;
$sql1 = "SELECT * FROM accounts WHERE Acct_Nbr = '".$account_number."' AND Guar_DOB LIKE '%".$dob_full."%' ";
$rows = getRows($sql1);
}
Try this
$dob = '01021999';
$account_number = 'whatever';
if (validateDate((string)$dob, 'dmY')) {
$date = DateTime::createFromFormat('dmY', $dob);
$final_date = $date->format('Y-m-d');
$sql1 = "SELECT * FROM accounts WHERE Acct_Nbr = '" . $account_number . "' AND Guar_DOB LIKE '%" . $final_date . "%' ";
$rows = getRows($sql1);
}
function validateDate($date, $format = 'Y-m-d H:i:s')
{
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) == $date;
}

Appointment Booking System Slots

Im trying to make an appointment booking system, in which everything else works, EXCEPT the appointment time slots, in which if, for example, an appointment is set at 11.30am, and lasts an hour (12.30pm), no one can book or have an appointment within these times.
I have converted start and end times of the input to unix time, as well as converting the times already set in the database, but it is failing me.
I have tried comparing the end time in between the two times set by the user, and the end time of the user between the two times already in the database.
My code is:
if ($length == "1 Hour"){
$edittime = $time;
$timeedit = strtotime($edittime)+3600;
$endtime = date('h:i:s', strftime($timeedit));
} elseif ($length == "1 Hour 30 Minutes") {
$edittime = $time;
$timeedit = strtotime($edittime)+5400;
$endtime = date('h:i:s', strftime($timeedit));
} elseif ($length == "2 Hour") {
$edittime = $time;
$timeedit = strtotime($edittime)+7200;
$endtime = date('h:i:s', strftime($timeedit));
} else {
header("location:Cancel.php");
}
/*Comparison of the start and end times, as well as the user input time.*/
$querysql = "SELECT Time FROM $tablename WHERE Time <= '$endtime' AND Date = '$date'";
$queryresult = mysqli_query($connection, $querysql);
/*Validate the query.*/
if (! $queryresult) {
echo ("Could not retrieve the sql data : " . mysqli_error($connection) . " " . mysqli_errno($connection));
}
/*Array to collect data from the sql query, to compare against the appointment times the user entered.*/
$count = 0;
$starttime = $time;
$secondtime = strtotime($starttime);
$existapp[$count] = mysqli_fetch_array($queryresult, MYSQLI_NUM);
while ($existapp[$count] <> "") {
$temp = $existapp[$count];
$acquireddata = $temp[$count];
$appsec = strtotime($acquireddata);
if ($length == "1 Hour") {
$existstart = $appsec;
$existedit = $existstart + 3600;
$existend = date('h:i:s', strftime($existedit));
} elseif ($length == "1 Hour 30 Minutes") {
$existstart = $appsec;
$existedit = $existstart + 3600;
$existend = date('h:i:s', strftime($existedit));
} elseif ($length == "2 Hour") {
$existstart = $appsec;
$existedit = $existstart + 3600;
$existend = date('h:i:s', strftime($existedit));
}
/*$timeedit = end time*/
/*$secondtime = start time*/
/*$existededit = exisiting appointment*/
if ($timeedit <= $existedit and $timeedit >= $existstart) {
header("location:Cancel.php");
}
$count = $count + 1;
}
If you need the whole file then just give me a shout.
I've been searching to no end with this, and after checking the unix times, it should work! But it doesnt! ):
<?php
/*Checks if user is logged in, else redirect to home.*/
session_start();
if(! $_SESSION['Username']) {
header("location:Index.php");
}
/*Sets variables as the login to the database, as well as tables of interest.*/
$servername = "";
$username = "";
$password = "";
$dbname = "";
$tablename = "appointmentinformation";
$tablenamed = "clientinformation";
/*Connect to the database server and the database.*/
$connection = mysqli_connect("$servername", "$username", "$password", "$dbname") or die("Could not connect to the database");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
/*Retrieve the username from the current session.*/
$clientusername = $_SESSION['Username'];
/*Retrieve the ClientID of interest from a table, with a parameter of the username. Limit the amount of results to one row (one result).*/
$sql = "SELECT ClientID FROM $tablenamed WHERE Username = '$clientusername' LIMIT 1";
/*Validate the query.*/
$results = mysqli_query($connection, $sql);
if (! $results) {
echo ("Could not select the data : " . mysql_error());
} else {
$datarows = mysqli_fetch_row($results);
$clientid = $datarows[0];
}
/*Retrieve user input.*/
$date = $_POST["date"];
$time = $_POST["time"];
$length = $_POST["length"];
/*Format date*/
$date = str_replace('/', '-', $date);
/*Protection from SQL injection attacks.*/
$date = stripslashes($date);
$time = stripslashes($time);
$length = stripslashes($length);
$date = mysqli_real_escape_string($connection, $date);
$time = mysqli_real_escape_string($connection, $time);
$length = mysqli_real_escape_string($connection, $length);
if ($length == "1 Hour"){
$edittime = $time;
$timeedit = strtotime($edittime)+3600;
} elseif ($length == "1 Hour 30 Minutes") {
$edittime = $time;
$timeedit = strtotime($edittime)+5400;
} elseif ($length == "2 Hour") {
$edittime = $time;
$timeedit = strtotime($edittime)+7200;
} else {
header("location:Cancel.php");
}
/*Comparison of the start and end times, as well as the user input time.*/
$querysql = "SELECT Time FROM $tablename WHERE Time <= '$endtime' AND Date = '$date'";
$queryresult = mysqli_query($connection, $querysql);
/*Validate the query.*/
if (! $queryresult) {
echo ("Could not retrieve the sql data : " . mysqli_error($connection) . " " . mysqli_errno($connection));
}
/*Array to collect data from the sql query, to compare against the appointment times the user entered.*/
$count = 0;
$starttime = $time;
$secondtime = strtotime($starttime);
$existapp[$count] = mysqli_fetch_array($queryresult, MYSQLI_NUM);
while ($existapp[$count] <> "") {
$temp = $existapp[$count];
$acquireddata = $temp[$count];
$appsec = strtotime($acquireddata);
if ($length == "1 Hour") {
$existstart = $appsec;
$existedit = $existstart + 3600;
} elseif ($length == "1 Hour 30 Minutes") {
$existstart = $appsec;
$existedit = $existstart + 3600;
} elseif ($length == "2 Hour") {
$existstart = $appsec;
$existedit = $existstart + 3600;
}
/*$timeedit = end time*/
/*$secondtime = start time*/
/*$existededit = exisiting appointment*/
if ($timeedit <= $existedit and $timeedit >= $existstart) {
header("location:Cancel.php");
}
$count = $count + 1;
}
/*SELECT query to retrieve data from the database. A complex query due to two parameters.*/
$sqlquery = "SELECT * FROM $tablename WHERE Date = '$date' AND Time = '$time'";
$sqlresult = mysqli_query($connection, $sqlquery);
/*Validate the query.*/
if (! $sqlresult) {
echo ("Could not retrieve the sql data : " . mysqli_error($connection) . " " . mysqli_errno($connection));
}
$rows = mysqli_fetch_row($sqlresult);
$date1 = $rows[3];
$time1 = $rows[4];
/*Compare the date and times and validate.*/
if ($date === $date1 && $time = $time1) {
echo("This date/time is taken!");
header("location:CreateAppointmentForm.php");
} else {
/*Insert the data into the database if validation passes.*/
$query = "INSERT INTO appointmentinformation (ClientID, Length, Date, Time) VALUES ('$clientid', '$length', '$date', '$time')";
$result = mysqli_query($connection, $query);
if ($result) {
header("Location:UserCP.php");
} else {
echo ("Could not insert data : " . mysqli_error($connection) . " " . mysqli_errno($connection));
}
}
?>
You should change strftime to strtotime
http://php.net/manual/en/function.strftime.php
http://php.net/manual/en/function.strtotime.php
strftime first parameter is string format, second timestamp http://php.net/manual/en/function.strftime.php but you give timestamp as first parameter: for example calculated here $timeedit = strtotime($edittime)

Conditional Operators not performing as expected

I'm currently trying to compare two sets of returned values from user selects, but when I go to compare the data from the results, the elseif statement defaults, despite the information being clearly the opposite. It doesn't matter what the values are, the program always refers to the elseif. Any help would be very much appreciated. Thank you!
// DB Constant Defines
define('DB_NAME','NurseData');
define('DB_USER','root');
define('DB_PASSWORD','root');
define('DB_HOST','localhost');
$state1 = $_REQUEST['state1'];
$state2 = $_REQUEST['state2'];
$city1 = $_REQUEST['city1'];
$city2 = $_REQUEST['city2'];
$jobTitle1 = $_REQUEST['job1'];
$jobTitle2 = $_REQUEST['job2'];
function showerror() {
die("Error " . mysql_errno() . " : " . mysql_error());
}
$connection = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die(mysql_error());
mysql_select_db(DB_NAME, $connection) or die(mysql_error());
$query1 = "SELECT DISTINCT
TOT_EMP,
JOBS_1000,
A_MEAN,
A_PCT90
FROM Nurse_Local
WHERE PRIM_STATE='" . $state1 . "'
AND AREA_NAME='" . $city1 . "'
AND OCC_TITLE='" . $jobTitle1 . "'";
$query2 = "SELECT DISTINCT
TOT_EMP,
JOBS_1000,
A_MEAN,
A_PCT90
FROM Nurse_Local
WHERE PRIM_STATE='" . $state2 . "'
AND AREA_NAME='" . $city2 . "'
AND OCC_TITLE='" . $jobTitle2 . "'";
if (!($getPosts1 = mysql_query ($query1, $connection))) {
showerror();
}
if (!($getPosts2 = mysql_query ($query2, $connection))) {
showerror();
}
while($rows1 = mysql_fetch_array($getPosts1)) {
while($rows2 = mysql_fetch_array($getPosts2)) {
//Retrieve array values
for ($i1 = 0; $i1 < count($rows1); $i1++) {
for ($i2 = 0; $i2 < count($rows2); $i2++) {
//Assign array values
$tot_EMP1 = $rows1['TOT_EMP'];
$tot_EMP2 = $rows2['TOT_EMP'];
$jobs_PER1 = $rows1['JOBS_1000'];
$jobs_PER2 = $rows2['JOBS_1000'];
$a_MEAN1 = $rows1['A_MEAN'];
$a_MEAN2 = $rows2['A_MEAN'];
$A_PCT901 = $rows1['A_PCT90'];
$A_PCT902 = $rows2['A_PCT90'];
//Convert array values to numbers
$tot_EMP1 = 0 + $tot_EMP1;
$tot_EMP2 = 0 + $tot_EMP2;
//Functions for calculating differences
/*
function compareEMP1($diffEMP1) {
$diffEMP1 = $rows1['TOT_EMP'] - $rows2['TOT_EMP'];
return $diffEMP1;
}
function compareEMP2() {
$diffEMP2 = $rows2['TOT_EMP'] - $rows1['TOT_EMP'];
return $diffEMP2;
}
*/
}
}
if($tot_EMP1 > $tot_EMP2 || $tot_EMP2 < $tot_EMP1) {
echo $tot_EMP1;//"In " . $state1 . " there are " . compareEMP1() . " more jobs than in " . $state2;
}
elseif ($tot_EMP2 > $tot_EMP1 || $tot_EMP1 < $tot_EMP2) {
echo $tot_EMP2;//"In " . $state2 . " there are " . compareEMP2() . " more jobs than in " . $state1;
}
else {
echo "<p>There was a problem comparing the employment numbers.</p>";
}
}
}
Found the answer, it was because the "numbers" were being outputted as strings, and PHP wasn't recognizing them as numbers. I resolved it by first performing a str_replace on both $tot_EMP1 and $tot_EMP2 to remove the commas and then performing a intval() on both variables. This converts them to an integer, and the logic performs as desired. Now I will need to figure out how to add the commas back in and preserve the int status of the results.
The actual code that did the converting, but please keep in mind that my DB has the info stored as strings, so part of the problem was my own failure to properly store the data:
//Assign individual array values
$tot_EMP1 = $rows1['TOT_EMP'];
$tot_EMP2 = $rows2['TOT_EMP'];
$jobs_PER1 = $rows1['JOBS_1000'];
$jobs_PER2 = $rows2['JOBS_1000'];
$a_MEAN1 = $rows1['A_MEAN'];
$a_MEAN2 = $rows2['A_MEAN'];
$a_PCT901 = $rows1['A_PCT90'];
$a_PCT902 = $rows2['A_PCT90'];
//Convert individual array values to numbers
$tot_EMP1 = str_replace(",", "", $tot_EMP1);
$tot_EMP2 = str_replace(",", "", $tot_EMP2);
$tot_EMP1 = intval($tot_EMP1);
$tot_EMP2 = intval($tot_EMP2);
$jobs_PER1 = floatval($jobs_PER1);
$jobs_PER2 = floatval($jobs_PER2);
$a_MEAN1 = str_replace(",", "", $a_MEAN1);
$a_MEAN2 = str_replace(",", "", $a_MEAN2);
$a_MEAN1 = intval($a_MEAN1);
$a_MEAN2 = intval($a_MEAN2);
$a_PCT901 = str_replace(",", "", $a_PCT901);
$a_PCT902 = str_replace(",", "", $a_PCT902);
$a_PCT901 = intval($a_PCT901);
$a_PCT902 = intval($a_PCT902);

SQL Syntax Error via php

I'm kinda new to php, this place has been a great help for me so far! Anyway, I have this code
$month = "
SELECT SUM(`duration`)
FROM `connlist` AS `month_sum`
WHERE `vatsimid` = '$vatsimid'
AND MONTH(atc_online) = " . $pmonth . "
AND YEAR(atc_online) = " . $year . "
";
That's what I get when I echo out $month
SELECT SUM(`duration`)
FROM `connlist` AS `month_sum`
WHERE `vatsimid` = '1070757'
AND MONTH(atc_online) = 07
AND YEAR(atc_online) = 13
When i use this directly into phpMyAdmin, works as a charm, but when I try to do it through a php webpage, I get the syntax error. I'm using php 5.4
Thanks!
Edit: Full Code:
<?php
//open MySQL connection
$mysql = mysqli_connect('host', 'un', 'pass', 'table')
or die ( "MySQL Error: ".mysqli_error() );
//Get and decode residents data
$jsonData = file_get_contents("link");
$phpArray = json_decode($jsonData, true);
//Start Operations
foreach ($phpArray as $key => $value) {
//Get controller hours for today
$vatsimid = $value[vatsimid];
//Get previous month
$pmonth = date("m", strtotime("-35 days") ) ;
$pmonthName = date("M", strtotime("-35 days") ) ;
echo $pmonth;
echo $pmonthName;
//This year or last year?
If (date("M") != "Jan") { //Checks that it's not January of the next year.
$year = date("y");
}
else {
$year = date("y", strtotime("-1 month") );
}
echo $year;
//Search and sum entries during last month
$month = "SELECT SUM(`duration`)
FROM `connlist` AS `month_sum`
WHERE `vatsimid` = '$vatsimid'
AND MONTH(atc_online) = " . $pmonth . "
AND YEAR(atc_online) = " . $year . "";
echo $month;
echo "</br> </br>";
$result = mysqli_query($mysql,$month);
$row = mysqli_fetch_assoc($result);
$month_sum = $row['month_sum'];
echo $month_sum;
//Updates data in atclist
$datainsert = "
UPDATE `atclist`
SET " . $monthName . "=" . $month_sum . "
WHERE vatsimid = " . $vatsimid . "";
$insert = mysqli_query($mysql,$datainsert);
if (!$insert)
{
die('Error: ' . mysqli_error($mysql));
}
}
/*
Did you mean:
SELECT SUM(duration) AS month_sum
FROM connlist
WHERE vatsimid = '1070757' AND MONTH(atc_online) = 07 AND YEAR(atc_online) = 13
It looks like $month_sum variable is not set or empty in your UPDATE query.
You can add single quotes like
$datainsert = "
UPDATE atclist
SET ".$monthName."= '".$month_sum."'
WHERE vatsimid= '".$vatsimid."'";

Php script to export mysql table data to a csv, escaping data from certain columns and mapping strings to arrays?

I need to migrate data within our old bug tracker (Zentrack) to our new one and the only import method I can use is to import from CSV. To do so I need the data from two tables, tickets and logs so I wrote the script below in php.
<?php
error_reporting(E_ALL);
$host = "localhost";
$user = "dbuser";
$pass = "dbpass";
$db = "zentrk";
$users[1] = 'john';
$users[4] = 'sally';
$users[5] = 'nick';
$users[6] = 'ralph';
$r = mysql_connect($host, $user, $pass);
if (!$r) {
echo "Could not connect to server\n";
trigger_error(mysql_error(), E_USER_ERROR);
}
echo mysql_get_server_info() . "\n";
$r2 = mysql_select_db($db);
if (!$r2) {
echo "Cannot select database\n";
trigger_error(mysql_error(), E_USER_ERROR);
}
$query_tickets = "select ZENTRACK_TICKETS.id, ZENTRACK_TICKETS.title, ZENTRACK_TICKETS.priority, ZENTRACK_TICKETS.status, ZENTRACK_TICKETS.description, ZENTRACK_TICKETS.otime,
ZENTRACK_TICKETS.type_id, ZENTRACK_TICKETS.user_id, ZENTRACK_TICKETS.system_id, ZENTRACK_TICKETS.creator_id, ZENTRACK_TICKETS.proj_key
from ZENTRACK_TICKETS
where ZENTRACK_TICKETS.status = 'OPEN'
and ZENTRACK_TICKETS.system_id in ('18', '3', '6', '1', '16', '7', '9', '4', '20')
and ZENTRACK_TICKETS.type_id not in ('1', '10', '5')";
$rs = mysql_query($query_tickets);
if (!$rs) {
echo "Could not execute query: $query";
trigger_error(mysql_error(), E_USER_ERROR);
} else {
echo "Query: $query executed\n";
}
$export = array();
$export[] = 'id,title,created date,priority,type,assigned,description,system,creator,project key,log1,log2,log3,log4,log5,log6,log7,log8,log9,log10
';
while ($row = mysql_fetch_assoc($rs)) {
$line = '';
$count = 0;
$line .= $row['id'] . "," . $row['title'] . "," . date('d-M-y h:m a',$row['otime']) . "," . $row['priority'] . "," . $row['type_id'] . "," . $row['user_id'] . "," . $row['description'] . "," . $row['system_id'] . "," . $row['creator_id'] . "," . $row['proj_key'] . ",";
$logs = find_logs($id = $row['id']);
foreach($logs as $log_entry) {
$line .= $log_entry.",";
$count++;
}
while($count < 10) {
$line .= ",";
$count++;
}
$export[] = $line.'
';
}
mysql_close();
// print_r($export);
$file = 'tickets.csv';
file_put_contents($file, $export);
function find_logs($ticket) {
$content = array();
$query = "select ZENTRACK_LOGS.created, ZENTRACK_LOGS.user_id, ZENTRACK_LOGS.entry
from ZENTRACK_LOGS
where ZENTRACK_LOGS.ticket_id = $ticket
and ZENTRACK_LOGS.action <> 'EDIT' ";
$rs = mysql_query($query);
if (!$rs) {
echo "Could not execute query: $query";
trigger_error(mysql_error(), E_USER_ERROR);
}
while ($row = mysql_fetch_assoc($rs)) {
$date = date('d-M-y h:m a',$row['created']);
$content[] = $date . ";" . $row['user_id'] . ";" . $row['entry'];
}
return $content;
}
?>
I'm running into two problems with this script, that I'm sure are due to me being new to PHP.
1) I need to escape out the data in $row['description'] as it contains both carriage returns and , in the text that is incorrectly breaking the output into new rows when saved to CSV. I need to save the contents of this row within " " but I'm not sure how to do so.
2) The data returned in $row['user_id'], $row['creator_id'] and $row['user_id'] within the find_logs function returns a number, which I need to find that number and replace with the corresponding string in the $users array. What's the best way to do this?
When dealing with csv files use fgetcsv and fputcsv, provide it with an array and it will handle the escaping for you.

Categories