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.
Related
I am making a Crawler with php, and this Crawler is working
<?php
$dbHost = 'localhost';
$dbName = 'invento';
$dbUser = 'root';
$dbPass = '';
try {
$pdo = new PDO("mysql:host=$dbHost;dbname=$dbName","$dbUser", "$dbPass");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(Exception $e) {
echo $e->getMessage();
}
$html = file_get_contents('https://www.google.com');
preg_match('/<title>(.*)<\/title>/i', $html, $title);
$title_out = $title[1];
$sql = "INSERT INTO prueba (title) VALUES ($title_out)";
$query = $pdo->prepare($sql);
$result = $query->execute([
'title' => $title_out
]);
but I have some problems to add the title to database, this is the error:
Fatal error: Uncaught PDOException: SQLSTATE[42S22]: Column not found:
1054 Unknown column 'Google' in 'field list' in
C:\xampp\htdocs\webcrawler\php-web-crawler\index.php:29 Stack trace:
#0 C:\xampp\htdocs\webcrawler\php-web-crawler\index.php(29): PDOStatement->execute(Array) #1 {main} thrown in
C:\xampp\htdocs\webcrawler\php-web-crawler\index.php on line 29
You are misusing prepared statements. To be effective you need to use a placeholder in place of the value.
$title_out = $title[1];
$sql = "INSERT INTO prueba (title) VALUES (:title)";
$query = $pdo->prepare($sql);
$result = $query->execute(['title' => $title_out]);
You also need to match the placeholder to the key, if you use the named placeholders. I usually use unnamed placeholders:
$title_out = $title[1];
$sql = "INSERT INTO prueba (title) VALUES (?)";
$query = $pdo->prepare($sql);
$result = $query->execute([$title_out]);
Additionally you shouldn't use a regex on HTML. It can break for many reasons. Using a parser will be more robust:
$html = file_get_contents('https://www.google.com');
$dom = new domdocument();
$dom->loadHTML($html);
$titleout = $dom->getElementsByTagName('title')[0]->nodeValue;
this is my code that is inserting data into an access database using php.
$conn = new COM ("ADODB.Connection") or die("Cannot start ADO");
$connStr = "PROVIDER=Microsoft.Ace.OLEDB.12.0;Data Source=" . realpath(‘my access path’) . ";";
// Open the connection to the database
$conn->open($connStr);
$query = “my insert query here which inserts into theaccess database fine”
$query2 = "select ##IDENTITY"
try{
$rs = $conn->execute($query);
$idReturned = $conn->lastInsertId();
echo json_encode($idReturned);
} catch(com_exception $e){
echo($e);
}
I’m trying to get the returned id but all I am getting is the below error :
exception 'com_exception' with message 'Source: ADODB.Connection
Description: Arguments are of the wrong type, are out of acceptable
range, or are in conflict with one another.' in
C:\inetpub\wwwroot\agency\createnewvaluation.php:132 Stack trace: #0
C:\inetpub\wwwroot\agency\createnewvaluation.php(132):
com->lastInsertId() #1 {main}
I went though the results manually and got the code myself
if($dbh->getAttribute(PDO::ATTR_DRIVER_NAME) == 'pgsql') {
} elseif($dbh->getAttribute(PDO::ATTR_DRIVER_NAME) == 'odbc') {
$sb = $dbh->prepare('SELECT ##IDENTITY AS lastID');
$sb->execute();
$row = $sb->fetch(PDO::FETCH_ASSOC);
$arr = array("ref" => $row["lastID"]);
echo json_encode($arr);
} else {
$arr = array("ref" => "error");
echo json_encode($arr);
}
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.
I'm receiving this error and it's got me scratching my head:
Fatal error: Uncaught exception 'PDOException' with message 'invalid
data source name' in
/Users/aaronwilson/Desktop/testing_server/ATOM_CMS/functions/sandbox.php:10
Stack trace: #0
/Users/aaronwilson/Desktop/testing_server/ATOM_CMS/functions/sandbox.php(10):
PDO->__construct('SELECT title FR...') #1
/Users/aaronwilson/Desktop/testing_server/ATOM_CMS/config/setup.php(30):
get_title(NULL, 'blog') #2
/Users/aaronwilson/Desktop/testing_server/ATOM_CMS/index.php(2):
include('/Users/aaronwil...') #3 {main} thrown in
/Users/aaronwilson/Desktop/testing_server/ATOM_CMS/functions/sandbox.php
on line 10
Here's the sandbox.php code:
<?php ## Sandbox PHP/PDO Functions
function get_page($dbc, $pg) {
$sql = new PDO("SELECT * FROM pages WHERE page = '$pg' AND status = 1 LIMIT 1");
$stmt = $dbc->prepare($sql);
$stmt->execute();
$row = $stmt->fetch();
echo '<h1>'.$page['title'].'</h1>';
echo '<div class="content">'.$page['body'].'</div>';}
function get_title($dbc, $pg)
$sql = new PDO("SELECT title FROM pages WHERE page = '$pg' AND status = 1 LIMIT 1");
$stmt = $dbc->prepare($sql);
$stmt->execute();
$row = $stmt->fetch();
return $page['title'];}
?>
On Setup.php there is a S_GET function to pull the url to call the function on sandbox.php:
if ($_GET ['page'] == '') {
$pg = 'home';}
else {
$pg = $_GET ['page']; }
new PDO("SELECT * FROM pages WHERE page = '$pg' AND status = 1 LIMIT 1");
That's not how you create a PDO object, its parameters are different, it does not take in a query. Following is the constructor prototype.
public PDO::__construct() ( string $dsn [, string $username [, string $password [, array $driver_options ]]] )
Send parameters to it accordingly. Send dsn, username, password.
Example from php.net
<?php
/* Connect to an ODBC database using driver invocation */
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
Source
Your are not using properly the PDO Library , and thats what causes errors.
Here is an example of one from many correct ways : (Adapt it to your situation and im sure it will help you )
$variable1 = "somthing";
$variable2 = "somewhat";
try
{
require_once("db-info.php");
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$db = new PDO('mysql:host='.$host.';dbname=' . $dbname, $dbuser, $dbpassword, $pdo_options);
$response = $db->prepare('SELECT column1, column2 FROM table WHERE column1 = :value1 and column2 = :value2');
$response->execute(array('value1' => $variable1,
'value2' => $variable2
));
$data = $response->fetch(); // works for one set of data
// if your are trying to fetch multiple line use a (while $data = $response->fetch())
//and insert your code inside the while loop.
//insert your code here....
//.........................
//.............
//using a return true or false may help you with your function case
$response->closeCursor();
}
catch (Exception $error)
{
die('error while selecting data' . $error->getMessage());
}
Looking on my error log I get the following error a lot:
[01-Mar-2011 04:31:27] exception 'Exception' with message 'Query failed' in /home1/mexautos/public_html/kiubbo/data/model.php:89
Stack trace:
#0 /home1/mexautos/public_html/kiubbo/data/article.php(275): Model::execSQl2('update articles...')
#1 /home1/mexautos/public_html/kiubbo/data/article.php(111): Article->save()
#2 /home1/mexautos/public_html/kiubbo/pages/frontpage.php(21): Article->calculateRanking()
#3 /home1/mexautos/public_html/kiubbo/pages/frontpage.php(27): FrontPage->updateRanking()
#4 /home1/mexautos/public_html/kiubbo/index.php(15): FrontPage->showTopArticles('')
#5 {main}
If I go to the model.php file I see this:
static function execSQl2($query)
{
/*
Execute a SQL query on the database
passing the tablename and the sql query.
Returns the LAST_INSERT_ID
*/
$db = null;
$lastid = null;
//echo "query is $query";
try
{
$db = Model::getConnection();
$results = $db->query($query);
if(!$results) {
throw new Exception('Query failed', EX_QUERY_FAILED );
}
$lastid = $db->insert_id;
}
catch(Exception $e)
{
/* errors are handled higher in the
object hierarchy
*/
throw $e;
}
Does Anybody see an error, or i should look somewhere else?
Thank you and Regards,
Carlos
Edit:
This is the query: $lastid = parent::execSql2($query);
And this is the context:
function save() {
/*
Here we do either a create or
update operation depending
on the value of the id field.
Zero means create, non-zero
update
*/
if(!get_magic_quotes_gpc())
{
$this->title = addslashes($this->title);
$this->description = addslashes($this->description);
}
try
{
$db = parent::getConnection();
if($this->id == 0 )
{
$query = 'insert into articles (modified, username, url, title, description, points )';
$query .= " values ('$this->getModified()', '$this->username', '$this->url', '$this->title', '$this->description', $this->points)";
}
else if($this->id != 0)
{
$query = "update articles set modified = NOW()".", username = '$this->username', url = '$this->url', title = '".$this->title."', description = '".$this->description."', points = $this->points, ranking = $this->ranking where id = $this->id";
}
$lastid = parent::execSql2($query);
if($this->id == 0 )
$this->id = $lastid;
}
catch(Exception $e){
error_log($e);
}
}
Regards,
Carlos
As heximal said, it's probably an error in your SQL query. Copy and paste the full SQL being queried into PhpMyAdmin or a similar tool and see what errors (if any) come up. Often, the problem is simply a mistyped table or a missing value.
Of course you can also post the query here if you want SO help with it! :D
The error is propably in sql-query. Append to log query text and analyze it.