How to include a PHP variable inside MySQL query - php

I wanna add an extra column to my database and give it the name price_23-05-2019.
How do I put this into a working query?
I have this right now, which is clearly not working:
$date = date("d-m-Y");
$query =
"ALTER TABLE `products_05_2019`
ADD price_'.$date.' DECIMAL(7,2)";
($result = mysqli_query($link, $query))

You really shouldn't have separate columns for each date. There should just be a date column, with the date as the value, and a separate row for each date.
But if you have to do it this way, here's how to solve it.
If you use - in a column name, you have to enclose the name in backticks.
$date = date("d-m-Y");
$query =
"ALTER TABLE `products_05_2019`
ADD `price_$date` DECIMAL(7,2)";
$result = mysqli_query($link, $query);
But it would probably be better to use _ instead of -.
$date = date("d_m_Y");
$query =
"ALTER TABLE `products_05_2019`
ADD price_'.$date.' DECIMAL(7,2)";
$result = mysqli_query($link, $query);

As #ficuscr says above, you may want to have a look at the design of your database so you don't have to create columns from code.
Anyway, what I use to do when I have a column name depending on code is create a new variable and then include it into the query:
$date = date("d-m-Y");
$column_name = 'price_'.$date;
$query = "ALTER TABLE `products_05_2019` ADD `$column_name` DECIMAL(7,2)";

Related

Can't update Date field in MySql using PHP

I have a DATE field in my table, and I'm trying to update it using the following code:
$query = mysqli_query($conn,$sql);
$todaydate = date("Y-m-d");
$sqlDate = date('Y-m-d', strtotime($todaydate));
$sql="UPDATE Library SET Loaned=1, LoanedDate=$sqlDate WHERE BookId=$bookId";
$query = mysqli_query($conn,$sql);
It updates the "Loaned" field fine, but always sets the Date field to "0000-00-00". Can anyone indicate what I'm doing wrong?
Youre missing ' quotes in your update query
Just use something like this
$sql="UPDATE Library SET Loaned=1, LoanedDate='$sqlDate' WHERE BookId='$bookId'";
$query = mysqli_query($conn,$sql);
You must have to add Quotes to the values... other wise the date may seem like an invalid integer to mysql. Here's how:
$query = mysqli_query($conn,$sql);
$todaydate = date("Y-m-d", time()); //<== DON'T FORGET THE 2ND ARGUMENT TO date(): TIME-STAMP. YOU MAY USE: time()
$sqlDate = date('Y-m-d', strtotime($todaydate));
$sql ="UPDATE Library SET Loaned=1, LoanedDate='{$sqlDate}' WHERE BookId='{$bookId}'";
$query = mysqli_query($conn,$sql);
Why don't you use only MySQL function to update date
Use this
$sql = "UPDATE Library SET Loaned = 1, LoanedDate = DATE(NOW())
WHERE BookId = '".$bookId."'";
Change your query with this code
$sql="UPDATE Library SET Loaned=1, LoanedDate= current_date() WHERE BookId='".$bookId."'";
Also check data structure in database.
This query is working fine:
$current_date = strtotime(date('Y-m-d H:i:s'));
$sql = "UPDATE user SET dt_added = '".$current_date."' WHERE id = '$id' ";
You're not concatenating the Date string properly in the SQL query.
Use ' and . operator to concatenate the string. Like this,
$sql="UPDATE Library SET Loaned=1, LoanedDate='".$sqlDate."' WHERE BookId='".$bookId."'";
Altough it's good practice to use Prepared statement to pass arguments in SQL query.
Learn more about PHP Prepared Statements
Looking closer, I would just do:
$sql="UPDATE Library SET Loaned=1, LoanedDate='".$todaydate."' WHERE BookId='".$bookId."'";
instead of
$sql="UPDATE Library SET Loaned=1, LoanedDate='".$sqlDate."' WHERE BookId=$bookId";

Unable to INSERT dates and times into MYSQL database with PHP

