MySQL Unknown column in where clause for simple select statement - php

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";

Related

Update a single row in SQL

I am having trouble with a really simple SQL statement: UPDATE.
I would only like to update the booking_date column in a specific row.
Here is the statement I'm using:
UPDATE `coupon-codes` SET `booking_id`=:timestamp WHERE `id` = :id
I'm using PDO named placeholders.
I always get an incorrect syntax error. What am I doing wrong?
Edit:
I tried without backticks:
UPDATE coupon-codes SET booking_id = :timestamp WHERE id = :id
Still doesn't work.
Here's the error message I'm getting:
Edit 2:
Here is the error message I'm getting when using backticks:
Edit 3:
For reference, here is an INSERT statement I used before, which works without any problems:
INSERT INTO `coupon-codes` (`code`, `date`) VALUES (:code, :date)
Edit 4:
Sorry, wrongly said some things in the comments, to clarify, see this:
I am using BACKTICKS everywhere. This is the query that doesnt work:
UPDATE `coupon-codes` SET `booking_date`=:timestamp WHERE `id` = :id
I also had a typo in the original question which had booking_id instead of booking_date field, but that doesn't matter, since I'm getting a SYNTAX ERROR.
Here is the PHP code I'm trying to run it with:
$stmt = $db->prepare("UPDATE `coupon-codes` SET `booking_date`=:timestamp WHERE `id` = :id");
$stmt->bindParam(':timestamp', $time);
$stmt->bindParam(':id', $id);
$stmt->execute();
Basic MySQL syntax:
'foo' - single-quotes. turns the quote word into a string literal
`foo` - backticks. used to escape table/fieldnames that happen to be reserved words
SELECT 'select' FROM ... -- select the literal word "select" from some table
SELECT `select` FROM ... -- select the field NAMED "select" from some table
SELECT select FROM ... -- syntax error - using a reserved word "select"
Given your error messages, you probably have one of the following:
UPDATE 'coupon-code' ... -- can't update a string. must specify a table name
UPDATE coupon-code ... -- math operation: coupon MINUS code - not a table name
Have you tried to use Predefined Constants (http://php.net/manual/en/pdo.constants.php);
Example:
$stmt = $db->prepare("UPDATE `coupon-codes` SET `booking_date`=:timestamp WHERE `id` = :id");
$stmt->bindParam(':timestamp', $time, PDO::PARAM_STR);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();

how to insert data with where cause

create table cmu_patient
( patient_id character varying(13) NOT NULL,
patient_hn character varying(7),
patient_fname character varying(50),
patient_lname character varying(50),
home_id integer,
CONSTRAINT cmu_patient_pkey PRIMARY KEY (patient_id),
CONSTRAINT Fk_home FOREIGN KEY(home_id)
REFERENCES cmu_home(home_id)
);
create table cmu_treatment
( treatment_id serial NOT NULL,
treatment_date date,
treatment_time time without time zone,
treatment_typecome character varying(100),
treatment_detail text,
patient_id character varying(13),
appointment_id character varying(5),
transfer_id character varying(5),
res_users_id integer,
CONSTRAINT cmu_treatment_pkey PRIMARY KEY (treatment_id),
CONSTRAINT Fk_patient FOREIGN KEY(patient_id)
REFERENCES cmu_patient(patient_id),
CONSTRAINT Fk_user_id FOREIGN KEY(res_users_id)
REFERENCES res_users(id)
);
$treatment_date = $GET_[...];
$treatment_time = $GET_[...];
$treatment_typecome = $GET_[...];
$treatment_note = $GET_[...];
$CID = $GET_[...];
this code -------- it's incorrect
INSERT INTO cmu_treatment(treatment_id, treatment_date, treatment_time,
treatment_typecome, treatment_detail, patient_id, appointment_id,transfer_id, res_users_id)
VALUES(NULL,'".$tratment_date."','".$treatment_time."','".
$treatment_typecome."','".$treatment_note."','".$CID."',NULL,NULL,NULL)
WHERE cmu_patient.patient_id = cmu_treatment.patient_id ;
i think that's wrong
i don't know if i want to write insert data into table with where cause i should write sql ?
thank :)
I suspect what you really want is an update, to change existing values in an existing record:
update cmu_treatment
set treatment_date = $treatment_date,
treatment_time = $treatment_time,
treatment_detail = $treatment_typecome,
treatment_note = $treatment_note
where patient_id = $CID;
(I'm leaving out the NULL values on the assumption that those shouldn't really change.)
If you do indeed want a new record, you can do:
INSERT INTO cmu_treatment(treatment_id, treatment_date, treatment_time,
treatment_typecome, treatment_detail, patient_id, appointment_id,
transfer_id, res_users_id
)
select NULL,'".$tratment_date."', '".$treatment_time."','".
$treatment_typecome."','".$treatment_note."','".$CID."', NULL, NULL, NULL;
You can write an INSERT statement populating target table with a SELECT statement. In the SELECT statement you can use WHERE condition.
So instead this query:
INSERT INTO table VALUES (....)
You must write:
INSERT INTO table
SELECT fields
FROM anothertable
WHERE condition
In your case, I think you must use an INSERT without WHERE condition if you want to insert only a row in your treatment table.
Tell me if you want to know further info
EDIT After comment
IMHO your statement must be:
INSERT INTO cmu_treatment
(treatment_id, treatment_date, treatment_time,
treatment_typecome, treatment_detail, patient_id, appointment_id,
transfer_id, res_users_id)
VALUES
(NULL,'".$tratment_date."','".$treatment_time."',
'".$treatment_typecome."','".$treatment_note."','".$CID."',NULL,NULL,NULL)
INSERT INTO `cmu_treatment`(`treatment_id`, `treatment_date`, `treatment_time`,
`treatment_typecome`, `treatment_detail`, `patient_id`, `appointment_id`,`transfer_id`, `res_users_id`)
VALUES(NULL,'".$tratment_date."','".$treatment_time."','".
$treatment_typecome."','".$treatment_note."','".$CID."',NULL,NULL,NULL)
WHERE `cmu_patient.patient_id` = `cmu_treatment.patient_id` ;
And you don't need (table name).(column).
Is this Inside "" ? If yes then you don't need '".$tratment_date."' you can use only '' so your code will look like this.
INSERT INTO cmu_treatment(treatment_id, treatment_date, treatment_time,
treatment_typecome, treatment_detail, patient_id, appointment_id,transfer_id, res_users_id)
VALUES(NULL,'$tratment_date','$treatment_time','
$treatment_typecome','$treatment_note','$CID',NULL,NULL,NULL)
WHERE `patient_id` = patient_id ;
And finally what is patient_id? Is it variable? If not IT MUST BE. Don't give same names to different things.

PDOException - SQLSTATE[42S22]: Column not found: 1054 Unknown column 'MyDataValue' in 'where clause'

First of all, I've seen this in numerous places on Stack Overflow, but I still can't get this error to go away. Some information about this particular issue is below:
The below code is the MySQL code which I used to create the table (where I want to insert the particular record):
CREATE TABLE IF NOT EXISTS `energymeter`.`Node` (
`node_id` INT NOT NULL AUTO_INCREMENT ,
`node_name` VARCHAR(7) NOT NULL ,
PRIMARY KEY (`node_id`) ,
UNIQUE INDEX `node_name_UNIQUE` (`node_name` ASC) )
ENGINE = InnoDB;
The below code is where it seems to be failing (resulting in the error given in the thread title):
$node_name_value = $line_of_text[2]; // In this example, the value would be 'MyDataValue'
$insert_demand_record = $conn->prepare("INSERT INTO Demand (date, time, trading_period, demand_value, Node_node_id) VALUES (STR_TO_DATE('$date', '%d %M %Y'), STR_TO_DATE('$time', '%k:%i:%s'), $trading_period, $demand_value, (SELECT Node.node_id FROM Node WHERE Node.node_name = $node_name_value))");
$insert_demand_record->execute();
EDIT: After further testing, changing the above code doesn't work, but if I alter the code below (with a change to the '$node_name_value value), I see the value changing in the browser (e.g. if I set $node_name_value to 'SomeRandomValue', the error would be something like 'Unknown column 'SomeRandomValue'...
//Ignoring items of same name that already exist (since there is a UNIQUE constraint
//on the 'node_name' column.
$insert_stmt = $conn->prepare('INSERT IGNORE INTO Node(node_name) VALUES(:node_value)');
//Bind the node name with the query
$node_name_value = $line_of_text[2];
$insert_stmt->bindParam(':node_value', $node_name_value);
//Execute PDO insert statement
$insert_stmt->execute();
If anyone could help me out with this issue, that would be much appreciated!
The following code managed to make things work for me...
$insert_demand_record = $conn->prepare("INSERT INTO Demand (date, time, trading_period, demand_value, Node_node_id) VALUES (STR_TO_DATE('$date', '%d %M %Y'), STR_TO_DATE('$time', '%k:%i:%s'), $trading_period, $demand_value, (SELECT Node.node_id FROM Node WHERE Node.node_name = :node_name_value))");
$insert_demand_record->bindValue(':node_name_value', $node_name_value, PDO::PARAM_STR);
$insert_demand_record->execute();
Thanks to the user 'Burhan Khalid' for suggesting the edit - will now be using prepared statements more...

How to get just inserted row from MySql to a php variable?

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
)

Query won't insert username into database

So I've got this query:
mysql_query(
"INSERT INTO wall_post (post,username,userip,date_created)
VALUES(
'".checkValues($_REQUEST['value'])."',
'".$_SESSION['user']."',
'".$userip."',
'".strtotime(date("Y-m-d H:i:s"))."'
)"
);
and I also tried to make the query this way:
mysql_query(
"INSERT INTO wall_post (post,username,userip,date_created)
VALUES(
'".checkValues($_REQUEST['value'])."',
$_SESSION['user'],
'".$userip."',
'".strtotime(date("Y-m-d H:i:s"))."'
)"
);
I don't see any error message from the database when the insert fails.
It won't insert the username into the database but when I echo $_SESSION['user'] it would still show me its content, please I would appreciate some help.
The table structure is:
CREATE TABLE wall_post (
p_id int(11) NOT NULL auto_increment,
username varchar(50) NOT NULL,
post varchar(255) NOT NULL,
image varchar(50) NOT NULL,
date_created int(11) NOT NULL,
userip varchar(200) NOT NULL, PRIMARY KEY (p_id)
)
The value which contains $_SESSION['user'] is theil, it doesn't have any special character, but if I replace $_SESSION['user'] with a string like $user = "test"; it will insert the value "test" into the database
mysql_query for insert statements either returns True on success or False on error. You have to check the return value if it was successful, and if it wasn't successful get the error via mysql_error:
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
It should be easy to fix from there.
The image column is set to NOT NULL, but you are not inserting anything into it. I suspect removing the NOT NULL clause, or setting a default value for the column might fix your problem.
Additional tip. use MYSQLS NOW() for the date. Just let the database handle that bit :)
just check what the value is and make sure there are no special characters in there.
You can also try "'.mysql_real_escape_string($_SESSION['user']).'"
the problem might be special characters.
From all the comments try this
$name = isset($_REQUEST['user']) ? $_REQUEST['user'] : '';
mysql_query('INSERT INTO wall_post (post,username,userip,date_created) VALUES("'..checkValues($_REQUEST['value']).'",
"'.$name.'","'$ipAddress'","'.$timestamp.'")');
From one of your comments above, I learnt that if you echo your query, it shows as
INSERT INTO wall_post (post,username,userip,date_created)
VALUES('','theil','127.0.0.1','1309975742')
Did you do this echo just before the statement where you run the query? If not, I'd request you to please do the echo just before the call, like this:
echo "INSERT INTO wall_post (post,username,userip,date_created) VALUES(
'".checkValues($_REQUEST['value'])."',
'".$_SESSION['user']."',
'".$userip."',
'".strtotime(date("Y-m-d H:i:s"))."')";
mysql_query("INSERT INTO wall_post (post,username,userip,date_created) VALUES(
'".checkValues($_REQUEST['value'])."',
'".$_SESSION['user']."',
'".$userip."',
'".strtotime(date("Y-m-d H:i:s"))."')"
);
Your query seems to be absolute fine and should run fine. The only reason why username might not be saving into the database is that `$_SESSION['user'] is empty or does not exist.
Did you try running this echoed query - INSERT INTO wall_post (post, username, userip, date_created) VALUES('', 'theil', '127.0.0.1', '1309975742') - directly into MySQL, either on the prompt or any other client that you might be using?

Categories