PHP and SQLSTate error - php

I have this PHP code:
<?php
require_once('../include/inner_global.php');
$id=$_REQUEST['id'];
$hostdb="localhost";
$namedb="architect";
$userdb="root";
$passdb="root";
$conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET CHARACTER SET utf8");
if(isset($_POST['submitDate'])){
if(!isset($_POST['Date'])){
echo "No date selected";
}else{
echo $d = date('Y-m-d',strtotime($_POST['Date']));
}
//foreach($result as $row){
$sql1= "SELECT SUM(total_pay) AS total FROM workers WHERE date_of_pay = :d AND projects_id = :id";
$stmt = $conn->prepare($sql1);
$stmt->bindValue(":d", $d);
$stmt->bindValue(":projid", $id);
$count = $stmt->execute();
$result = $stmt->fetchAll();
echo var_dump($result);
}
?>
And I am getting this error:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number: parameter was not defined' in C:\wamp\www\architect\pages\projDReport.php on line 25
does someone know what is going wrong? the global.php file, is for session detection, else it will take us to login page.

Change $stmt->bindValue(":projid", $id); to $stmt->bindValue(":id", $id);.
The values you are binding in prepared statements should have same names, as it defined in the statement. In that case it should be named :id and not :projid.

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

MySql General error: 2053

