PDO insert into inserting two rows - php

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.

Related

php select row from database

I have a database - named tbl_stats which contains a column (UUID) and a list of user IDs.
Im trying to create a script where http://domain.com/index.php?cid=874365 displays a page with only the values from that user's row.
My current code connects to the database but always shows the information from the top row, regardless of what the ?cid= is.
My current code:
<?php
error_reporting( E_ALL & ~E_DEPRECATED & ~E_NOTICE );
ob_start();
session_start();
define('DB_DRIVER', 'mysql');
define('DB_SERVER', 'localhost');
define('DB_SERVER_USERNAME', '[REDACTED]');
define('DB_SERVER_PASSWORD', '[REDACTED]');
define('DB_DATABASE', '[REDACTED]');
$dboptions = array(
PDO::ATTR_PERSISTENT => FALSE,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
try {
$DB = new PDO(DB_DRIVER.':host='.DB_SERVER.';dbname='.DB_DATABASE, DB_SERVER_USERNAME, DB_SERVER_PASSWORD , $dboptions);
} catch (Exception $ex) {
echo $ex->getMessage();
die;
}
//get error/success messages
if ($_SESSION["errorType"] != "" && $_SESSION["errorMsg"] != "" ) {
$ERROR_TYPE = $_SESSION["errorType"];
$ERROR_MSG = $_SESSION["errorMsg"];
$_SESSION["errorType"] = "";
$_SESSION["errorMsg"] = "";
}
try {
$cid = intval($_GET['cid']);
$sql = "SELECT * FROM tbl_stats WHERE 1 AND UUID=$cid";
$stmt = $DB->prepare($sql);
$stmt->bindValue(":cid", $cid);
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
echo $ex->getMessage();
}
?>
And then to quote the info on the page, I use the following:
<?php echo $results[0]["username"] ?>
Thanks a lot for the help guys!
Managed to get this fixed thanks to you!
try {
$cid = $_GET['cid'];
$sql = "SELECT * FROM tbl_stats WHERE UUID=:cid";
$stmt = $DB->prepare($sql);
$stmt->bindValue(":cid", $cid);
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
echo $ex->getMessage();
}
You need to add the placeholder in the SQL statement
$sql = "SELECT * FROM tbl_stats WHERE UUID=:cid";

SQL error that i could not figure it out

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

Undefined index:session LOOP NOT WORKING php, pdo oop

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 ', &nbsp '.$getRow['username'].' &nbsp ';
}
} 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 ', &nbsp ' . $r2['username'] . ' &nbsp ';
}
}
}
}
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 ', &nbsp '.$getRow['username'].' &nbsp ';
}
} catch (PDOException $e) {
die('Error :'. $e->getMessage());
}
$total = $gr + $gr2;
} //end

SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected error

my code and I take a error. I wonder how I solve problems
<?php
include_once 'simple_html_dom.php';
try {
$dsn = "mysql:host=localhost;db=test";
$username ="root";
$password = "";
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND=> 'SET NAMES UTF8' ,
PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION );
$conn = new PDO($dsn, $username, $password, $options);
} catch (Exception $ex) {
echo "Hata kodu " . $ex->getMessage();
}
// markaları alalım
$markaurl ="https://www.xxxx/chip-tuning";
$markaurlhtml = file_get_html($markaurl);
foreach ($markaurlhtml->find('div[class="darkGrid mediumBordered"] ul[id="brandsList"] a') as $markalar0) {
/* //Buna hiç gerek yokmuş üstteki kod gayet güzel ve esnek oldu :D
foreach ($markalar0->find('ul[id="brandsList"] a') as $markalar0) {
echo $markalar->href . "<br>";
} */
// echo $markalar0->href . "<br>";
// $mrk = $markalar0->href;
try {
$deyim = $conn->prepare("INSERT INTO remap_marka (marka) VALUES (?)");
$deyim->bindParam(1, $mrk);
$deyim->execute();
} catch (Exception $ex) {
echo $ex->getMessage() . "<br>";
}
}
?>
This is a solution you need for your code. Please replace it:
<?php
include_once ("simple_html_dom.php");
try {
$dsn = "mysql:host=localhost;dbname=test";
$username = "root";
$password = "";
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8',
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
$conn = new PDO($dsn, $username, $password, $options);
} catch (PDOException $ex) {
echo "Hata kodu " . $ex->getMessage();
}
// markaları alalım
$markaurl ="https://www.xxxx/chip-tuning";
$markaurlhtml = file_get_html($markaurl);
foreach ($markaurlhtml->find('div[class="darkGrid mediumBordered"] ul[id="brandsList"] a') as $markalar0) {
/*
// Buna hiç gerek yokmuş üstteki kod gayet güzel ve esnek oldu :D
foreach ($markalar0->find('ul[id="brandsList"] a') as $markalar0) {
echo $markalar->href . "<br>";
}
// echo $markalar0->href . "<br>";
// $mrk = $markalar0->href;
*/
try {
$deyim = $conn->prepare("INSERT INTO remap_marka (marka) VALUES (?)");
$deyim->bindParam(1, $mrk);
$deyim->execute();
} catch (Exception $ex) {
echo $ex->getMessage() . "<br>";
}
}
?>
I hope it is useful, regards :)

PHP Query Where and Like

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

Categories