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
Related
I need to generate a code which consists of some arbitrary prefix, a year, and an incrementing number. The incrementing number must start at 1 at the first time when the number is generated that year.
This code needs to be added to the sqlite database and be available elsewhere in the PHP script.
What i have done now uses 4 accesses to the database:
$codePrefix = 'TEST';
$stmt = $db->prepare(
'INSERT INTO test (year)
VALUES(strftime("%Y", "now"))'
);
$stmt->execute();
$id = $db->lastInsertId();
$stmt = $db->prepare('SELECT `year` FROM `test` WHERE `id`=:id');
$stmt->bindValue(':id', $id);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$year = $result['year'];
$stmt = $db->prepare('SELECT Ifnull(Max(id), 0) `max_id` FROM `test`
WHERE `year`<:year');
$stmt->bindValue(':year', $year);
$result = $stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$previousMax = $result['max_id'];
$codeSuffix = $id-$previousMax;
$code = "{$codePrefix}-{$year}-{$codeSuffix}";
$stmt = $db->prepare('UPDATE `test` SET `code`=:code WHERE `id`=:id');
$stmt->bindParam(':code', $code);
$stmt->bindParam(':id', $id);
$stmt->execute();
Here i am abusing the fact that the id is an integer primary key, and autoincrements.
This works. But i feel that it is doing something very easy in a very complicated manner.
Is there a better solution? I need to assume that the midnight of the first of January can happen at any moment of the code, so i cannot do things like get the year information from PHP without hitting the database.
Before somebody asks, the reason i am using prepared statements even when no values are bound is because late on obviously more data will be inserted into the table.
Consider a pure SQL solution using the ROW_NUMBER window function. Below assigns to new field, new_id:
UPDATE test
SET new_id = 'TEST_' || test.[Year] || '_' || sub.rn
FROM (
SELECT id,
[Year],
ROW_NUMBER() OVER (PARTITION BY [Year] ORDER BY id) AS rn
FROM test
) AS sub
WHERE test.id = sub.id;
I'm getting the same error some some people got here. But still my problem was not solved. In my University project for my all modules Im getting the same error.
When I'm running the following query in PHP
$username = $_SESSION['username'];
$query = "SELECT id FROM user WHERE username = '$username'";
$qpost = mysqli_query($connection,$query);
$post_user = mysqli_fetch_assoc($qpost);
$forum_size = strlen($forum);
$dt = time();
$datetime = strftime("%Y-%m-%d %H:%M:%S", $dt);
$enteruser = $post_user['id'];
$Query = "INSERT INTO posts('id','user_id','post','date_added') VALUES(NULL,'$enteruser','$forum','$datetime')";`
I'm getting the following error,
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''id','user_id','post','date_added') VALUES (NULL,'3','erye yeyeyeyetyery ery ery '' at line 1
And when I was run it in mysql shell I'm getting the same error.
When I run that query in phpmyadmin as following,
INSERT INTO posts('id','user_id','post','date_added') VALUES (NULL,3,'erye yeyeyeyetyery ery ery ','2015-07-24 18:53:48');
I'm getting the same error. Can you please help me to solve this.I checked the query in every way I can adn error remains. I cant go forward withour solving this! Thank you for your help!
You don't need apostrophes on your table headers.
$username = $_SESSION['username'];
$query = "SELECT id FROM user WHERE username = '$username'";
$qpost = mysqli_query($connection,$query);
$post_user = mysqli_fetch_assoc($qpost);
$forum_size = strlen($forum);
$dt = time();
$datetime = strftime("%Y-%m-%d %H:%M:%S", $dt);
$enteruser = $post_user['id'];
$Query = "INSERT INTO `posts` (id, user_id, post, date_added) VALUES (NULL,'$enteruser','$forum','$datetime')";
Given id is primary-key and auto-increment, you can exclude it. You can also use native Mysql function now() for date_added
$Query = "INSERT INTO `posts` (user_id, post, date_added) VALUES ('$enteruser','$forum',now())";
Try this...
$username = $_SESSION['username'];
$query = "SELECT id FROM user WHERE username = '$username'";
$qpost = mysqli_query($connection,$query);
$post_user = mysqli_fetch_assoc($qpost);
$forum_size = strlen($forum);
$dt = time();
$datetime = strftime("%Y-%m-%d %H:%M:%S", $dt);
$enteruser = $post_user['id'];
$Query = "INSERT INTO posts ('user_id','post','date_added') VALUES('$enteruser','$forum','$datetime')";`
I've been trying to get this INSERT to work correctly, so I worked through the undefined variable and index problems and now I think I am nearly there.
Below is the code:
<?php
session_start();
require "../dbconn.php";
$username = $_SESSION['username'];
$query1 = "SELECT user_table.user_id FROM user_table WHERE user_table.username ='".$username."'";
$query2 = "SELECT department.department_id FROM department, user_table, inventory
WHERE user_table.user_id = department.user_id
AND department.department_id = inventory.department_id";
//Copy the variables that the form placed in the URL
//into these three variables
$item_id = NULL;
$category = $_GET['category'];
$item_name = $_GET['item_name'];
$item_description = $_GET['item_description'];
$item_quantity = $_GET['quantity'];
$item_quality = $_GET['quality'];
$item_status = NULL;
$order_date = $_GET['order_date'];
$invoice_attachment = NULL;
$edit_url = 'Edit';
$ordered_by = $username;
$user_id = mysql_query($query1) or die(mysql_error());
$department_id = mysql_query($query2) or die(mysql_error());
$price = $_GET['price'];
$vat = $_GET['vat%'];
$vat_amount = $_GET['vat_amount'];
$create_date = date("D M d, Y G:i");
$change_date = NULL;
//set up the query using the values that were passed via the URL from the form
$query2 = mysql_query("INSERT INTO inventory (item_id, category, item_name, item_description, item_quantity, item_quality, item_status, order_date,
invoice_attachment, edit_url, ordered_by, user_id, department_id, price, vat, vat_amount, create_date, change_date VALUES(
'".$item_id."',
'".$category."',
'".$item_name."',
'".$item_description."',
'".$item_quantity."',
'".$item_quality."',
'".$item_status."',
'".$order_date."',
'".$invoice_attachment."',
'".$edit_url."',
'".$ordered_by."',
'".$user_id."',
'".$department_id."',
'".$price."',
'".$vat."',
'".$vat_amount."',
'".$create_date."',
'".$change_date."')")
or die("Error: ".mysql_error());
header( 'Location:../myorders.php');
?>
Error:
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'VALUES( '', 'adasd', 'dsadsa', 'dsad', 'sadsad', '' at line 2
Could anyone please let me know where I am going wrong? :(
Been staring at this for 3-5 hours already :(
You are not actually trying to insert any data into your table. You only craft and assign the query in string form to a variable. You need to use the function mysql_query to actually run the code.
As pointed out you will also have to specify the columns you are inserting data into in the MySQL query if you don't supply data for every column (in the correct order). Here you can look at the MySQL insert syntax.
I would also urge you to look into using the MySQLi or the MySQL PDO extensions for communicating with your MySQL database since the MySQL extension is deprecated. Look here for additional information and comparisons.
Here, you only assign the values to the $query var:
$query = "INSERT INTO inventory VALUES (
'".$item_id."',
'".$category."',
'".$item_name."',
'".$item_description."',
'".$quantity."',
'".$quality."',
'".$item_status."',
'".$order_date."',
'".$invoice_attachment."',
'".$edit_url."',
'".$ordered_by."',
'".$price."',
'".$vat."',
'".$vat_amount."',
'".$create_date."',
'".$change_date."')"
or die("Error: ".mysql_error());
You do not actually run the query.
try:
$query = mysql_query("INSERT INTO inventory (column_name1, column_name 2, column_name3 ... the column name for each field you insert) VALUES (
'".$item_id."',
'".$category."',
'".$item_name."',
'".$item_description."',
'".$quantity."',
'".$quality."',
'".$item_status."',
'".$order_date."',
'".$invoice_attachment."',
'".$edit_url."',
'".$ordered_by."',
'".$price."',
'".$vat."',
'".$vat_amount."',
'".$create_date."',
'".$change_date."')")
or die("Error: ".mysql_error());
Also, you should use mysqli_* or any other PDO as the mysql_* functions are deprecated
If you are not inserting in all columns you need to specify the columns you are going to insert. Like this:
INSERT INTO Table(Column1, Column6) VALUES (Value1, Value6)
You are missing the column names in your INSERT
I want to execute these queries
$q1 = "INSERT INTO t1 (id,desc) VALUES (1,'desc');" <br>
$q2 = "SET #last_id = LAST_INSERT_ID();" <br>
$q3 = "INSERT INTO t2 (parentid,desc) VALUES (#last_id, 'somedesc');"<br>
Will this work correctly 3 mysqli_query something like this?
$res = mysqli_query($q1);
$res2 = mysqli_query($q2);
$res3 = mysqli_query($q3);
To start, desc is a MySQL reserved word
http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
and must be wrapped in backticks if you're going to decide on using it, without renaming it to something else than desc, say description for instance.
Therefore, you will need to change it to the following, assuming your DB connection is established, and using $con as an example, which you haven't shown us what your DB connection is.
$q1 = "INSERT INTO t1 (id,`desc`) VALUES (1,'desc')";
$q2 = "SET #last_id = LAST_INSERT_ID()";
$q3 = "INSERT INTO t2 (parentid,`desc`) VALUES (#last_id, 'somedesc')";
minus all of your <br> tags, since you are inside PHP, unless that wasn't part of your code, but in trying to format your code in your question.
Sidenote: Your semi-colons were misplaced.
and passing DB connection to your queries:
$res = mysqli_query($con,$q1);
$res2 = mysqli_query($con,$q2);
$res3 = mysqli_query($con,$q3);
Plus, adding or die(mysqli_error($con)) to mysqli_query() to check for possible errors in your queries.
I've got a PHP/MySQL script that is yielding strange results on a date field. All along the process, my dates are fine until the very end. The final result has every entry in the date field as '0000-00-00'. I'm totally stuck and don't know what else to do. I can tell that this is an issue with PHP not interpreting this as a date, but I don't know how to fix it. Here is my code:
$sql = "CREATE TABLE temp_workouts (my_date date, sg_id int(11), loc_id int(11))";
$result = mysql_query($sql);
if (!$result) {
$tag_success = "failure";
$tag_message = mysql_error();
echo encodeJSON($tag_success, $tag_message);
die();
}
$sql = "SELECT * FROM my_table";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$my_date = $row['my_date'];
echo $my_date . " "; //<--this output looks perfect
$sql = "INSERT INTO temp_table (my_date) VALUES ($my_date)";
$result2 = mysql_query($sql);
}
die();
When I flip over to MyPHPAdmin and look at the table, the entire column my_date contains '0000-00-00'. How can I get PHP to recognize this as a 'Y-m-d' formatted date? Thanks. I appreciate any help.
I suspect the issue is that you haven't enclosed a string literal in single quotes:
INSERT INTO temp_table (my_date) VALUES ('$my_date')
^--- ^--- string literals in single quotes
Otherwise, the statement is probably something like:
... VALUES (2013-08-22)
MySQL isn't converting that into a valid date, issuing a warning message, and inserting a "zero" date.
Your immediate problem is that you don't use quotes around date values in your insert statement.
Change
$sql = "INSERT INTO temp_table (my_date) VALUES ($my_date)";
to
$sql = "INSERT INTO temp_table (my_date) VALUES ('$my_date')";
^ ^
Now, you can just use INSERT ... SELECT syntax to achieve your goal in one go
INSERT INTO temp_table (my_date)
SELECT my_date
FROM my_table
Therefore this part of your code
$sql = "SELECT * FROM my_table";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$my_date = $row['my_date'];
echo $my_date . " "; //<--this output looks perfect
$sql = "INSERT INTO temp_table (my_date) VALUES ($my_date)";
$result2 = mysql_query($sql);
}
can be changed to
$sql = "INSERT INTO temp_table (my_date)
SELECT my_date FROM my_table";
$result2 = mysql_query($sql);
On a side note: Consider switching to either PDO or MySQLi and use prepared statements.
Try this one...This will re-convert it to date, and then save..
$dt = strtotime($row['my_date']);
$date = date("Y-m-d",$dt);
$sql = "INSERT INTO temp_table (my_date) VALUES ({$date})";