Problems to insert data in mysql with PDO - php

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;

Related

Returning id from access database

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

PDO exception trying to insert data into a blob

I am trying to insert a very large JSON object into a blob and I am getting an exception error indicating invalid parameter number 'not defined'.
code:
<?php
session_start();
require_once('sconfig.php');
require_once('mail/config.php');
try{
$token = $_POST['stripeToken'];
$customer = \Stripe\Customer::create(array(
'email' => $_SESSION['SESS_EMAIL'],
'card' => $token
));
$charge = \Stripe\Charge::create(array(
'customer' => $customer->id,
'amount' => $_SESSION['PLAN'],
'currency' => 'usd'
));
} catch (Exception $e) {
echo "<br>";
echo "Handle your exception fool!";
}
//var_dump($customer);
echo "<br>";
//var_dump(json_decode($customer));
echo "<br>";
//echo $_SESSION['PLAN'];
$pdo = new PDO(
'mysql:host=' . DB_HOST . ';dbname=' . DB_DATABASE,
DB_USER,
DB_PASSWORD
);
//here we insert plan into the database following purchase
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
$session_var = $_SESSION['SESS_MEMBER_ID'];
//ATTENTION!!! All of these variable need to be changed when price gets changed
if($_SESSION['PLAN'] === '3500'){
$plan_var = 1;
echo $plan_var;
$sql = 'UPDATE accounting SET active = 1, plan = :plan_var WHERE id = :session_var';
$sql2 = 'INSERT INTO transactions (customer_object, charge_object) VALUES(:customer, :charge)';
}
else if($_SESSION['PLAN'] === '2500'){
$plan_var = 2;
echo $plan_var;
$sql = 'UPDATE accounting SET active = 1, plan = :plan_var WHERE id = :session_var';
$sql2 = 'INSERT INTO transactions (customer_object, charge_object) VALUES(:customer, :charge)';
}
else if($_SESSION['PLAN'] === 'NULL'){
echo "Call a Dr. Something bad happened, or the programmer needs to be fired";
header("location: ../index.php?p=failed");
}
else {
echo "This looks like a paid invoice. Thank you!";
$plan_var = 9;
echo '<br>';
echo $plan_var;
echo '<br>';
echo '<pre>' . print_r($_SESSION, TRUE) . '</pre>';
$sql = 'UPDATE accounting SET plan = :plan_var WHERE id = :session_var';
$sql2 = 'INSERT INTO transactions (invoice_num) VALUES(:invoice_num)';
//header("location: ../index.php?p=success");
}
$statement = $pdo->prepare($sql);
$statement2 = $pdo->prepare($sql2);
$statement->bindParam(':plan_var', $plan_var, PDO::PARAM_STR, 1);
$statement->bindParam(':session_var', $session_var, PDO::PARAM_STR, 1);
$statement2->bindParam(':customer', $customer, PDO::PARAM_LOB);
$statement2->bindParam(':charge', $charge, PDO::PARAM_LOB);
$statement2->bindParam(':invoice_num', $_SESSION['INVOICE_NUM'], PDO::PARAM_STR, 255);
$user = $statement->execute();
$user = $statement2->execute();
var_dump($statement);
//header("location: ../index.php?p=success");
//echo $token;
?>
The ERROR I am receiving is as follows:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number: parameter was not defined' in /usr/home/nyctelecomm/www/pages/scharge.php:79 Stack trace: #0 /usr/home/nyctelecomm/www/pages/scharge.php(79): PDOStatement->bindParam(':customer', Object(Stripe\Customer), 3) #1 {main} thrown in /usr/home/nyctelecomm/www/pages/scharge.php on line 79
How do I get blob data into a mysql database using pdo?
Based on your stack trace
Fatal error: Uncaught exception
'PDOException' with message 'SQLSTATE[HY093]:
Invalid parameter number: parameter was not defined' in
/usr/home/nyctelecomm/www/pages/scharge.php:79 Stack trace:
#0 /usr/home/nyctelecomm/www/pages/scharge.php(79):
PDOStatement->bindParam(':customer', Object(Stripe\Customer), 3)
#1 {main} thrown in /usr/home/nyctelecomm/www/pages/scharge.php on line 79
It looks like PHP is stumbling over the following line (#79)
$statement2->bindParam(':customer', $customer, PDO::PARAM_LOB);
My guess if you're trying to bind the parameter :customer into a SQL statment that doesn't have the parameter :customer defined. Looking at all the possible values of $sql2
$sql2 = 'INSERT INTO transactions
(customer_object, charge_object) VALUES(:customer, :charge)';
$sql2 = 'INSERT INTO transactions
(customer_object, charge_object) VALUES(:customer, :charge)';
$sql2 = 'INSERT INTO transactions (invoice_num) VALUES(:invoice_num)';
It seems like you're not always binding a :customer parameter.
I'd refactor your code to ensure you're not binding parameters that don't exist in your SQL.

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.

PDO Fatal Error update

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

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
?>

Categories