Error: Unknown column 'x' in 'field list' - php

I'm having some trouble inputting some data into a table.
I'm retrieving some values from a form and inputting them to a table, but this error shows up every time:
Error: Unknown column 'planner_id' in 'field list'
<?php
session_start();
include 'conexion_data.php';
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$teacherid = $_POST["teacherid"];
$plannerid = $_POST["plannerid"];
$yeargroup = $_POST["yeargroup"];
$subject = $_POST["subject"];
$planner_event = htmlspecialchars($_POST["event_comment"]);
$event_date = $_POST["event_date"];
echo "$teacherid $plannerid $yeargroup $planner_event $event_date <br/><br />";
if (empty($event_date) or empty($planner_event)) {
echo "One of the fields was left blank! <br />";
} else {
$sql = "INSERT INTO subject_directorio (planner_id, teacher_id, subject, yeargroup, date, comment ) VALUES ('$plannerid', '$teacherid', '$subject', '$yeargroup', '$event_date', '$planner_event')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
} else {
/* header('Location: user_area.php'); */
echo "Data was inputed to DB";
mysqli_close($con);
}
}
?>

It's very straight
while you are getting this type error :{Error: Unknown column 'planner_id' in 'field list'}
Troubleshoot first step will be Just Describe The Table [subject_directorio]
Desc subject_directorio and check planner_id is exist or not. According to to the error
subject_directorio not holding any column called as planner_id
Hope it helps!!

It's self explanatory that your table doesn't have a column planner_id. Even if you see that it has, you may have trialing spaces before or after planner_id in the column name. Check carefully.

