I'm using Zend Framework and MySql to create my web-application. My SQL-code is the following at the moment:
public static function newTestResult($testId, $accountId, $score, $deviation, $averageTime)
{
try
{
$db = self::conn();
$statement = "INSERT INTO test_results(test_id, test_person_id, score, standard_deviation, average_answer_time, created_at)
VALUES(" . $testId . ", " . $accountId . ", " . $score . ", " . $deviation . ", " . $averageTime . ", NOW())";
$db->query($statement);
$db->closeConnection();
}
catch(Zend_Db_Exception $e)
{
error_log($e->getMessage());
}
}
Now what I'm asking is: How can I get the just inserted row to a variable in PHP? I would want to get my hands on the id-value what MySql is creating automatically for the row.
Here is my table code:
CREATE TABLE test_results(
id int UNSIGNED AUTO_INCREMENT PRIMARY KEY,
test_id int UNSIGNED NOT NULL,
test_person_id int UNSIGNED NOT NULL,
score float UNSIGNED NOT NULL,
standard_deviation float UNSIGNED NOT NULL,
average_answer_time float UNSIGNED NOT NULL,
removed boolean NOT NULL DEFAULT 0,
created_at datetime) CHARACTER SET utf8 COLLATE utf8_general_ci;
Take a look at the MySQL function "LAST_INSERT_ID()"
See also this forum for more detail on the methods available.
http://forums.phpfreaks.com/topic/188084-get-last-mysql-id-using-zend-frameworks/
In "plain" PHP, I usually use the mysql_ functions. The mysql_insert_id() function returns the key of the last row inserted. I'm not advocating this over using the Zend way, just giving context:
mysql_query("INSERT INTO ... query");
$id = mysql_insert_id();
Then reference that ID in writing other queries related to that inserted row.
This should give you the last insert id from the last query made.
$db->lastInsertId()
try this:
$query="SELECT id FROM test_results WHERE test_id=$testId";
$id=$db->query($query);
I assume this is what you're looking for, otherwise you can change the WHERE condition to whatever you need.
From the MySQL manual: "If you insert a record into a table that contains an AUTO_INCREMENT column, you can obtain the value stored into that column by calling the mysql_insert_id() function." This refers to the C function.
In the PHP manual, you are suggested to use the PDO function instead. http://php.net/manual/en/function.mysql-insert-id.php PDO::lastInsertId
And apparently, "The insert() method on Zend_Db_Table will return the value of the last insert id." http://osdir.com/ml/php.zend.framework.db/2007-04/msg00055.html
To get last two records from any table you can use the following query
SELECT * FROM aa WHERE ID IN(
(SELECT COUNT(*) FROM aa),
(SELECT COUNT(*) FROM aa)-1
)
Related
I am having trouble inserting null values into date fields into a MySQL table.
Here is the insert query:
$query = 'INSERT INTO table (column_s1, column_s2, column_d1, column_d2)
VALUES ("'.$string1.'", "'.$string2.'", '.$date1.', '.$date2.')';
Columns s1 and s2 take string values and d1 and d2 take dates. When I run this query with only the string fields, there is no problem.
The date values can be either set or null, so I have not included the quotation marks in the query, but have instead added them to the variable earlier on. This is the php code I am using to set the date values:
if (empty($date1)){
$date1 = NULL;
}
else{
$date1part = explode("/",$date1);
$date1 = '"'.$date1part[2].'/'.$date1part[1].'/'.$date1part[0].'"';
}
When the date values are all set, the record is inserted correctly. However, when either of the dates is null, nothing is inserted.
Why can't I just insert null values into MySQL like this?
Try this:
$query = "INSERT INTO table (column_s1, column_s2, column_d1, column_d2)
VALUES ('$string1', '$string2', " . ($date1==NULL ? "NULL" : "'$date1'") . ", " . ($date2==NULL ? "NULL" : "'$date2'") . ");";
so for example if you put this into query:
$string1 = "s1";
$string2 = "s2";
$date1 = NULL;
$date2 = NULL;
result should be:
INSERT INTO table (column_s1, column_s2, column_d1, column_d2) VALUES ('s1', 's2', NULL, NULL);
You should convert the null variable into a NULL string first
Like this:
if(is_null($date1)){
$date1 = 'NULL';
}
If you are using a MySQL date column, you must also specify that it should hold null when creating it, like this:
CREATE TABLE `table` (
id INT NOT NULL AUTO_INCREMENT,
date DATE NULL DEFAULT NULL,
PRIMARY KEY(id)
)
It is also very important that you perform the query with bound parameters, for example using pdo
http://www.php.net/manual/en/pdo.construct.php
http://php.net/manual/en/pdo.prepared-statements.php
How do I insert NULL values using PDO?
Something like this:
$query = 'INSERT INTO table (column_s1, column_s2, column_d1, column_d2)
VALUES (?, ?, ?, ?)';
$stmt = $db->prepare($query);
$stmt->execute(array($string1,$string2,$date1,$date2));
If NULL does not work, just pass your date as "0000-00-00":
$chequeDate = "0000-00-00";
Backslash N is another way to express NULL in MySQL.
Try putting the value (backslash N): \N into one of the parameters like this:
$data1 = "\N";
$sql="insert into tablename set column_s1='" . $data1 .
"', column_s2='" . data2 .
"', column_s3='" . $data3 . "'";
Reference: http://dev.mysql.com/doc/refman/5.1/en/load-data.html
In Derby, If you want to insert values except the ones you have declared Null (column_d1, column_d2), sql:
INSERT INTO DB.table (column_s1, column_s2) VALUES ('s1', 's2');
Probably answer is unneeded at this moment, but I found solution exactly I have been searching. Use an Expression to pass NULL like this:
['some_date_to_update' => new Expression('NULL')]
Hence, MySQL will understand what you want, and save (NULL) in DB instead of storing 0-dates. Hope this will help somebody.
In Mysql DATE data type Default NULL means
Some version set as 0000-00-00
Some version set as 1970-01-01
Years later, if someone is still experiencing this issue, you want to use PDO and bind the variables, everything will be taken care of no need to handle the null variables yourself.
So, a snippet of my code which is resulting in an error is :
$con = mysqli_connect('localhost', 'root', '', 'notesDB');
if(isset($_POST['tableName'])) {
$tName = htmlentities($_POST['tableName']);
$firstQuery = mysqli_query($con,"INSERT into notes(Title) VALUES( '$tName'); CREATE TABLE $tName(id int NOT NULL AUTO_INCREMENT, Title varchar(20) NOT NULL, Description varchar(100), PRIMARY KEY(id));");
if($firstQuery){
header("Location: create2.php");
}
else
echo mysqli_error($con);
}
The output of this is :
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 'CREATE TABLE test1(id int NOT NULL AUTO_INCREMENT, Title varchar(20) NOT NULL, D' at line 1
Well, the funny thing is that the exact code (except the variable - I just removed the $ sign) executed perfectly in phpMyAdmin.
Also, to prove that there is nothing really wrong with the php, the query executed without any error when it was only the INSERT query (and not the CREATE query).
mysqli_query can only perform one query at a time.
Try mysqli_multi_query instead.
As an aside creating tables on the fly is usually a sign of larger design issues. Schema should be relatively static while data should be dynamic.
You are trying to run two separate queries at a time in the code, which you can't run like that. You have to run them separately like below:
$con = mysqli_connect('localhost', 'root', '', 'notesDB');
if(isset($_POST['tableName'])) {
$tName = htmlentities($_POST['tableName']);
$firstQuery = mysqli_query($con,"INSERT into notes(Title) VALUES( '$tName')");
$secondQuery = mysqli_query("CREATE TABLE '$tName' (id int NOT NULL AUTO_INCREMENT, Title varchar(20) NOT NULL, Description varchar(100), PRIMARY KEY(id));");
if($firstQuery || $secondQuery){
header("Location: create2.php");
}
else
echo mysqli_error($con);
}
Your database architecture is wrong.
You shouldn't create tables on the fly. So, you have only register whatever new entity with simple regular INSERT query. And then use this entity's id to link records from another [already existing] table.
if(isset($_POST['tableName'])) {
$stm = mysqli_prepare($con,"INSERT into notes(Title) VALUES(?)");
$stm->bind_param("s",$_POST['tableName']);
$stm->execute();
}
I have a very basic select statement that is causing a column unknown error. The problem with the query happens when I try to use a character instead of just numbers in the variable. Wondering if it has anything to do with Collation.
Here's what I have so far:
$titleno=$_REQUEST['title_no'];
$titleno=mysql_real_escape_string($titleno);
$titleno = utf8_decode($titleno); //tried without this before but didn't work
$query="SELECT * FROM `Titles` WHERE `title-no` = '".$titleno."'";
//tried various versions of this query - left it as single quotes as that seems to be the correct way. This only fails when a character is entered. Numbers work fine.
echo "query - <br> $query <br>";
$get_title_result=mysql_query($query) or die(mysql_error());
//here I get the unknown column name error - MySQL treats the titleno as the column name
Echo output:
SELECT * FROM `Titles` WHERE `title-no` = '1234566d'
Unknown column '1234566d' in 'where clause'
If I didn't use the 'd' in title-no, it works fine....Also, I tried a different column name that doesn't have the hyphen and still get the same behavior. The DB defines collation for title-no as latin1_swedish_ci. (This problem doesn't occur when I paste the query into mysqladmin)
Here's the table definition:
CREATE TABLE `Titles` (
`id` int(11) NOT NULL auto_increment,
`title-no` varchar(15) NOT NULL,
UNIQUE KEY `title-no` (`title-no`),
KEY `id` (`id`)
) ENGINE=MyISAM
AUTO_INCREMENT=9090949 DEFAULT CHARSET=latin1 AUTO_INCREMENT=9090949 ;
RESOLVED: The issue was not with this query. It was with a subsequent query. I was confused because I was only echoing this query. My bad. Thank you all for your support! :)
Try with:
$query = "SELECT * FROM Titles WHERE `Titles`.`title-no` = '" . $titleno . "'";
Here is a quick conversion to statement-based query (which is using MySQLi, adapt as necessary, your code or this example). The assumption is that the underlying prepared statement engine knows that you cannot specify a column name with placeholders in a prepared statement, so it should be passing it correctly (here's hoping :-)
$titleno=$_REQUEST['title_no'];
$statement=mysqli_prepare($your_mysqli_link, "SELECT `id` FROM `Titles` WHERE `title-no` = ?");
mysqli_stmt_bind_param($statement, 's', $titleno);
mysqli_stmt_execute($statement);
mysqli_stmt_bind_result($statement, $found_id);
mysqli_stmt_fetch($statement);
echo "found id: $found_id";
I'm trying to get the auto incremented column of a row. The code will explain, but basically I'm trying to insert a row into a table called orders, and then I want to get the auto incremented number.
This is my PHP.
<?php
$db = DBConnection::connect();
$q = "INSERT INTO orders (customerid, orderdate) VALUES (".$customerid.", CURRENT_TIMESTAMP)";
$ps = $db->prepare($q);
$ps->execute();
$db = null;
echo mysql_insert_id();
?>
At this stage all I really want to do is echo out the auto number.
This is my structure
CREATE TABLE `orders` (
`orderid` int(25) NOT NULL AUTO_INCREMENT,
`customerid` int(11) NOT NULL,
`orderdate` date DEFAULT NULL,
PRIMARY KEY (`orderid`),
KEY `orderid` (`orderid`)
)
Any help would be greatly appreciated, thank you :)
DBConnection != MySQL
You can't use functions from different libraries like that. You must either change mysql_num_rows() to the DBConnection equivalent, or change the DBConnection stuff to mysql_*.
PDO is different from mysql_* functions.
Since you've used PDO, you must use the method lastInsertId() from the PDO object:
$db->lastInsertId();
Try adding
$ps->execute()
or die(mysql_error());
This may show any errors that the database query is generating
Trying to check if a name is already stored in the database from the login user. The name is a set of dynamic arrays entered by the user threw a set of dynamic form fields added by the user. Can some show me how to check and see if the name is already entered by the login user? I know my code can't be right. Thanks!
MySQL code.
SELECT *
FROM names
WHERE name = '" . $_POST['name'] . "'
AND userID = '$userID'
Here is the MySQL table.
CREATE TABLE names (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
userID INT NOT NULL,
name VARCHAR(255) NOT NULL,
meaning VARCHAR(255) NOT NULL,
PRIMARY KEY (id)
);
If $_POST['name'] is actually an array of strings, as you say, then try this PHP:
$namesString = '';
foreach ($i=0; $i < count($_POST['name']) $i++)
{
$namesString .= "'" . mysql_real_escape_string($_POST['name'][$i]) . "'";
if(isset($_POST['name'][$i + 1]) $nameString .= ', ';
}
With this query:
SELECT * FROM `names`
WHERE `name` IN ( $namesString )
AND `userID` = '$userID'
The query will return all the rows in which the name is the same as string in $_POST['name'].
First of all, if the userID field is unique, you should add a unique index on it in your table.
Also, watch out for SQL injection attacks!
Using something like this is much more secure:
$sqlQuery = sprintf('SELECT COUNT(id) AS "found" FROM names WHERE userID = "%s"', mysql_real_escape_string($_POST['name'], $conn));
This SQL query will return 1 row with 1 field (named found) which will return you the number of matched rows (0 if none). This is perfect if you only want to check if the userID exists (you don't need to fetch all data for this).
As for the dynamic array, you will have to post more information and I'll update my answer.
Meanwhile here are some usefull PHP functions that can help you do what you want:
For MySQL queries:
mysql_connect
mysql_real_escape_string
mysql_query
mysql_fetch_assoc
For your list of users:
explode
implode
Stated as you say, I'm quite sure the code does exactly what you are asking for. The SELECT should return the records that respond both to the name sent and the current user ID.
If you need some php code, here it is (should be refined):
$result = mysql_query('YOUR SELECT HERE');
if (!$result) {
die('ERROR MESSAGE');
} else {
$row = mysql_fetch_assoc($result));
// $row is an associative array whose keys are the columns of your select.
}
Remember to escape the $_POST.