This is the code:
<?php
try
{
$bdd = new PDO('mysql:host=localhost;dbname=mydatabase;charset=utf8', 'root', '',array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
}
catch(Exception $e)
{
die('Erreur : '.$e->getMessage());
}
$req = $bdd->prepare('SELECT nom FROM jeux_video WHERE possesseur = ?');
$req->execute(array($_GET['possesseur']));
while($data = $req->fetch()){
echo $data['nom'].'<br/>';
}
$req->closeCursor();
?>
and this is the error:
Notice: Undefined index: possesseur in /opt/lampp/htdocs/openclassroom/index.php on line 12
The variable "possesseur" is not passed in the URL like that
script.php?possesseur=TEST
It is not a Mysql error, it is a PHP notice
$req->execute(array($_GET['possesseur']));
You're not checking if $_GET['possesseur'] exists. Add an if clause in it:
<?php
try
{
$bdd = new PDO('mysql:host=localhost;dbname=mydatabase;charset=utf8', 'root', '',array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
}
catch(Exception $e)
{
die('Erreur : '.$e->getMessage());
}
if (isset($_GET['possesseur'])) {
$req = $bdd->prepare('SELECT nom FROM jeux_video WHERE possesseur = ?');
$req->execute(array($_GET['possesseur']));
while($data = $req->fetch()){
echo $data['nom'].'<br/>';
}
$req->closeCursor();
}
Related
I'm trying to setup a web service without wsdl (for the moment) but is not working.
I have a file called "Operaciones.php" with the following code:
<?php
namespace ClasesT6;
use PDO, PDOException;
class Operaciones extends Conexion {
public function __construct()
{
parent::__construct();
}
function getPVP($id) {
$pvp = null;
$consulta = " SELECT pvp FROM productos WHERE id='$id' ";
$stmt = $this->conexion->prepare($consulta);
try {
$stmt->execute();
if($stmt) {
$row = $stmt->fetch();
$pvp = $row['pvp'];
}
} catch (PDOException $ex) {
die("Error al recuperar el pvp del producto indicado: " . $ex->getMessage());
}
return $pvp;
}
function getStock($idproducto, $idtienda) {
$stock = null;
$consulta = " SELECT unidades FROM stocks WHERE producto='$idproducto' AND tienda='$idtienda' ";
$stmt = $this->conexion->prepare($consulta);
try {
$stmt->execute();
if($stmt) {
$row = $stmt->fetch();
$stock = $row['unidades'];
}
} catch (PDOException $ex) {
die("Error al recuperar el stock del producto indicado en la tienda indicada: " . $ex->getMessage());
}
return $stock;
}
function getFamilias() {
$familiasCod = array();
$consulta = " SELECT * FROM familias ";
$stmt = $this->conexion->prepare($consulta);
try {
$stmt->execute();
if($stmt) {
$row = $stmt->fetch();
while ($row != null) {
$familiasCod[] = "{$row['cod']}";
$row = $stmt->fetch();
}
}
} catch (PDOException $ex) {
die("Error al recuperar el código de las familias: " . $ex->getMessage());
}
return $familiasCod;
}
function getProductosFamilia($cod) {
$productosFamiliaIds = array();
$consulta = " SELECT id FROM productos WHERE familia='".$cod."' ";
$stmt = $this->conexion->prepare($consulta);
try {
$stmt->execute();
if($stmt) {
$row = $stmt->fetch();
while ($row != null) {
$productosFamiliaIds[] = "{$row['id']}";
$row = $stmt->fetch();
}
}
} catch (PDOException $ex) {
die("Error al recuperar el id de los productos de la familia indicada: " . $ex->getMessage());
}
return $productosFamiliaIds;
}
}
?>
Then I have the file "service.php" with the following code:
<?php
require '../vendor/autoload.php';
$uri = 'http://localhost/archivos/FP/DWES/tarea6/servidorSoap';
$parametros = ['uri'=>$uri];
try {
$server = new SoapServer(NULL, $parametros);
$server->setClass('Operaciones');
$server->handle();
} catch (SoapFault $f) {
die("error en server: " . $f->getMessage());
}
?>
And then I have the file "cliente.php" with the following code:
<?php
require '../vendor/autoload.php';
$url = 'http://localhost/archivos/FP/DWES/tarea6/servidorSoap/servicio.php';
$uri = 'http://localhost/archivos/FP/DWES/tarea6/servidorSoap';
header('Content-Type: text/html; charset=UTF-8');
try {
$cliente = new SoapClient(null, ['location' => $url, 'uri' => $uri, 'trace'=>true]);
} catch (SoapFault $ex) {
echo "Error: ".$ex->getMessage();
}
$paramPVP = ['id' => "1"];
$getPVP = $cliente->__soapCall('getPVP', $paramPVP);
?>
When I open client.php on my localhost I get this error:
Fatal error: Uncaught SoapFault exception: [SOAP-ENV:Server] Function 'getPVP' doesn't exist in /Applications/XAMPP/xamppfiles/htdocs/files/FP/DWES/task6/public/client.php:17 Stack trace: #0 /Applications/XAMPP/xamppfiles/htdocs/archivos/FP/DWES/tarea6/public/cliente.php(17): SoapClient->__soapCall('getPVP', Array) #1 {main} thrown in /Applications/XAMPP /xamppfiles/htdocs/archivos/FP/DWES/tarea6/public/cliente.php on line 17
I've followed the instructions of the notes from my course to make service.php and cliente.php but it is not working and I don't know how to fix it.
Many thanks in advance for your solution suggestions
My request PDO Insert into is inserting two rows in my table, How can i solve it please ?
This is my scripts
try
{
$bdd = new PDO('mysql:host=XXX;dbname=XXX;charset=utf8', 'XXX', 'XXX');
$bdd->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(Exception $e)
{
die('Erreur : ' . $e->getMessage());
}
$today = date("Y-m-d");
$id = $_POST['id'];
$min = $_POST['min'];
$req = $bdd->prepare('INSERT INTO Commentaires(pseudo, commentaire, date_comment, id_video) VALUES(:pseudo, :commentaire, :date_comment, :id_video)');
$req->execute(array(
'pseudo'=>$_POST['pseudo'],
'commentaire'=>$_POST['comment'],
'date_comment'=> $today,
'id_video'=>$id));
$req->execute();
$req->closeCursor();
header('Location: read.php?min='.$min.'&id='.$id);
Just remove second execution.
try {
$bdd = new PDO('mysql:host=XXX;dbname=XXX;charset=utf8', 'XXX', 'XXX');
$bdd->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(Exception $e) {
die('Erreur : ' . $e->getMessage());
}
$today = date("Y-m-d");
$id = $_POST['id'];
$min = $_POST['min'];
$req = $bdd->prepare('INSERT INTO Commentaires(pseudo, commentaire, date_comment, id_video) VALUES(:pseudo, :commentaire, :date_comment, :id_video)');
$req->execute([
'pseudo'=> $_POST['pseudo'],
'commentaire'=> $_POST['comment'],
'date_comment'=> $today,
'id_video'=> $id
]);
$req->closeCursor();
Edit: Removed redirect code.
I make users online page using PHP - OOP - PDO
include_once '../database.php';
$db = new database();
$getRows = $db->getRows('select * from visitors_online');
$gr = $db->rowCount();
$online = '';
$getRow = $db->getRow('select * from user_online');
$gr2 = $db->rowCount();
if(!empty($gr2)) {
try {
while ($getR = $getRow){
$getRow = $db->getRow('select * from users where id = ?',[$getR['session']]);
echo ',   '.$getRow['username'].'   ';
}
} catch (PDOException $e) {
die('Error :'. $e->getMessage());
}
$total = $gr + $gr2;
The problems is:
* Not show any users except Admin, also I got this :
ONLINE
admin
Notice: Undefined index: session in /Applications/MAMP/htdocs/baws/admin/online.php on line 56
,
.Users = 0 ,Member = 2 , Register = 2
Who is online list
Here is the function from Database class
// Get row by id, username, or email etc..
public function getRow($query, $para = []){
try {
$this->stmt = $this->datab->prepare($query);
$this->stmt->execute($para);
return $this->stmt->fetch();
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}
}
Any Help
Thanks
I tried to simplify a bit your code as I do not know your class details and it s messy.
The problem is you are not binding stuff properly neither fetching them properly too. Also, you are preparing the second query, each time you loop inside the query 1 results , that is useless. prepare both (withyour class or not) and just bind and execute.
$stmt1 = $db->prepare('select * from user_online where id= ?');
$result1 = getRows($stmt1, "1");
$gr1 = $db->rowCount();
if (!empty($gr1)) {
$stmt2 = $db->prepare('select * from users where id = ?');
foreach ($result1 as $key1 => $h1) {
$stmt2->bindParam(1, $h1['session'], PDO::PARAM_INT);
$stmt2->execute();
$result2 = $stmt2->fetchAll(PDO::FETCH_ASSOC);
if (count($result2) !== 0) {
foreach ($result2 as $key2 => $r2) {
echo ',   ' . $r2['username'] . '   ';
}
}
}
}
function getRow($query, $para) {
$stmt1->bindParam(1, $para, PDO::PARAM_INT);
try {
$stmt1->execute($para);
$result1 = $stmt1->fetchAll(PDO::FETCH_ASSOC);
return $result1;
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}
}
Please find the database class here
class database {
public $isConn;
protected $datab;
private $stmt;
public function __construct() {
$this->connect();
}
// connect to database
private function connect(){
$host = 'localhost';
$db = 'baws';
$user = 'root';
$pass = 'root';
$option = [];
$this->isConn = TRUE;
try {
$this->datab = new PDO('mysql:host='.$host.';dbname='.$db.';charset=utf8', $user, $pass, $option);
$this->datab->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->datab->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
} catch (PDOException $e) {
echo '<h3>Not connected</h3>' . $e->getMessage();
}
}
// Disconnected from database
private function disconnect(){
$this->isConn = NULL;
$this->datab = FALSE;
}
//insert to database
public function insertRow($query, $para = []){
try {
$this->stmt = $this->datab->prepare($query);
$this->stmt->execute($para);
return TRUE;
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}
}
//update row to database
public function updateRow($query, $para = []){
$this->insertRow($query, $para);
}
//Delete row from database
public function deleteRow($query, $para = []){
$this->insertRow($query, $para);
}
// Get row by id, username, or email etc..
public function getRow($query, $para = []){
try {
$this->stmt = $this->datab->prepare($query);
$this->stmt->execute($para);
return $this->stmt->fetch();
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}
}
}
online.php Page
ob_start();
echo "ONLINE <br>";
include_once '../database.php';
$db = new database();
try {
$session=$_COOKIE['id'];
$time=time();
$time_check=$time-300; //SET TIME 10 Minute
$getRow = $db->getRow("SELECT * FROM user_online WHERE session = ?", [$session]);
$count =$db->rowCount($getRow);
if($count == '0'){
$insertRow = $db->insertRow("INSERT INTO user_online(session, time)VALUES(? , ?)",[$session, $time ]);
}
elseif($count != '0'){
$updateRow = $db->updateRow("UPDATE user_online SET time = ? WHERE session = ?", [$time, $session]);
}else{
$deleteRow = $db->deleteRow("DELETE FROM user_online WHERE time < ? ", [$time_check]);
}
} catch (PDOException $e) {
die('Error :'. $e->getMessage());
}
try {
$ip=$_SERVER['REMOTE_ADDR'];
$session=$ip;
$time=time();
$time_check=$time-300; //SET TIME 10 Minute
$deleteRow = $db->deleteRow("DELETE FROM visitors_online WHERE time < ? ", [$time_check]);
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}
$getRows = $db->getRows('select * from visitors_online');
$gr = $db->rowCount();
$online = '';
$getRow = $db->getRow('select * from user_online');
$gr2 = $db->rowCount();
if(!empty($gr2)) {
try {
while ($getR = $getRow){
$getRow = $db->getRow('select * from users where id = ?',[$getR['session']]);
echo ',   '.$getRow['username'].'   ';
}
} catch (PDOException $e) {
die('Error :'. $e->getMessage());
}
$total = $gr + $gr2;
} //end
I begin to despair, because I do not make a condition, if the result of the request for PDO is empty ...here is the code I use:
try
{
$pdo=new PDO('mysql:host=localhost;dbname=MyDataBase','root','');
}
catch (Exception $e)
{
die('Erreur : ' . $e->getMessage());
}
$sql = "SELECT COUNT(*) FROM Mytable WHERE name=".$name;
if ($res = $bdd->query($sql)){
echo" this name exist ";
}
else {
echo "No rows matched the query.";
}
Ues this...
$name= $_POST['name'];
try
{
$pdo=new PDO('mysql:host=localhost;dbname=MyDataBase','root','');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (Exception $e)
{
die('Erreur : ' . $e->getMessage());
}
$sql = "SELECT COUNT(*) FROM Mytable WHERE name=".$name;
$res = $pdo->query($sql);
$row = $res->fetchColumn();
if ($row){
echo" this name exist ";
}
else {
echo "No rows matched the query.";
}
It should $pdo instead in $bdd in query statement...basically a typo..thats all
I try to use a system with jQuery autocomplete to provide a listview
Here is my PHP code, except I can not find the problem, I have no error in the console but I can not seem to get the data that are in the db. It finds me no correspondence.
Conditions "where" are all right and checked (I even try the SQL query directly into phpMyAdmin, and it works, but not through the php file)
<?php
try
{
$bdd = new PDO('mysql:host=localhost;dbname=schoolby_fr', '*****', '*****');
}
catch (Exception $e)
{
die('Erreur : ' . $e->getMessage());
}
$term = "Malrau";
$pays = "France";
$dept = "Vosges";
$tipe = "Lycée";
$requete = $bdd->prepare('SELECT * FROM school WHERE s_pays="'.$pays.'" AND s_dept="'.$dept.'" AND s_type="'.$tipe.'" AND s_ecole LIKE :term');
$requete->execute(array('term' => '%'.$term.'%'));
$array = array();
while($donnee = $requete->fetch())
{
array_push($array, $donnee['s_ecole']);
}
echo json_encode($array);
?>
EDIT 22/09/2014
I wanted to show you what I get if I voluntarily recalling the condition $pays and $tipe but leaving $term and $dept.
Because it does not work with all conditions.
if you simplify your prepare statement by taking out the variables and hard coding the values maybe you can identify if it's the variables
You should prepare the query the right way, no need for the loop, and always turn on error mode.
<?php
try{
$bdd = new PDO('mysql:host=localhost;dbname=schoolby_fr', '*****', '*****');
$bdd->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$term = "Malrau";
$pays = "France";
$dept = "Vosges";
$tipe = "Lycée";
$query = 'SELECT *
FROM school
WHERE s_pays= :pays
AND s_dept= :dept
AND s_type= :tipe
AND s_ecole LIKE :term';
$requete = $bdd->prepare($query);
$requete->execute(array(':pays' => $pays,
':dept' => $dept,
':tipe' => $tipe,
':term' => '%'.$term.'%',
));
$donnees = $requete->fetchAll();
//var_dump($donnees);
echo json_encode($array);
}
catch (PDOException $e){
die('Erreur : ' . $e->getMessage());
}