Database
You are using wrong way how to connect to database and fetch its data.
Because you database may be hacked using SQL Injection
The right way how to do this is:
Using PDO
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
For error catching:
try {
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
And data fetching:
$id = 5;
try {
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
$stmt->execute(array('id' => $id));
while($row = $stmt->fetch()) {
print_r($row);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
Using Mysqli
$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with $row
}
And your problem
I think problem is in your query and binding params to it.So try to use proper way as I shown you, and then show us results.
SQLFiddle

Related

getting error for mysql when i am using if else in there

getting error for mysql when i am using if else in there. i dont know what should i do and when i am using duplicate condition to update then it not woring i am not be able to find where is error
this is the error which is i am getting.
ERROR:SQLSTATE[HY093]: Invalid parameter number: parameter was not
defined
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt=$conn->prepare("SELECT uniqueid FROM hotelcarttemp WHERE uniqueid=:uniqueid");
$stmt->execute(array(':uniqueid'=>$uniqueid));
$count=$stmt1->rowCount();
echo "count-".$count;
if($count>0)
{
$sql = "UPDATE hotelcarttemp SET `hotelname`='".$hotelname."',`roomtype`='".$roomtype."',`checkin`='".$checkin."',`checkout`='".$checkout."',`Country`='".$Country."',`Destination`='".$Destination."',`price`='".$price."' WHERE uniqueid='".$uniqueid."'";
echo "sql- ".print_r($sql);
$stmt = $conn->prepare($sql);
// echo print_r($stmt);
$stmt->execute();
}
else
{
$sql = "INSERT INTO hotelcarttemp (timestamp, packageid, uniqueid, hotelname, roomtype, checkin, checkout, Country, Destination, hoteldetail, price)
VALUES ('"
.$timestamp."','"
.$packageid."','"
.$uniqueid."','"
.$hotelname."','"
.$roomtype."','"
.$checkin."','"
.$checkout."','"
.$Country."','"
.$Destination."','"
.addslashes($hoteldetail)."','"
.$price."'
)";
// echo "sql- ".print_r($sql);
$stmt = $conn->prepare($sql);
// echo print_r($stmt);
$stmt->execute();
}
}
catch(PDOException $e) {
echo 'ERROR:' . $e->getMessage();
} here
Your SELECT query where condition is WHERE uniqueid=:uniqueid
And you are binding username to it
$stmt->execute(array(':username'=>$uniqueid));//:username invalid parameter
Change this to
$stmt->execute(array(':uniqueid'=>$uniqueid));

PDO Read From Database

I have made a code using PDO to read a table from a database.
I try to echo my result but I get a blank page without error.
My Code Is:
<?php
include 'config.php';
id = "264540733647332";
try {
$conn = new PDO("mysql:host=$hostname;dbname=mydata", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$result = $conn->query("SELECT * FROM mytable WHERE id='".$id."';");
if ($result->fetchColumn() != 0)
{
foreach ( $result->fetchAll(PDO::FETCH_BOTH) as $row ) {
$Data1 = $row['Data1'];
$Data2 = $row['Data2'];
echo $Data2;
}
}
?>
But the echo is empty without any error.
What I am doing wrong?
Thank you All!
Few things to change:
dont forget $
if your going to catch the error, catch the whole pdo code
You can use rowCount() to count the rows
echo something if the record count is 0
include 'config.php';
$id = "264540733647332";
try {
$conn = new PDO("mysql:host=$hostname;dbname=mydata", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result = $conn->query("SELECT * FROM mytable WHERE id='".$id."';");
if ($result->rowCount() != 0)
{
$row = $result->fetch(PDO::FETCH_BOTH);
echo $row['Data1'];
echo $row['Data2'];
}else{
echo 'no row found';
}
}catch(PDOException $e){
echo "error " . $e->getMessage();
}
Also use prepared statements for example:
$result = $conn->prepare("SELECT * FROM mytable WHERE id=:id");
$result->execute(array(':id'=>$id));
I'm assuming there's only one record with the id "264540733647332".
The issue is that $result->fetchColumn() call reads first row in the result set and then advances to the next result. Since there's only one of the results, the subsequent call to $result->fetchAll() returns nothing, hence no data displayed.
To fix this replace fetchColumn with rowCount:
<?php
include 'config.php';
id = "264540733647332";
try {
$conn = new PDO("mysql:host=$hostname;dbname=mydata", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$result = $conn->query("SELECT * FROM mytable WHERE id='".$id."';");
if ($result->fetchColumn() != 0)
{
foreach ( $result->fetchAll(PDO::FETCH_BOTH) as $row ) {
$Data1 = $row['Data1'];
$Data2 = $row['Data2'];
echo $Data2;
}
}
?>

How to select from a dynamic column through a variable with PDO?

I have a PHP variable $col with a column name. I want to create a query with PDO, that selects the value of that column. I know how to use bindValue(), and tried the following:
$db = new PDO('mysql:host='. $db_host . ';dbname=' . $db_name . ';charset=utf8', $db_user, $db_password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
function get_user($id, $column){
$sql = "
SELECT :col
FROM users
WHERE `id` = :id;";
try {
$st = $db->prepare($sql);
$st->bindValue('col', $column, PDO::PARAM_STR);
$st->bindValue(':id', $id, PDO::PARAM_INT);
$st->execute();
$result = $st->fetch();
return $result;
} catch (PDOException $e) {
echo "Database query exception: " . $e->getMessage();
return false;
}
}
That results in the following exception: Database query exception: SQLSTATE[42S22]: Column not found: 1054 Unknown column ''name'' in 'field list' for $col = 'name'. Of course, the column name does exist.
It works well on WHERE = :value, but I can not get it working for a column. How to achieve this?
Addition: I did found the function bindColumn(), but I think that does the opposite, binding the column name to a PHP variable instead of binding a variable to the column.
You can use an array of allowed column names to sanitize the query.
$allowed_columns = array('name', 'type1',etc);//Array of allowed columns to sanatise query
Then check if column name is in array.
if (in_array($column, $allowed_columns)){
$result= get_user($id, $column);
}
function get_user($id, $column){
$sql = "
SELECT $column
FROM users
WHERE `id` = :id;";
try {
$st = $db->prepare($sql);
$st->bindValue(':id', $id, PDO::PARAM_INT);
$st->execute();
$result = $st->fetch();
return $result;
} catch (PDOException $e) {
echo "Database query exception: " . $e->getMessage();
return false;
}
}
I would use array_intersect something like a sanitizing function that would extract only the allowed fields. Example:
function get_fields_allowed($input_fields,$allowed){
$input_fields=explode(",",$input_fields);
$allowed=explode(",",$allowed);
return array_intersect($allowed,$input_fields);
}
$select_fields=$_POST["fields"]; //example: "id,name,email"
$fields=get_fields_allowed ($select_fields, "id,name" ) ;
So you then use the $fields as in:
$sql="Select $fields FROM [table] WHERE id=:id etc...";

Can't retrieve data from MS SQL with PDO

I use PDO on my local computer to connect to MS SQL server to use prepare statements. The driver is installed properly and can connect to database. Here's the code:
try {
$con = new PDO("sqlsrv:Server={$host};Database={$db_name}", $username, $password);
}
catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}
$query = "SELECT TOP 10 ClientID FROM CLIENT";
$stmt = $con->prepare($query);
$stmt->execute();
$num = $stmt->rowCount();
print $num;
From SSMS the query returns as it should, but nothing from the code as it prints -1 as the result of $num. If i change the query to SELECT ##VERSION it prints the version properly but not my query. My query is right from SSMS and PDO can connect to server but can't figure out where the problem is it's so frustrating please help.
can you try :
try {
$con = new PDO("sqlsrv:Server={$host};Database={$db_name}", $username, $password);
}
catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}
$query = "SELECT TOP 10 ClientID FROM CLIENT";
$stmt = $con->prepare($query);
$stmt->execute();
$rows = $stmt->fetchAll();
$num = count($rows);
print $num;
// To print results :
foreach ($rows as $row) {
echo $row["ClientID"] . "<br/>";
}

mysql AND operator not working for passing multiple parameter

try {
$conn = new PDO('mysql:host=localhost;dbname=dbtable', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$data = $conn->prepare('SELECT * FROM table WHERE name = ' . $conn->quote($name).' AND id = '. $conn->quote($id));
$data->execute();
while($row = $data->fetch(PDO::FETCH_ASSOC)) {
echo "ID : ".$row['id'].'</br>';
echo "Name : ".$row['name'].'</br>';
echo "Name : ".$row['header'].'</br>';
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
The above works for one parameter (name) but when i use AND operator it shows no results. URL is as given below.
http://www.mywebsite.com/page.php?id=2&name=xyz
As mentioned in the documentation, you're strongly advised to use parametrized queries, like so:
$data = $conn->prepare('SELECT * FROM table WHERE name = :name AND id = :id');
$data->bindParam(":name", $name);
$data->bindParam(":id", $id);
If this still does not work, I would suggest running a similar query directly against your database, through either phpMyAdmin or the MySQL Workbench, to verify that the query actually returns anything.
$data = $conn->prepare("SELECT * FROM table WHERE name = '$name' AND id <> '$id' ");
The above code worked for me.

Categories