php mysql wrong value from timestamp column - php

I have a mysql table that holds property for sale data, I record when then property is first listed in the column 'Added' and when the property details are updated I record the date and time in the 'Updated' Column.
This all works fine but when I run a query with php and return the row the value of the 'Updated' column is being returned as the current time.
Here is my table structure :
My query I use is this
$query = $pdo->query("SELECT * FROM table WHERE ID = 5030238");
while ($p = $query->fetch()) {
$added = $p['Added'];
$updated = $p['Updated'];
}
Expected output would be the variables to equal this:
$added = '2018-05-10 19:23:51'
$updated = '2018-05-11 09:55:11'
But the $updated is giving me the current time and date instead!
Does any one know what is wrong here?
Any help is much appreciated.

Related

Laravel Eloquent Builder: Get selected columns

I have a object (Illuminate\Database\Eloquent\Builder) that have a (Illuminate\Database\Query\Builder) inside it. I dump the object and can see this:
The image bellow, is a dd($querybuilder) from the object
My plan is to get the query and extract the selected columns but I already tried ($querybuilder->query) and ($querybuilder['query']) and I received errors.
How can I get the "columns" value?
Solved. Thank you
Tim Lewis
$query->getQuery()->columns worked!
Im posting where what im tying to do. select and addSelect are not doing what I wanted if no colunms are selected.
public function scopeAddStatusColumn($query)
{
$previous_columns = $query->getQuery()->columns;
$status_column = DB::raw('(begin <= NOW() AND end >= NOW()) OR (begin <= NOW() AND end IS NULL) as status');
$new_columns = $previous_columns == null ? ['*', $status_column] : [$previous_columns] + [$status_column];
$query = $query->select($new_columns);
return $query;
}
If you want to get all the columns of the table:
$query = Products::where('product_name', 'pencil')->get();
If you want to get a spesific column:
$query = Products::where('product_name', 'pencil')->get(['product_id']); // this is an array, you can get any column name here
If you want to get value of a single column:
$query = Products::where('product_name', 'pencil')->first(['description'])->description;

Column count doesn't match value count at row 1 when Bind_param() with UPDATE statement

Here is my code:
public function deletePost($postId,$userId){
$stmt = $this->conn->prepare("UPDATE post SET active_status = ? ,modified_by =? ,modified_time=? WHERE post_id=?");
$notActivePost = 0;
$currentTime = $this->getCurrentTime();
$stmt->bind_param("ssss",$notActivePost,$userId,$currentTime,$postId);
$res = $stmt->execute();
var_dump($notActivePost,$currentTime,$postId,$userId);
var_dump($stmt->error_list);
return $res;
}
I checked the value of all the variable which is all correct,as below:
$notActivePost = 0 //I tried this also $notActivePost = "0",also not work
$currentTime = 2017-08-30 20:34:05
$postId = 606
$userId = 56
But I keep getting this error
Column count doesn't match value count at row 1
I check all the question about this error is because the column number in query not same with the number of variable binding in,but as you see is 4 column in query,and 4 variable I binding in.So I really don't know what's going on here.
Can somebody please help?Cause I tried some many ways already..tq
EDIT:
I tried this same code in localhost all going good.But this code run in live server,it produce the error.
need to pass i if field is of type integer.Considering active_status, modified_by and post_id as of type integer
DO the change from ssss to iisi
public function deletePost($postId,$userId){
$stmt = $this->conn->prepare("UPDATE post SET active_status = ? ,modified_by =? ,modified_time=? WHERE post_id=?");
$notActivePost = 0;
$currentTime = $this->getCurrentTime();
$stmt->bind_param("iisi",$notActivePost,$userId,$currentTime,$postId);
$res = $stmt->execute();
var_dump($stmt->error_list);
return $res;
}
After 10 more hours to figure it out what is the problem,finally I solve it.It actually cause by the trigger of the table but not the query itself.The number of the data count not match the column to insert in the trigger that cause this error
Column count doesn't match value count at row 1
Hope can help the future reader solve this problem.I suggest if the query is all correct,but still produce this error,just check the trigger of your table.

How to limit how often a user can update a mysql value to a database

