PHP MYSQL SELECT query parameter includes an ampersand(&) - php

I am using PHP PDO prepared statements. I am passing in a string and returning the record from MYSQL. I am passing three variables to the method.
The query returns nothing. If I perform the same query in phpmyadmin it returns all the correct data. I believe it is the ampersand(&) in the $team variable but, don't know I to work around it. I am not using a link and it is not a form element. It is a straight call to the method.
The values of the three parameters are
$season = '2018-19';
$league = 20;
$team = "Texas A&M University-Kingsville";
Here is my method:
public static function getTeamGames($season, $league, $team){
$conn = parent::connect();
$sql = "SELECT * FROM rfw_games WHERE season = :season &&
league = :league && home = :team";
try {
$st = $conn->prepare( $sql );
$st->bindValue( ":season", $season, PDO::PARAM_STR );
$st->bindValue( ":team", $team, PDO::PARAM_STR );
$st->bindValue( ":league", $league, PDO::PARAM_INT );
$st->execute();
$games = array();
foreach ( $st->fetchAll() as $row ) {
$games[] = new Game( $row );
}
parent::disconnect( $conn);
return $games;
} catch (PDOException $e ) {
parent::disconnect( $conn );
die( "Query failed: " . $e->getMessage() );
}
}
$weeklyGames = Game::getTeamGames( $season, $league, $tName );
I really appreciate the help of everyone.
Thank you in advance.

I was able to fix the issue.
I had to use html_entity_decode on the $team parameter.
I changed my method to the following:
public static function getTeamGames($season, $league, $team){
$dTeam = html_entity_decode($team);
$conn = parent::connect();
$sql = "SELECT * FROM rfw_games WHERE season = :season && league = :league && home = :team";
try {
$st = $conn->prepare( $sql );
$st->bindValue( ":season", $season, PDO::PARAM_STR );
$st->bindValue( ":team", $dTeam, PDO::PARAM_STR );
$st->bindValue( ":league", $league, PDO::PARAM_INT );
$st->execute();
$games = array();
foreach ( $st->fetchAll() as $row ) {
$games[] = new Game( $row );
}
parent::disconnect( $conn);
return $games;
} catch (PDOException $e ) {
parent::disconnect( $conn );
die( "Query failed: " . $e->getMessage() );
}
}

Related

mysql_query to pdo conversion error on processing