I'm getting the error:
ERROR: SQLSTATE[HY000]: General error: 2053
I have no idea why this is happening because the code works fine and the database is updated, but it still returns this error.
Here's my code:
<?php
header("Content-Type: application/json; charset=UTF-8");
require 'UHCauth.php';
try {
$conn = new PDO("mysql:host=$mysql_serv;dbname=$mysql_db", $mysql_user, $mysql_pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
if(isset($_GET['d6518e47'])) {
$USERNAME = $_GET['d6518e47'];
$stmt = $conn->prepare(
"UPDATE $mysql_table
SET KILLS = KILLS+1 WHERE USERNAME = :USERNAME"
);
$stmt->execute(array('USERNAME' => $USERNAME));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
echo json_encode($row);
} else {
$stmt = $conn->prepare(
"SELECT * FROM $mysql_table
ORDER BY
McVersion DESC,
ModVersion DESC
LIMIT 1"
);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
echo json_encode($row);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
$row = $stmt->fetch(PDO::FETCH_ASSOC); is the line that will cause your error.
Why?
Because there's nothing to fetch - in array - after an update
Remember that
PDO::FETCH_ASSOC: returns an array indexed by column name as returned
in your result set
So, no result set ... no party
If you want to know exit status of your command, just use the return value of execute() function
$rv = $stmt->execute(array('USERNAME' => $USERNAME));

Uncaught exception 'PDOException' with message 'SQLSTATE[42S22]: Column not found

I tried to run the following code but it returned this erros:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column ''1'' in 'field list'' in /home/cardg/cards/jogar.php:59 Stack trace: #0 /home/cardg/cards/jogar.php(59): PDOStatement->execute() #1 {main} thrown in /home/cardg/cards/jogar.php on line 59
Why this is happening?
<?php
include('config.php');
$usuarion = $_SESSION['login'];
$senhan = $_SESSION['senha'];
// $attrs is optional, this demonstrates using persistent connections,
// the equivalent of mysql_pconnect
$attrs = array(PDO::ATTR_PERSISTENT => true);
// connect to PDO
$pdo = new PDO('mysql:host='.$dbservidor.';dbname='.$dbnome.'', $dbusuario, $dbsenha);
// the following tells PDO we want it to throw Exceptions for every error.
// this is far more useful than the default mode of throwing php errors
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare the statement. the place holders allow PDO to handle substituting
// the values, which also prevents SQL injection
$stmt = $pdo->prepare("SELECT estado,usuario1,usuario2,usunivel,id FROM duelos WHERE estado=:estadox AND usuario1!=:usuario");
// bind the parameters
$stmt->bindValue(":estadox", 0);
$stmt->bindValue(":usuario", $usuarion);
// initialise an array for the results
$duelos = array();
if ($stmt->execute()) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$products[] = $row;
echo $row['usuario1'];
}
}
$usuario = $pdo->query("SELECT id,apelido,usuario,nivel FROM usuarios WHERE usuario = '".$usuarion."' AND senha ='".$senhan."'");
$usulinha = $usuario->fetch(PDO::FETCH_ASSOC);
$usuarioid = $usulinha['id'];
$usunivel - $usulinha['nivel'];
$sqlduelos = "SELECT COUNT(*) FROM duelos WHERE (estado = 1 AND usuario2 = 0)";
if ($resl = $pdo->query($sqlduelos)) {
/* Check the number of rows that match the SELECT statement */
if ($resl->fetchColumn() > 0) {
$msg = "True msg";
}
else{
$msg = "false msg";
$inid = $pdo->prepare("INSERT INTO `duelos` (`usuario1`, `usunivel`) VALUES (
`:usua`,
`:usuni`)");
$inid->bindParam(':usua', $usuarioid);
$inid->bindParam(':usuni', $usunivel);
$inid->execute();
}
}
// set PDO to null in order to close the connection
$pdo = null;
?>
Remove delimiters (backticks) around the placeholders:
$inid = $pdo->prepare("INSERT INTO `duelos` (`usuario1`, `usunivel`)
VALUES (:usua, :usuni)");
... as these are placeholders, which values (bound to them by bindValue) will be escaped automatically. Otherwise, those values will be treated as a column names, causing the error.
As a sidenote, you have a typo here:
$usunivel - $usulinha['nivel'];
... it should be $usunivel = $usulinha['nivel']; most probably.

PHP/PDO function return value from database variable parameters

I am trying to write this basic function to get a value from a table.
<?php
function getvalue($value, $from, $id){
//Returns the value of a table
require('includes/connect.php');
$db = new PDO('mysql:host=localhost;dbname='.$database, $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT :value AS value
FROM :from
WHERE id = :id
LIMIT 1";
$stmt = $db->prepare($sql);
$stmt->bindParam(':value', $value, PDO::PARAM_STR);
$stmt->bindParam(':from', $from, PDO::PARAM_STR);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
$data = $stmt->fetch();
$return = $data['value'];
return $return;
}//function
?>
It gives this Fatal error:
Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 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 ''project' WHERE id = '1'' at line 2' in /functions/getvalue.php:26 Stack trace: #0 /functions/getvalue.php(26): PDOStatement->execute() #1 /
test.php(24): getvalue('tarief', 'project', '1') #2 {main} thrown in /functions/getvalue.php on line 26
Although your idea of having such a function is excellent, the implementation is just terrible. Some essential drawbacks are:
you are connecting to database every time this function is called
this code is prone to SQL injection
yet it is awfully inflexible, letting you to run no query different from silly SELECT ... WHERE id. Eventually you will learn other queries and find this function unusable.
It should be a function that accepts an SQL query and array with parameters to bind:
<?php
//Returns the value of a query
function getvalue($sql, $params = array())
{
global $pdo;
$stmt = $db->prepare($sql);
$stmt->execute($params);
return $stmt->fetchColumn();
}
require('includes/connect.php');
$name = getValue("SELECT name FROM users WHERE id =?",array($_GET['id']))
simple, robust and usable.
While connection string better to be moved into includes/connect.php
$dsn = "mysql:host=localhost;dbname=$database;charset=utf8";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn, $username, $password, $opt);
Try this (be sure $value and $from variables values are escaped):
<?php
function getvalue($value, $from, $id){
//Returns the value of a table
require('includes/connect.php');
$db = new PDO('mysql:host=localhost;dbname='.$database, $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT " . $value . " AS value
FROM " . $from . "
WHERE id = :id
LIMIT 1";
$stmt = $db->prepare($sql);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
$data = $stmt->fetch();
$return = $data['value'];
return $return;
}//function
?>

undefined fetchAll and fetch in an returned PDOStatement

I'm just beginning with PDO and have look up in several tutorials for an answer but I just can't make it work.
I got
Notice: Undefined property: PDOStatement::$fetch in E:\-------- on line 22
Result: 1
with
$dsn = "mysql:host=localhost;dbname=the_database;";
try {
$dbh = new PDO($dsn, "root", "");
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch (PDOException $e){
die( "failed conexion: ".$e->getMessage() );
}
$query = "SELECT MAX(price) AS max, MIN(price) AS min FROM cellphones";
try {
$sth = $dbh->prepare($query);
$sth->execute();
$sth->setFetchMode(PDO::FETCH_ASSOC);
$result = $sth->fetchAll;
}
catch(PDOException $e){
echo $e->getMessage();
}
die( "<br />Result: ".print_r($result, true) );
I get the same result with
$sth = $dbh->query($query);
$result = $sth->fetchAll;
and
$sth = $dbh->prepare($query);
$sth->execute();
$result = $sth->fetch;
What I do get is that it might be returning the count of results
But why? And why it gives me a Notice about fetch / fetchAll not even declared.
I don't get any exception either.
You need to use the method call with paranthesis:
$sth->fetchAll();
Or
$sth->fetch();
not just
$sth->fetchAll;
PHP thinks your trying to hit a property called fetchAll!

Categories