I have a field on my website, which updates a value in my mysql database. I want to make it so the user can only update the value every 3 days. How would I go about doing this?
Here is the code that I have written so far:
<?php
if(isset($_POST['Update'])){
$UpdateHWID = $_POST['HWID'];
$sql = $con->query("UPDATE users SET HWID = '{$UpdateHWID}' where UserID = $User");
echo "HWID Updated Successfully!";
}
?>
Use a last updated field in mysql (date and time of last update), and check it before making the update. If satisfies your condition then commit the update and also update that time field, if not show error to the user.
Create new row into db (last_update) type= data
//return to sql last_update (select db ...)
$current_Data = date ('Y-m-d');
$current_Data_time = strtotime ($current_Data); //convert data to time
$last_update_p3 = strtotime ("+3day", strtotime($last_update));
$last_update_p3 = strtotime ($last_update_p3);//convert data to time
if($current_Data_time <=$last_update_p3)
{
$sql = $con->query("UPDATE users SET HWID = '{$UpdateHWID}' , last_update='{$current_Data}' where UserID = $User");
//update last data with current date
}
else
{
//It has not gone three days
}
According to Pinx0, if you add a new column to your users table which contains the date of the last update, then you can create a condition. For example:
ALTER TABLE `users`
ADD `lastUpdated` DATE NOT NULL;
Now you can add a condition to your existing query something like this:
UPDATE `users`
SET `HWID` = '{$UpdateHWID}',
`lastUpdated` = NOW()
WHERE `UserID` = $User AND 2 < DATEDIFF(CURDATE(),`lastUpdated`);
You can easily do that, using the DATEDIFF method.
It will be my first comment. so, Let me know if I have written
something incorrectly here.
$currentDate = date('Y-m-d');
$query = "SELECT DATEDIFF($currentDate,*Last_update_date_row_name*) as diff FROM *TABLE_NAME* WHERE user_id=Current_User_Id";
$result = mysqli_query($conn,$query);
if($result!=false){
//compare the diff with your desire number
// then you can hide or disable the button or show error
}

Return frequency of string in MYSQL column with PHP

after searching for several questions, i'm still struggling with mysql queries in PHP, my current goal is to do a MYSQL query that counts how many repeated strings are in a column and then return this amount in a INT variable to be written in the database.
The current code looks like:
//Fetch value from form and uppercase the string
$glitter = utf8_decode(strtoupper($_POST['code_string']));
$magic = mysql_query("SELECT COUNT(*) FROM table WHERE CODE_STR = '$glitter'");
The next step is inserting the var $magic into a INT field in the database, however the value is always 0.
Where is my mistake?
Thanks.
mysql_query returns a resource on success, or FALSE on error.
try this
$magic = mysql_query("SELECT COUNT(*) as count FROM table WHERE CODE_STR = '$glitter'");
$row = mysql_fetch_assoc($magic);
$count = $row['count'];
Your approach is correct. What you need to do now is
Change your query from
$magic = mysql_query("SELECT COUNT(*) FROM table WHERE CODE_STR = '$glitter'");
to
$magic = mysql_query("SELECT COUNT(*) as total_num FROM table WHERE CODE_STR = '$glitter'");
mysql_fetch_assoc() Use the returned value from table
$magic_row = mysql_fetch_assoc($magic);
echo $magic_row['total_num'];
See
http://php.net/manual/en/function.mysql-fetch-assoc.php

Php PDO request for data from the sum of a derived table column

Here is an SQL query that I am attempting to use in some php PDO code:
SELECT SUM(credit_hours) AS hours FROM(SELECT Course_List.credit_hours FROM Program_Courses, Course_List
WHERE program_id= :pid and concentration_id= :conid
and fulfills_major=1 and Program_Courses.course_id = Course_List.course_id ) AS major_credits
When I run this query on my database in SQL Workbench I get a derived table with a single column named
"hour" and a single row with the value 76 in it.
Here is the php code I'm using to try to get this same data stored in a variable $major_hours:
$result = $conn->prepare("SELECT * FROM students WHERE username = :un");
$result->bindParam(':un',$user);
$result->execute();
$data = $result->fetch(PDO::FETCH_ASSOC); //returns an associated array where the indices are the column names
$program = $data['program_id'];
$concentration = $data['concentration_id'];
//get the total number of credit hours in the student's major/concentration
$result = $conn->prepare("SELECT SUM(credit_hours) AS hours FROM(
SELECT Course_List.credit_hours FROM Program_Courses, Course_List
WHERE program_id= :pid and concentration_id= :conid
and fulfills_major=1 and Program_Courses.course_id = Course_List.course_id
) AS major_credits");
$result->bindParam(':pid',$program);
$result->bindParam(':conid',$concentration);
$result->execute();
$major_hours = $result->fetchColumn();
I know that the variables $user, $program, and $concentration all have legitimate values because when I echo those to the page, I get the correct result. However, echoing $major_hours gives absolutely nothing. What am I doing wrong?
Use fetch as you may guess it fetches the next row from a result set
The fetch_style parameter determines how PDO returns the row, in your case FETCH_ASSOC would be a good one since it returns an array indexed by column name as returned in your result set.
$row = $result->fetch(PDO::FETCH_ASSOC);//row is an associative array
$major_hours = $row['hours']; //access the column name hour
echo $majors_hours; //will print the hour value from db
I have not used sql workbench, but you may want to use isnull() or coalesce() on your SUM(credit_hours) expression. I think that should result in $major_hours showing 0.
Use this
$major_hours = $result->fetch(PDO::FETCH_ASSOC);
echo $majors_hours['hours'];
There is 2 way to return a data from database. fetch(PDO::FETCH_ASSOC) and fetchAll(PDO::FETCH_ASSOC). Fetch only return 1 row from database .. but fetchAll will return all row from the database query you make.
And (PDO::FETCH_ASSOC) it means will return the data with an array.

Categories