Why is the same date echoing despite being created and stored properly in db? - date

I am pulling comments from my database. The 'created_on' field I have created is inserting properly, however when I echo the results, it's a random date and time that is the same no matter what(Mar 11, 2013 at 10:50 AM).
Here is my query to pull the records:
public function get_airwave_comments($profile_id)
{
$session = $this->session->userdata('is_logged_in');
$user_id= $this->session->userdata('id');
if($profile_id == $user_id)
{
$comments_query = "SELECT * FROM airwaves_comments aw,users u WHERE u.id=aw.from_id AND AW.FROM_id=aw.to_id AND aw.from_id=".$profile_id." order by aw.created_on desc" ;
}
else
{
$comments_query = "SELECT * FROM airwaves_comments aw,users u WHERE u.id=aw.from_id AND aw.to_id=".$profile_id." order by aw.created_on desc" ;
}
$query = $this->db->query($comments_query);
if($query->num_rows() >= 1)
{
$data = $query->result_array();
// return whole resultset. It contains zero, one or more records
return $data;
}
else return false;
$query = $this->db->query($poster_info_query);
if($query->num_rows() >= 1)
{
$data = $query->result_array();
// return whole resultset. It contains zero, one or more records
return $data;
}
else return false;
}
}
Here is the view in which I'm trying to echo the 'created_on' field properly:
if ($airwave && $profile_id == $session_id)
{
foreach ($airwave as $airwave_comment_row)
$airwave_comment_row = $airwave[0];
{
echo "<div id='profile_airwave'>";
echo $airwave_comment_row['comment'];
echo "<br />";
echo "<span class='profile_airwave_info'>";
echo date('M d, Y',strtotime($airwave_comment_row['created_on'])); ?> at <?php echo date('g:i A',strtotime($airwave_comment_row['created_on']));
echo "</span>";
echo "</div>";
}
}
so basically even if I just do echo $airwave_comment_row['created_on']; It's echoing the same said date.
thanks in advance.

I changed the name of the datetime column in the comments table so that it was different from the datetime column in the users table it's being spliced with.

Related

Getting sum in PHP MySQL

I want to get sum of integers that are selected from mysql
Here is my code
<?php
Include 'init.php';
$page = '2459';
$ttl = array();
$search = $db->link->query("SELECT id,packid,rating FROM pakrate WHERE packid LIKE '%$q%'");
if($search->num_rows>0){
while($result=$search->fetch_assoc()){
$ttl[] = $row['rating'];
echo $ttl;
echo $result[SUM('rating')];
}
}
else {
echo "no such query";
}
So what I am doing wrong here, any other suggestions?
Just run the sum in your query
<?php
Include 'init.php';
$page = '2459';
$ttl = array();
// Not sure why you're doing this but there should only be one leading connection ($conn->query) unless you're doing some object item elsewhere in init.
// I would also use prepared statements since they're more secure:
$q = "%$q%"; // create your like variable, wherever $q is coming from??
$query = "SELECT sum(rating) from pakrate WHERE packid LIKE ?);
$stmt = $db->prepare($query); // assuming $db is your connection variable
if($stmt){
$stmt->bind_param("s",$q); // Bind the variable in
$stmt->execute(); // Execute
$stmt->bind_result($rating); // Bind the result variable
$stmt->store_result(); // Store it so you can get num_rows
$rows = $stmt->num_rows; // assign rows found
if($rows > 0){
while($stmt->fetch()){ // Loop the result
$ttl[] = $rating; // add to your array
// You can't echo an array like this.... echo $ttl;
// if you really want to, print_r($ttl);
}
}
$stmt->close(); // Close it
}
?>

Returning an array using PDO

I'm trying to use PDO using the following code, I want to select the array of values for the context_list, but it returns one record, any ideas where I'm going wrong?
try {
$sql2 = "SELECT area_easting, area_northing, context_number FROM excavation.contexts";
$sth = $conn->prepare($sql2);
$sth->execute();
while ($row = $sth->fetch(PDO::FETCH_ASSOC))
{
$easting_list = $row['area_easting'];
$northing_list = $row['area_northing'];
$context_list = $row['context_number'];
}
}
catch(PDOException $e )
{
echo "Error: ".$e;
}
echo "context list: ";
echo $context_list;
A partial solution:
This worked:
$query = $conn->prepare("SELECT area_easting, area_northing, context_number FROM excavation.contexts");
$query->execute();
while($r = $query->fetch(PDO::FETCH_OBJ)){
echo $r->area_easting, '|';
echo $r->area_northing;
echo '<br/>';
}
But Now I need to make the $r->area_easting accessible to the session, but that's another question.
Your query may return several records (provided they actually exist in the table).
Your code loops through all the records (with the while loop) but the values ($easting_list, $northing_list and $context_list) are overwritten in the loop.
I suggest the following changes to your code:
$easting_list = array();
$northing_list = array();
$context_list = array();
try {
$sql2 = "SELECT area_easting, area_northing, context_number FROM excavation.contexts";
$sth = $conn->prepare($sql2);
$sth->execute();
while ($row = $sth->fetch(PDO::FETCH_ASSOC))
{
$easting_list[] = $row['area_easting'];
$northing_list[] = $row['area_northing'];
$context_list[] = $row['context_number'];
}
}
catch(PDOException $e )
{
echo "Error: ".$e;
}
echo "context list: ";
echo implode(', ', $context_list);
Now all the values are stored in 3 arrays. explode is used to print a comma-separated list of all values in $context_list array.

