EDITED CODEI have a mysqli line of code: $stmt->bind_param("ss", $_POST['skills'], $_POST['city']); in a working query.
I've found the need to change to PDO and have used:$stmt->bindValue(':skill', $skills, PDO::PARAM_STR);
$stmt->bindValue(':city', $city, PDO::PARAM_STR);
I get no results except the echoed "No result found. Did you enter a city?" nor error messages although there is a connection to the db as evidenced in the search form in which the select list of 'city' is loaded. The full query:
try {
global $pdo;
if(isset($_POST['search'])) {
$skills = htmlspecialchars($_POST['skills']);
$city = htmlspecialchars($_POST['city']);
$stmt = $pdo->prepare('SELECT skill.skill_name, team.city FROM skill JOIN team ON skill.skill_id=team.skill WHERE skill.skill_name LIKE :skills AND team.city LIKE :city');
$skills = "%".$skills."%";
$city = "%".$city."%";
$stmt->bindParam(':skills', $skills, PDO::PARAM_STR);
$stmt->bindParam(':city', $city, PDO::PARAM_STR);
$stmt->execute();
if ($stmt->rowCount() > 0){
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
echo $row['skill'] . " is available in " . $row['city'];
}
}
else {
echo "No result found. Did you enter a city?";
}
}
}//try
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
Thanks.
If you really need to use LIKE then you need a wildcard somewhere in the string. As a placeholder has to represent a complete data literal, and if you want to use LIKE you have to create the parameter with the wildcards included like this.
try {
global $pdo;
if(isset($_POST['search'])) {
$skills = '%' . htmlspecialchars($_POST['skills']) . '%';
$city = '%' . htmlspecialchars($_POST['city']) . '%';
$stmt = $pdo->prepare('SELECT skill.skill_name, team.city
FROM skill
JOIN team ON skill.skill_id=team.skill
WHERE skill.skill_name LIKE :skill
AND team.city LIKE :city');
$stmt->bindValue(':skill', $skills, PDO::PARAM_STR);
$stmt->bindValue(':city', $city, PDO::PARAM_STR);
$stmt->execute();
if ($stmt->rowCount() > 0){
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
echo $row['skill_name'] . " is available in " . $row['city'];
}
}else{
echo "No result found. Did you enter a city?";
}
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
A minor edit by ML: Corrected $row['skill'] to $row['skill_name']
Related
The following SELECT statement works just fine:
try {
$sql = $db->prepare('SELECT *
FROM classes
WHERE classes.id IN (65,70,80)');
$sql->execute();
$sublist = $sql->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {
echo $e->getMessage();
die();
}
BUT when I try to send a variable into the WHERE clause, I only get one row back.
In this case $ids is a string that looks like '65,70,80'.
try {
$sql = $db->prepare('SELECT *
FROM classes
WHERE classes.id IN (?)');
$sql->bindParam(1, $ids);
$sql->execute();
$sublist = $sql->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {
echo $e->getMessage();
die();
}
Do I need to change the way I'm fetching the data, or is my syntax wrong?
A-HA! Thanks for that link Mihai. Here's the code that works:
First: instead of passing in a string, put ids into an $ids array.
// Figure out how many ? marks have to be in your query as parameter placeholders.
$count = count($ids);
$arrayOfQuestions = array_fill(0, $count, '?');
$queryPlaceholders = implode(',', $arrayOfQuestions);
try {
$sql = $db->prepare('SELECT *
FROM classes
WHERE classes.id IN (' . $queryPlaceholders . ')');
$sql->execute($ids);
$sublist = $sql->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {
echo $e->getMessage();
die();
}
Try this:
try {
$sql = $db->prepare('SELECT *
FROM classes
WHERE classes.id IN (?)');
$sql->bindParam(1, explode(',', $ids));
$sql->execute();
$sublist = $sql->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {
echo $e->getMessage();
die();
}
This method is part of a larger class, and am trying to get it to return an array of objects containing the same classes. However, it doesn't seem to be entering the while loop, and I can't figure out why. Any suggestions?
The expected result would be an array of objects containing this data http://sqlfiddle.com/#!9/b6e23/1.
public static function getAllFacts($groupID)
{
$factTable = array();
$conn = new mysqli($GLOBALS['hostName'], $GLOBALS['userName'], $GLOBALS['password'], $GLOBALS['database']);
if ($conn->connect_error)
{
echo "Database connection error (source table)<br>";
}
$query = "SELECT factID, sourceID, factTXT, citationID, noteGroupID, factCreated, factsGroupID FROM facts WHERE factsGroupID = ?";
$stmt = $conn->prepare($query);
if ($stmt)
{
$stmt->bind_param("i", $groupID);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result(
$factID,
$sourceID,
$factTXT,
$citaitionID,
$noteGroupID,
$factCreated,
$factsGroupID
);
$row = 0;
while ($stmt->fetch())
{
$numRows = $stmt->num_rows;
echo "numRows: " . $numRows . "<br>";
$factTable[$row] = new self($factID, $sourceID, $factTxt, $citationTxt, $noteGroupID, $factCreated, $factsGroupID, $numRows);
$row++;
}
$stmt->close();
}
else
{
echo "Statement failed. (source table) <br>";
}
return $factTable;
}
MY code is:
try
{
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $user, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("select userid,fname,type from native_users where email=:email and pass=:pass");
$stmt->bindParam(':email', $username);
$stmt->bindParam(':pass', $password);
$stmt->execute();
if($stmt->rowCount() > 0)
{
$_SESSION['uid']=$stmt->fetchColumn(0); //working
$_SESSION['fname']=$stmt->fetchColumn(1); //not working
$utype=$stmt->fetchColumn(3); // not working
if($utype == "admin")
{
// send to admin page
}
else
{
//send to user page
}
}
else
{
echo"Incorrect data.";
}
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
I am new to PHP, I basically do Java.
I read here that:
There is no way to return another column from the same row if you use
PDOStatement::fetchColumn() to retrieve data.
In java, there is ResultSet#getString() funtion to do this.
What is the PHP equivalent of this?
You can use:
$result = $sth->fetch();
$result[0] will give userid
$result[1] will give fname
$result[2] will give type
Please read this
fetchColumn(), Returns a single column from the next row of a result
set.
Please read this for detail.
Use PDO::fetchAll() :
$rows = $stmt->fetchAll();
foreach ($rows as $v) {
echo $v['userid'] . " " . $v['fname'] . " " . $v['type'] ;
}
}
or just print_r($rows) you will notice that it's an associative array.
I'm trying to write an UPDATE query with PDO, but I can't execute my code.
This is and UPDATE function, which updates a specific row by orderID. Any ideas?
function UpdateExistingEvent ($oID, $title, $range, $organizer, $chief,
$secretary, $coOrganizer, $shortDesc, $poster, $datebegin, $dateend,
$room, $roomEquipment, $cardHolterAmount, $cardHolderNames) {
try
{
$obj=new DBconnection();
$dhb=$obj->db_connect();
$sql = 'UPDATE `materialy.event` SET '
. '`title` = :title,'
. '`range` = :range, '
. '`organizer` = :organizer, '
. '`chief` = :chief, '
. '`secretary` = :secretary, '
. '`coOrganizer` = :coOrganizer, '
. '`shortDesc` = :shortDesc, '
. '`poster` = :poster, '
. '`dateBegin` = :dateBegin, '
. '`dateEnd` = :dateEnd, '
. '`room` = :room, '
. '`roomEquipment` = :roomEquipment, '
. '`cardHolderAmount` = :cardHolderAmount, '
. '`cardHolderNames` = :cardHolderNames '
. 'WHERE `orderID` = :orderID';
$stmt = $dhb->prepare($sql);
$stmt ->bindParam(':title', $title, PDO::PARAM_STR);
$stmt ->bindParam(':range', $range, PDO::PARAM_STR);
$stmt ->bindParam(':organizer', $organizer, PDO::PARAM_STR);
$stmt ->bindParam(':chief', $chief, PDO::PARAM_STR);
$stmt ->bindParam(':secretary', $secretary, PDO::PARAM_STR);
$stmt ->bindParam(':coOrganizer', $coOrganizer, PDO::PARAM_STR);
$stmt ->bindParam(':shortDesc', $shortDesc, PDO::PARAM_STR);
$stmt ->bindParam(':poster', $poster, PDO::PARAM_STR);
$stmt ->bindParam(':dateBegin', $datebegin, PDO::PARAM_STR);
$stmt ->bindParam(':dateEnd', $dateend, PDO::PARAM_STR);
$stmt ->bindParam(':room', $room, PDO::PARAM_INT);
$stmt ->bindParam(':roomEquipment', $roomEquipment, PDO::PARAM_STR);
$stmt ->bindParam(':cardHolderAmount', $cardHolterAmount, PDO::PARAM_INT);
$stmt ->bindParam(':cardHolderNames', $cardHolderNames, PDO::PARAM_STR);
$stmt ->bindParam(':orderID', $oID, PDO::PARAM_STR);
$stmt->execute();
$stmt->debugDumpParams();
if( $stmt->rowCount() )
{
echo '<div id="GAlert" class="CompleteAlertCentral">Complete!</div>';
}
else
{
echo '<div id="error">error!<div>';
}
}
catch(PDOException $e){
echo 'PDO Library Error: '.$e->getMessage();
}
}
I don't know what is wrong. INSERT and READ work great, but UPDATE does not. Please help me.
Your problem is probably this line:
UPDATE `materialy.event` SET
Unless your table name has a period in it (which is possible, but typically quite unlikely). You probably mean:
UPDATE `materialy`.`event` SET
The problem I am having is on occasion (1 of every 8 or so) insertions to the database, the string value of (fileLocation) will be incomplete. so for example..
what should be "filecomplete.mp4" will be inserted as "filecomple".
Has anyone experienced this before or have any ideas as to what the problem could be?
Here is my insert statement.
public function addNewGame($gameID, $receiverID, $senderID, $gameTrack, $fileLocation){
$this->gameid = $gameID;
$this->receiverid = $receiverID;
$this->senderid = $senderID;
$this->gameTrack = $gameTrack;
$this->filelocation = $fileLocation;
$SQUERY = "SELECT GameId FROM ActiveGames WHERE GameId = :gameid";
try{
$stamt = $this->connection->prepare($SQUERY);
if ($stamt === false) {
throw new Exception($this->connection->error);
}
$stamt->bindValue(':gameid', $this->gameid, PDO::PARAM_INT);
$stamt->execute();
$result = $stamt->fetchAll();
$resultCount = count($result);
if($resultCount > 0){
echo "existing record";
} else{
$QUERY = "INSERT INTO ActiveGames (GameId,
ReceiverId,
SenderId,
GameTrack,
FileLocation)
VALUES (
:gameid,
:receiverid,
:senderid,
:gametrack,
:filelocation)";
try{
$stmt = $this->connection->prepare($QUERY);
if ($stmt === false) {
throw new Exception($this->connection->error);
}
$stmt->bindValue(':gameid', $this->gameid, PDO::PARAM_INT);
$stmt->bindValue(':receiverid', $this->receiverid, PDO::PARAM_INT);
$stmt->bindValue(':senderid', $this->senderid, PDO::PARAM_INT);
$stmt->bindValue(':gametrack', $this->gameTrack, PDO::PARAM_STR);
$stmt->bindValue(':filelocation', $this->filelocation, PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
}
}
catch(PDOException $e){
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
}