I am trying to build an SQL query that will insert the check-in time for a child at a fictional daycare facility. Here is a condensed version of my query code:
$childFirstName = $_POST['childFirstName'];
$childLastName = $_POST['childLastName'];
$now = new DateTime();
$nowDate = $now->format('m-d-Y');
$nowTime = $now->format('h:i');
$sql_childID = "SELECT id FROM child
WHERE firstName = '$childFirstName'
AND lastName = '$childLastName'";
$result = $pdo->query($sql_childID);
$row = $result->fetch();
$sql = "INSERT INTO checkinout(date, in, child_id) VALUES(?,?,?)";
$statement = $pdo->prepare($sql);
$statement->bindValue(1, $nowDate);
$statement->bindValue(2, $nowTime);
$statement->bindValue(3, $row['id']);
$statement->execute();
The checkinout table uses VARCHAR datatypes for the date and in columns. Originally they were set to use DATETIME, but I received the same errors.
Right now I get the following errors returned...
You can see from the error messages that my values are getting passed in the way I want them to, but I don't understand where my syntax error would be.
Enclose your field names with backticks. Two of them are reserved words (date and in):
$sql = "INSERT INTO checkinout(`date`, `in`, `child_id`) VALUES(?,?,?)";
https://dev.mysql.com/doc/refman/5.5/en/keywords.html

update data in existing row in mysql database

I have a table called pack_details with 4 columns. I'm trying to insert new data into an existing table. Can somebody tell me what's wrong with my codes and why i have a parse error?
$sql_query = "UPDATE pack_details SET $delivery_date = $_POST["delivery_date"], $delivery_time = $_POST["delivery_time"]
WHERE $delivery_building = $_POST["delivery_building"]
AND $delivery_room = $_POST["delivery_room"]";
Try any from below options:
$sql_query = "UPDATE pack_details SET $delivery_date = '{$_POST['delivery_date']}', $delivery_time = '{$_POST['delivery_time']}' WHERE $delivery_building = '{$_POST['delivery_building']}' AND $delivery_room = '{$_POST['delivery_room']}'";
or
$sql_query = "UPDATE pack_details SET delivery_date = '".$_POST["delivery_date"]."', delivery_time = '".$_POST["delivery_time"]."' WHERE delivery_building = '".$_POST["delivery_building"]."' AND delivery_room = '".$_POST["delivery_room"]."'";
Note: If field name doesn't contain $, remove $ from field name in query. For eg. "$delivery_date" should be "delivery_date"
Suggestion: Instead of using string concatenation for building, You should use bind parameters to pass value to query. It helps to prevent SQL injection as well as code look well.

Cannot rename MySQL table

Please help me to discover syntax error in my rename_table script. What i want is add date to the table name, but something goes wrong.
Now here's the code:
$date = date('d-m-Y');
$query = "RENAME order TO order".$date;
if(mysql_query($ren)){
...
You have to use backticks for order as it is a reserved keyword. Also you are executing the query wrongly.
if(mysql_query($ren))
^
Replace $ren with $query as your query is stored in a variable $query, not $ren..
So try with
$query = "RENAME TABLE `order` TO order".$date;
if(mysql_query($query))
change
$query = "RENAME order TO order".$date;
to
$query = "RENAME `order` TO `order".$date."`";
You cant use - sign as table name, use _ or dmy format 06nov2014
Try this
$date = date('d-m-Y');
$query = "RENAME `order` TO `order".$date."`";
if(mysql_query($ren))

Check database table if row exists, then create it if not

I am trying to check the database if data for a specific date exists. If it does not exist, then a new row needs to be inserted into the database for that date. Here's my code so far in php/sql (after db login info), but I can't get it to work:
// gets two data points from form submission
$tablename = $_GET['tablename'];
$date = $_GET['date'];
//Fetching from your database table.
$query = "IF NOT EXISTS (SELECT * FROM $tablename WHERE date = $date) BEGIN Insert into $tablename (date, var1, var2) VALUES ('$date', '', ''); END"
$result = mysql_query($query);
Please HELP...
Just USE INSERT ON DUPLICATE KEY UPDATE

Categories