change mysqli check exit and insert into pdo statement

i want to change my mysqli check exist and insert into pdo.. my statement look like below:
<?php
$addSearch = preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $search);
if ($CheckMusic = $mysqli->query("SELECT * FROM search WHERE term='$addSearch'")) {
$CheckRow = mysqli_fetch_array($CheckMusic);
$CheckId = $CheckRow['id'];
$CheckCnt = $CheckMusic->num_rows;
$CheckMusic->close();
} else {
printf("Error: %s\n", $mysqli->error);
}
$Now = strtotime("now");
$addSearch = $mysqli->escape_string($addSearch);
if ($CheckCnt < 1) {
$mysqli->query("INSERT INTO search (term, datetime) VALUES('$addSearch','$Now') ") or die(mysqli_error());
} else {
$mysqli->query("UPDATE search SET datetime='$Now' WHERE id='$CheckId'") or die(mysqli_error());
}
?>
hope someone can help with sample if can ;q thanks for your advance!
<?php
$addSearch = preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $search);
$CheckMusic = $mysqli->query("SELECT * FROM search WHERE term='$addSearch'");
$Now = strtotime("now");
if($CheckMusic->num_rows == 0){
$mysqli->query("INSERT INTO search (term, datetime) VALUES('$addSearch','$Now') ") or die(mysqli_error());
}else{
$CheckRow = mysqli_fetch_array($CheckMusic);
$CheckId = $CheckRow['id'];
$addSearch = $mysqli->escape_string($addSearch);
$mysqli->query("UPDATE search SET datetime='$Now' WHERE id='$CheckId'") or die(mysqli_error());
}
I hope it will work.

Fatal error: Call to a member function prepare() on a non-object in mysqlicon.php on line 62 Help explain OOP mysqli classes and prepared statements [duplicate]