I need help on converting mysql_query to PDO. The MySQL database is not updating when I edit columns. I've tried translating the following code:
<?php
include("connect.php");
if($_GET['id'] and $_GET['data'])
{
$id = $_GET['id'];
$data = $_GET['data'];
$key = $_GET['key'];
if(mysql_query("update information set $key='$data' where id='$id'"))
echo 'success';
}
}
?>
Into this:
<?php
include("connect.php");
if(isset($_GET))
{
$id = $_GET['id'];
$data = $_GET['data'];
$key = $_GET['key'];
}
try {
$pdo = new PDO( DSN, DB_USR, DB_PWD );
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->query( "SET NAMES utf8" );
$stmt = $pdo->prepare(
"UPDATE information
SET
key=:data where id=:id"
);
$stmt->bindValue( ':id', $id, PDO::PARAM_INT );
$stmt->bindValue( ':key', $data, PDO::PARAM_STR );
$stmt->execute();
} catch (PDOException $e){
var_dump($e->getMessage());
}
$pdo = null;
You used :key in your bindValue() call when it should be :data. You also need to put $key into the query (you can't use a placeholder for a column name, so this requires variable substitution).
$stmt = $pdo->prepare(
"UPDATE information
SET
$key = :data where id=:id"
);
$stmt->bindValue( ':id', $id, PDO::PARAM_INT );
$stmt->bindValue( ':data', $data, PDO::PARAM_STR );
$stmt->execute();
You should validate $key before substituting it, to prevent SQL injection. Something like:
$allowed_keys = array('col1', 'col2', 'col3');
if (!in_array($key, $allowed_keys)) {
die("Bad key $key");
}

Call to undefined method PDOStatement

I'm having this error and been trying to figure whats wrong for like 3 days straight with no luck:
Fatal error: Call to undefined method PDOStatement::bindValues() on line 92
My complete code
<?php
//CLASS TO HANDLE AD
class Ad
{
//Ad id from database
public $id = null;
//Ad client
public $client = null;
//Ad client login id
public $client_loginID = null;
//Ad video source
public $video = null;
//Ad banner source
public $banner = null;
//Ad cover source
public $cover = null;
//Ad mid video banner ad
public $midVideoBannerAd = null;
//Ad link
public $link = null;
//Ad click
public $clicks = null;
//Ad impressions
public $impressions = null;
//If ad is active
public $active = null;
//Sets the obect properties using the values in supplied array
public function __construct( $data=array() ){
if( isset ( $data['id'] ) ) $this->id = (int) $data['id'];
if( isset ( $data['client'] ) ) $this->client = $data['client'];
}
//Sets the object properties using the edit form post values in the supplied array
public function storeFormValues( $params ){
//Store all the parameters
$this->__construct( $params );
}
//Returns an Author Object matching the given id
public static function getById( $statement ){
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "SELECT * FROM ad $statement";
$st = $conn->prepare( $sql );
$st->execute();
$row = $st->fetch();
$conn = null;
if( $row ) return new Ad( $row );
}
//Returns all (or range of) ad object in the db
public static function getList( $statement ){
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "SELECT * FROM ad $statement";
$st = $conn->prepare( $sql );
$st->execute();
$list = array();
while( $row = $st->fetch() ){
$ad = new Ad( $row );
$list[] = $ad;
}
//Now get the total number of Ad that match the criteria
$sql = "SELECT FOUND_ROWS() AS totalRows";
$totalRows = $conn->query( $sql )->fetch();
$conn = null;
return ( array ( "results" => $list, "totalRows" => $totalRows[0] ) );
}
//Insert current Ad object into database and set its ID properties
public function insert(){
//Check if Ad object already has an id
//Insert the Ad
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "INSERT INTO ad (client) VALUES ( :client )";
$st = $conn->prepare( $sql );
$st->bindValues( ":client", $this->client, PDO::PARAM_STR );
$st->execute();
$this->id = $conn->lastInsertId();
$conn = null;
}
//Updates the current Ad in DB
public function update(){
//Check if Ad object has an id
if( !is_null ( $this->id ) ) trigger_error ( "Ad::update(): Attempt to update an Ad object that already has an ID set.", E_USER_ERROR );
//Updates the Ad
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "UPDATE ad set client=:client, client_loginID=:client_loginID, video=:video, midVideoBannerAd=:midVideoBannerAd, banner=:banner, cover=:cover, link=:link, active=:active WHERE id=:id";
$st = $conn->prepare( $sql );
$st->bindValues( ":client", $this->client, PDO::PARAM_STR );
$st->bindValues( ":client_loginID", $this->client_loginID, PDO::PARAM_INT );
$st->bindValues( ":video", $this->video, PDO::PARAM_INT );
$st->bindValues( ":midVideoBannerAd", $this->midVideoBannerAd, PDO::PARAM_INT );
$st->bindValues( ":banner", $this->banner, PDO::PARAM_INT );
$st->bindValues( ":cover", $this->cover, PDO::PARAM_INT );
$st->bindValues( ":link", $this->link, PDO::PARAM_STR );
$st->bindValues( ":active", $this->active, PDO::PARAM_INT );
$st->bindValues( ":id", $this->id, PDO::PARAM_INT );
$st->execute();
$conn = null;
}
//Delete current Ad from Database
public function delete(){
//Delete the Ad
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$st = $conn->prepare( "DELETE FROM ad WHERE id=:id" );
$st->bindValues( ":id", $this->id, PDO::PARAM_INT );
$st->execute();
$conn = null;
}
}
And this is what's on line 92:
$st->bindValues( ":client", $this->client, PDO::PARAM_STR );
The method is called PDOStatement->bindValue() without the trailing "s"
see http://www.php.net/manual/en/pdostatement.bindvalue.php

How to add parameter to clause in PDO query

I am using code to run a Mysql query that defines a clasue ($datimeClause). I would like to run the query with a second parameter (:method) but if I change the syntax of the clause at all, the query won't run. I am fairly new to PDO could someone please tell me how I can reformat the clause to query for the second parameter.
This is the Query
public static function getList( $numRows=1000000, $datimeId=null ) {
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$datimeClause = $datimeId ? "WHERE DatimeId = :datimeId" : "";
$sql = "SELECT SQL_CALC_FOUND_ROWS * FROM notify $datimeClause";
$st = $conn->prepare( $sql );
$st->bindValue( ":numRows", $numRows, PDO::PARAM_INT );
$st->bindValue( ":datimeId", $datimeId, PDO::PARAM_INT );
$st->execute();
$list = array();
while ( $row = $st->fetch() ) {
$text = new Text( $row );
$list[] = $text;
}
This is the function that calls it.
function newAutoText() {
$results = array();
$datimeId = ( isset( $_GET['datimeId'] ) && $_GET['datimeId'] ) ? (int)$_GET['datimeId'] : null;
$results['datime'] = Text::getById( $datimeId );
$data = Text::getList( 100000, $results['datime'] ? $results['datime']->id : null);
$results['texts'] = $data['results'];
$results['totalRows'] = $data['totalRows'];
require( TEMPLATE_PATH . "/sms.php" );
}
so just try:
public static function getList( $numRows=1000000, $datimeId=null, $andClause=null ) {
and here :
$data = Text::getList( 100000, $results['datime'] ? $results['datime']->id : null, 'testMethod');
and off course here:
$sql = "SELECT SQL_CALC_FOUND_ROWS * FROM notify $datimeClause";
if ($andClause!=null ) $sql .= " AND method= :method ";
$st = $conn->prepare( $sql );
$st->bindValue( ":numRows", $numRows, PDO::PARAM_INT );
$st->bindValue( ":datimeId", $datimeId, PDO::PARAM_INT );
if ($andClause!=null )
$st->bindValue( ":method", $andClause, PDO::PARAM_STR );
Okay, the first getById query I ran in my call function was arbitrary.
This works:
public static function getList( $numRows=1000000, $datimeId, $method=1 ) {
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$datimeClause = $datimeId ? "WHERE DatimeId = :datimeId" : "";
$sql = "SELECT SQL_CALC_FOUND_ROWS * FROM notify $datimeClause AND Method= :method LIMIT :numRows";
$st = $conn->prepare( $sql );
$st->bindValue( ":numRows", $numRows, PDO::PARAM_INT );
$st->bindValue( ":datimeId", $datimeId, PDO::PARAM_INT );
$st->bindValue( ":method", $method, PDO::PARAM_INT );
$st->execute();
$list = array();
while ( $row = $st->fetch() ) {
$text = new Text( $row );
$list[] = $text;
}
// Now get the total number of articles that matched the criteria
$sql = "SELECT FOUND_ROWS() AS totalRows";
$totalRows = $conn->query( $sql )->fetch();
$conn = null;
return ( array ( "results" => $list, "totalRows" => $totalRows[0] ) );
}
function newAutoText() {
$results = array();
$datimeId = ( isset( $_GET['datimeId'] ) && $_GET['datimeId'] ) ? (int)$_GET['datimeId'] : null;
$data = Text::getList( 100000, $datimeId, '1');
$results['texts'] = $data['results'];
$results['totalRows'] = $data['totalRows'];
require( TEMPLATE_PATH . "/sms.php" );
}

Use PHP to $_GET[ID] from URL

i am using simple code to get some data from DB based on some unique ID called VIN.
i wrote a script which work fine if somebody insert it in form, but now i need to edit to work more automaticly, and use $_GET['vin'] from URL and just display results based on that.
My try of code looks like:
public $vin = null;
public function __construct( $data = array() ) {
if( isset( $data['vin'] ) ) $this->vin = stripslashes( strip_tags( $data['vin'] ) );
}
public function storeFormValues( $params ) {
$this->__construct( $params );
}
public function fetchByVinEvidence($vin) {
$success = false;
try{
$con = new PDO( DB_HOST, DB_USER, DB_PASS );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT * FROM evidence_vin WHERE vin = :vin LIMIT 1";
$stmt = $con->prepare( $sql );
$stmt->bindValue( "vin", $this->vin, PDO::PARAM_STR );
$stmt->execute();
echo "<table>";
echo "<th>First Registration</th>";
echo "<th>Validity Until</th>";
echo "<th>Rpm</th>";
echo "<th>Max-Speed</th>";
echo "<th>Action</th>";
while ($row = $stmt->fetch()){
echo "<tr>";
echo "<td>24</td>";
echo "<td>".$row['claim_number']."</td>";
echo "<td>".$row['license']."</td>";
echo "<td>".$row['country']."</td>";
echo "<td>".$row['vin']."</td>";
echo "</tr>";
}
echo "</table>" ;
}catch(PDOExeption $e){
echo $e->getMessage();
echo $con->errorInfo();
}
return $success;
}
and call the function:
$vin = $_GET['vin'];
echo $vin;
$data = new Data;
$data->fetchByVinEvidence($vin);
Can somebody help me with that?
You pass a variable $vin to the function fetchByVinEvidence but then use the class level variable $this->vin instead of the passed one.
$stmt->bindValue( "vin", $this->vin, PDO::PARAM_STR );
should be
$stmt->bindValue( "vin", $vin, PDO::PARAM_STR );
OR set the class level variable to the passed one at the start of the function if you need to use it elsehwere:
public function fetchByVinEvidence($vin) {
$this->vin = $vin;
....
public function __construct( $data = array() ) {
if( isset( $data['vin'] ) ) $this->vin = stripslashes( strip_tags( $data['vin'] ) );
}
__construct if waiting for an array, give it your $_GET directly :
$data = new Data($_GET); // and not $_GET['vin'] as it was the case before my edit
$data->fetchByVinEvidence($vin);
It was giving null because you didn't send anything to your constructor, so it used the default value : an empty array.

Invalid argument supplied for foreach() in Comment System showing from SQL

I am creating a comment system for my website, and I am linking the comment to the article ID. Each comment has its own id in an increment order, but different comments can have the same article ID.
Here is the area the on my template form the error is being thrown:
<h1>Comments</h1>
<ul id="headlines" class="archive">
<?php foreach ($craps['comments'] as $comment ) { ?>
<li>
<h2>
<span class="pubDate"><?php echo date('j F Y', $comment->publicationDate)?></span>
</h2>
<p class="summary">
<?php echo htmlspecialchars( $comment->content )?>
</p>
</li>
<?php } ?>
</ul>
Here is the section of my index page with the setting of the variables like the array and data that the php for loop is using:
function viewArticle() {
if ( !isset($_GET["articleId"]) || !$_GET["articleId"] ) {
homepage();
return;
}
$results = array();
$results['article'] = Article::getById( (int)$_GET["articleId"] );
$results['pageTitle'] = $results['article']->title . " | Gaming News";
$craps = array();
$data = Comment::getList( (int)$_GET["articleId"]);
$craps['comments'] = $data['craps'];
require( TEMPLATE_PATH . "/viewArticle.php" );
}
this is where the system is pulling the data from the database with (it is in my Comment.php):
public static function getList( $art, $order="publicationDate DESC", $numRows=10000 ) {
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate FROM comments WHERE articleid = :art
ORDER BY " . mysql_escape_string($order) . " LIMIT :numRows";
$st = $conn->prepare( $sql );
$st->bindValue( ":art", $art, PDO::PARAM_INT );
$st->bindValue( ":numRows", $numRows, PDO::PARAM_INT );
$st->execute();
$list = array();
while ( $row = $st->fetch() ) {
$comment = new Comment( $row );
$list[] = $comment;
}
}
I would really appreciate the help. This the last error i have before the comments in the test system are displayed.
here is the new get list code :
public static function getList( $art, $order="publicationDate DESC", $numRows=10000 ) {
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate FROM comments WHERE articleid = :art ORDER BY :order LIMIT :numRows";
$st = $conn->prepare( $sql );
$st->bindValue( ":art", $art, PDO::PARAM_INT );
$st->bindValue( ":numRows", $numRows, PDO::PARAM_INT );
$st->bindValue( ":order", $order, PDO::PARAM_INT );
$st->execute();
$list = array();
while ( $row = $st->fetch() ) {
$comment = new Comment( $row );
$list[] = $comment;
}
return $list;
}

Categories