This question already has answers here:
Call to a member function on a non-object [duplicate]
(8 answers)
Closed 10 years ago.
I'm hesitant to post this, as I'd really prefer to figure this out myself, but I don't think I will. I'm just trying to set a class for mysqli stuff, to make it as dynamic as possible, and yes I'm newer to OOP, but have been using PHP and Mysql as a hobby, and more heavily lately, for quite some time. I figured it was time to switch, but there just isn't that much on oop classes with mysqli and prepared statements with a possibility of multiple results (yes I've check documentation, guess I'm just not getting it or something). After quite a few hours, this is what I have. I'm not necessarily looking for a "quick fix". I really want to understand this and learn, so please explain thoroughly.
I'm using a dbconfig.php file to store my database info at root/config/dbconfig.php
in root/classes/mysqlicon.php
<?php
/*
* class MYSQLIDB
* #param Host
* #param User
* #param Password
* #param Name
*/
class MYSQLIDB
{
private $host; //MySQL Host
private $user; //MySQL User
private $pass; //MySQL Password
private $name; //MySQL Name
private $mysqli; //MySQLi Object
private $last_query; //Last Query Run
/*
* Class Constructor
* Creates a new MySQLi Object
*/
public function __construct()
{
include('./config/dbconfig.php');
$this->host = $db_host;
$this->user = $db_user;
$this->pass = $db_pass;
$this->name = $db_name;
$this->mysqli = new mysqli($this->host, $this->user, $this->pass, $this->name);
if ($mysqli->connect_errno) {
return "Failed to connect to MySQLi: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
}
private function __destruct()
{
$mysqli->close();
}
public function select($fields, $from, $where, $whereVal, $type, $orderByVal, $ASDESC, $limitVal)
{
if (is_int($whereVal))
{
$bindVal = 'i';
} else {
$bindVal = 's';
}
switch($type)
{
case "regular":
$queryPre = "SELECT " . $fields;
$querySuff = " WHERE " . $where . " = ?";
break;
case "orderByLimit":
$queryPre = "SELECT " . $fields;
$querySuff = " ORDER BY " . $orderByVal . " " . $ASDESC . " LIMIT " . $limitVal;
break;
}
//$query = "SELECT * FROM news ORDER BY id DESC LIMIT 4";
if ($stmt = $mysqli->prepare('$queryPre . " FROM " . $from . " " . $querySuff'))
{
if ($type == 'regular') {
$stmt->bind_param($bindVal, $whereVal);
}
$stmt->execute();
$stmt->bind_result($values);
$stmt->store_result();
$sr = new Statement_Result($stmt);
$stmt->fetch();
// call by this style printf("ID: %d\n", $sr->Get('id') );
//$stmt->fetch();
//$stmt->close();
//return $value;
printf("ID: %d\n", $sr->Get_Array() );
} else return null;
}
//use to call $db = new MYSQLI('localhost', 'root', '', 'blog');
/*
* Function Select
* #param fields
* #param from
* #param where
* #returns Query Result Set
function select($fields, $from, $where, $orderBy, $ASDESC, $limit, varNamesSent)
{
if ($orderBy == null &&)
$query = "SELECT " . $fields . " FROM `" . $from . "` WHERE " . $where;
$result = $this->mysqli->query($query) or exit("Error code ({$sql->errno}): {$sql->error}");
$this->last_query = $query;
return $result;
}
/*
* Function Insert
* #param into
* #param values
* #returns boolean
*/
public function insert($into, $values)
{
$query = "INSERT INTO " . $into . " VALUES(" . $values . ")";
$this->last_query = $query;
if($this->mysqli->query($query))
{
return true;
} else {
return false;
}
}
/*
* Function Delete
* #param from
* #param where
* #returns boolean
*/
public function delete($from, $where)
{
$query = "DELETE FROM " . $from . " WHERE " . $where;
$this->last_query = $query;
if($this->mysqli->query($query))
{
return true;
} else {
return false;
}
}
}
//Hand arrays for multiple returned items from database
class Statement_Result
{
private $_bindVarsArray = array();
private $_results = array();
public function __construct(&$stmt)
{
$meta = $stmt->result_metadata();
while ($columnName = $meta->fetch_field())
$this->_bindVarsArray[] = &$this->_results[$columnName->name];
call_user_func_array(array($stmt, 'bind_result'), $this->_bindVarsArray);
$meta->close();
}
public function Get_Array()
{
return $this->_results;
}
public function Get($column_name)
{
return $this->_results[$column_name];
}
}
?>
And just as a test, I'm trying to pull all the news in my db by:
<?php
require_once('classes/mysqlicon.php');
$testing = new MYSQLIDB;
$testing->select('*','news',null,null,'orderByLimit','id','DESC',4);
?>
But what I really want is stuff that can do the equivalent of this:
<?php
/*
require('config/dbconfig.php');
$query = "SELECT * FROM news ORDER BY id DESC LIMIT 4";
if ($stmt = $mysqli->prepare($query)) {
// execute statement
$stmt->execute();
// bind result variables
$stmt->bind_result($idn, $titlen, $categoryn, $descn, $postdaten, $authorn);
// fetch values
while ($stmt->fetch()) {*/
//echo 'id: '. $id .' title: '. $title;
echo "<table border='0'>";
$shortDescLengthn = strlen($descn);
if ($shortDescLengthn > 106) {
$sDCutn = 106 - $shortDescLengthn;
$shortDescn = substr($descn, 0, $sDCutn);
} else {
$shortDescn = $descn;
}
echo "<h1>$titlen</h1>";
echo "<tr><td>$shortDescn...</td></tr>";
echo '<tr><td><a href="javascript:void(0);" onclick="'
. 'readMore(' . $idn . ',' . htmlspecialchars(json_encode($titlen)) . ','
. htmlspecialchars(json_encode($categoryn)) . ','
. htmlspecialchars(json_encode($descn)) . ',' . htmlspecialchars(json_encode($postdaten)) . ','
. htmlspecialchars(json_encode($authorn)) . ')">Read More</a></td></tr>';
echo "<tr><td>Written by: $authorn</td></tr>";
echo '<tr><td><img src="images/hardcore-games-newsbar-border.png" width="468px" /></td></tr>';
}
echo "</table><br />";
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>
Again, please, please explain in detail. I'm a blockhead sometimes.
I'm assuming the error is coming from this line:
if ($stmt = $mysqli->prepare('$queryPre . " FROM " . $from . " " . $querySuff'))
$mysqli is not defined in the context of this function. You should be accessing $this->mysqli instead. The same applies to other references you have made such as here:
if ($mysqli->connect_errno)

Formating a date field in the Model (Codeigniter)

I', trying to re-format a date from a table in Codeigniter. The Controller is for a blog. I was succesfull when the date conversion happens in the View. I was hoping to convert the date in the Model to have things in order.
This is the Model:
class Novedades_model extends Model {
function getAll() {
$this->db->order_by('date','desc');
$query = $this->db->get('novedades');
if($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
}
return $data;
}
}
This is part of the controller
$this->load->model('novedades_model');
$data['records'] = $this->novedades_model->getAll();
Here's the date conversion as it happens in the View. This is inside the posts loop:
<?php foreach($records as $row) : ?>
<?php
$fdate = "%d <abbr>%M</abbr> %Y";
$dateConv = mdate($fdate, mysql_to_unix($row->date));
?>
<div class="article section">
<span class="date"><?php echo $dateConv ;?></span>
... Keeps going ...
How can I convert the date in the Model? Can I access the date key and refactor it?
Why you need to format the date in the Model because ultimately you need the formatted date in the View to be shown. However, you can do the same what you are already doing in the View for formatting it:
function getAll() {
$this->db->order_by('date','desc');
$query = $this->db->get('novedades');
if($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
}
foreach($data as $row) :
$fdate = "%d <abbr>%M</abbr> %Y";
$dateConv = mdate($fdate, mysql_to_unix($row->date));
............
}