PHP : condition on a mysql db - php

I'm pretty new in PHP coding, and I cannot find the error in the following code... could you help me please ?
Fatal error: Cannot use object of type PDOStatement as array in C:\wamp\www\membre\inscription_post.php on line 14 Call Stack # Time Memory Function Location 1 0.0006 682688 {main}( ) ..\inscription_post.php:0
<?php
try
{
$bdd = new PDO('mysql:host=localhost;dbname=test', 'root', '');
}
catch(Exception $e)
{
die('Erreur : '.$e->getMessage());
}
$mem = $bdd -> query('SELECT * FROM membres');
while ($data = $mem -> fetch())
{
if($mem['pseudo'] == $_POST['pseudo'])
{
echo "Pseudo existant";
}
else
{
$pass_hache = sha1($_POST['pass']);
$req = $bdd->prepare('INSERT INTO membres (pseudo, pass, email, date_inscription) VALUES(?, ?, ?, CURDATE())');
$req->execute(array($_POST['pseudo'], $pass_hache, $_POST['email']));
header('Location: inscription.php');
echo "Membre ajouté";
}
}
$mem -> closeCursor();
?>
membres table structure is the following
id(=INT, primary key),
pseudo (VARCHAR(255)),
pass (VARCHAR(255)),
date_inscription (date)
Thank you for your help

something like this
<?php
$dsn = 'mysql:host=localhost;dbname=test;charset=utf8';
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$bdd = new PDO($dsn,'root','', $opt);
$stm = $bdd->prepare('SELECT 1 FROM membres WHERE pseudo=?');
$stm->execute(array($_POST['pseudo']));
$row = $stm->fetch();
if ($row) {
echo "Pseudo existant";
} else {
$pass_hache = sha1($_POST['pass']);
$sql = 'INSERT INTO membres VALUES(NULL, ?, ?, ?, CURDATE())';
$req = $bdd->prepare($sql);
$req->execute(array($_POST['pseudo'], $pass_hache, $_POST['email']));
header('Location: inscription.php');
}
insert query can be wrong, depends on the table schema

if($mem['pseudo'] == $_POST['pseudo'])
^^^--- should be $data instead
But this is bad code. You're basically buying up the entire contents of a grocery store (your members table), driving it all home, then throwing away everything EXCEPT the one chocolate bar you wanted. You should be doing this in the DB, essentially
SELECT * FROM members WHERE pseudo=...

if($mem['pseudo'] == $_POST['pseudo']) should be if($data['pseudo'] == $_POST['pseudo']) as you are reading each line from $mem as $data. However, this doesn't seem like the best option for doing what it looks like you are trying to do - why not search for $_POST['pseudo'] in the database directly instead of looping through them all?

Related

PDO insert array

Reccently I have been attempting to insert an array into a database, I keep getting the error message "Notice: Array to string conversion", I not really sure how to resolve this issue, any advice would be greatly appreciated
<?php
try{
$db = new PDO("mysql:host=localhost;dbname=test", 'root', '');
$db ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
echo $e->getMessage();
die();
}
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$sort = $_POST['sort'];
$count = $_POST["count"];
$error = $_POST["error"];
$audit = array( ':sort' => $sort,
':count' => $count,
':error' => $error
);
foreach($audit as $completeAudit => $display) {
//print_r($display);
$sql = implode("INSERT INTO `audits` (`sort`, `count`, `error`, `timeentered`) VALUES ('$sort','$count','$error', NOW())");
}
$query = $db->prepare($sql);
$query->execute(array(
':sort' => $sort,
':count' => $count,
':error' => $error
));
}
EDIT
$db = new PDO("mysql:host=localhost;dbname=test", 'root', '');
$db ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$sql = "INSERT INTO `audits` (`sort`, `count`, `error`, `timeentered`) VALUES (?,?,?, NOW())";
$stmt = $db->prepare($sql);
$query->execute(array($_POST['sort'], $_POST["count"], $_POST["error"]));
}
This is how it looks now, I deleted everything and used code supplied below
The problem is probably with the implode() call. It requires an array as parameter but you're passing a string.
However, you're overriding the $sql variable in every iteration inside the loop so I'm not sure what it's supposed to do.
Last thing, your code is subject to SQL inejctions so have a look at using prepared statements.
this error has nothing to do with PDO - it's just basic PHP syntax.
However, your PDO is wrong as well. Here is the proper code:
$db = new PDO("mysql:host=localhost;dbname=test", 'root', '');
$db ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$sql = "INSERT INTO `audits` (`sort`, `count`, `error`, `timeentered`) VALUES (?,?,?, NOW())");
$stmt = $db->prepare($sql);
$stmt->execute(array($_POST['sort'], $_POST["count"], $_POST["error"]));
}

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

SELECT_IDENTITY() not working in php

Scenario:
I have a SQL Query INSERT INTO dbo.Grades (Name, Capacity, SpringPressure) VALUES ('{PHP}',{PHP}, {PHP})
The data types are correct.
I need to now get the latest IDENTIY which is GradeID.
I have tried the following after consulting MSDN and StackOverflow:
SELECT SCOPE_IDENTITY() which works in SQL Management Studio but does not in my php code. (Which is at the bottom), I have also tried to add GO in between the two 'parts' - if I can call them that - but still to no avail.
The next thing I tried, SELECT ##IDENTITY Still to no avail.
Lastly, I tried PDO::lastInsertId() which did not seem to work.
What I need it for is mapping a temporary ID I assign to the object to a new permanent ID I get back from the database to refer to when I insert an object that is depended on that newly inserted object.
Expected Results:
Just to return the newly inserted row's IDENTITY.
Current Results:
It returns it but is NULL.
[Object]
0: Object
ID: null
This piece pasted above is the result from print json_encode($newID); as shown below.
Notes,
This piece of code is running in a file called save_grades.php which is called from a ajax call. The call is working, it is just not working as expected.
As always, I am always willing to learn, please feel free to give advice and or criticize my thinking. Thanks
Code:
for ($i=0; $i < sizeof($grades); $i++) {
$grade = $grades[$i];
$oldID = $grade->GradeID;
$query = "INSERT INTO dbo.Grades (Name, Capacity, SpringPressure) VALUES ('" . $grade->Name . "',". $grade->Capacity .", ".$grade->SpringPressure .")";
try {
$sqlObject->executeNonQuery($query);
$query = "SELECT SCOPE_IDENTITY() AS ID";
$newID = $sqlObject->executeQuery($query);
print json_encode($newID);
} catch(Exception $e) {
print json_encode($e);
}
$gradesDictionary[] = $oldID => $newID;
}
EDIT #1
Here is the code for my custom wrapper. (Working with getting the lastInsertId())
class MSSQLConnection
{
private $connection;
private $statement;
public function __construct(){
$connection = null;
$statement =null;
}
public function createConnection() {
$serverName = "localhost\MSSQL2014";
$database = "{Fill In}";
$userName = "{Fill In}";
$passWord = "{Fill In}";
try {
$this->connection = new PDO( "sqlsrv:server=$serverName;Database=$database", $userName, $passWord);
$this->connection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch( PDOException $e ) {
die("Connection Failed, please contact system administrator.");
}
if ($this->connection == null) {
die("Connection Failed, please contact system administrator.");
}
}
public function executeQuery($queryString) {
$results = array();
$this->statement = $this->connection->query( $queryString );
while ( $row = $this->statement->fetch( PDO::FETCH_ASSOC ) ){
array_push($results, $row);
}
return $results;
}
public function executeNonQuery($queryString) {
$numRows = $this->connection->exec($queryString);
}
public function getLastInsertedID() {
return $this->connection->lastInsertId();
}
public function closeConnection() {
$this->connection = null;
$this->statement = null;
}
}
This is PDO right ? better drop these custom function wrapper...
$json = array();
for ($i=0; $i < sizeof($grades); $i++) {
//Query DB
$grade = $grades[$i];
$query = "INSERT INTO dbo.Grades (Name, Capacity, SpringPressure)
VALUES (?, ?, ?)";
$stmt = $conn->prepare($query);
$success = $stmt->execute(array($grade->Name,
$grade->Capacity,
$grade->SpringPressure));
//Get Ids
$newId = $conn->lastInsertId();
$oldId = $grade->GradeID;
//build JSON
if($success){
$json[] = array('success'=> True,
'oldId'=>$oldId, 'newId'=>$newId);
}else{
$json[] = array('success'=> False,
'oldId'=>$oldId);
}
}
print json_encode($json);
Try the query in this form
"Select max(GradeID) from dbo.Grades"

Delete MySQL PHP

mysql_connect('localhost', 'root', '')
or die(mysql_error());
mysql_select_db('shuttle_service_system')
or die(mysql_error());
$insert="INSERT INTO inactive (ID_No, User_Password, First_Name, Last_Name, Email, Contact_Number)
VALUES('". $ID_No ."','". $UserPassword ."','". $FirstName ."','". $LastName ."','". $Email ."','". $ContactNumber ."')";
$result=mysql_query($insert);
$sql="DELETE FROM users WHERE ID_No = '$ID_No'";
$result2=mysql_query($sql);
if($result && $result2){
echo"Successful!";
} else {
echo "&nbsp Error";
}
Hi guys I have been stuck in delete function of MySQL, I have tried searching the net but when I ran my code it always goes to the else part which means there is an error, the insert is already okay but the delete is not.
PHP variables are allowed in double quotes. Hence try this,
$sql="DELETE FROM users WHERE ID_No = $ID_No";
Your first query was not properly escaped. Rewrite like
$insert="INSERT INTO inactive (`ID_No`, `User_Password`, `First_Name`, `Last_Name`, `Email`, `Contact_Number`)
VALUES('$ID_No','$UserPassword','$FirstName','$LastName','$Email','$ContactNumber')";
This (mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. Switching to PreparedStatements is even more better to ward off SQL Injection attacks !
First, use PDO.
Make your connection Database like this:
function connectToDB(){
$host='localhost';
try {
$user = 'username';
$pass = 'password';
$bdd = 'databaseName';
$dns = 'mysql:host='.$host.';dbname='.$bdd.'';
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
return $connexion = new PDO($dns, $user, $pass, $options);
}catch ( Exception $e ) {
echo "Fail to connect: ", $e->getMessage();
die();
}
}
To delete something, here is an example:
function deleteUserWithId($ID_No){
$connexion = connectToDB();
try{
$connexion->exec('DELETE FROM users WHERE ID_No = '.$ID_No);
}catch(Exception $e){
echo "Error: ".$e->getMessage();
}
}
To insert something:
function addInactiveUser($UserPassword,$FirstName ,$LastName ,$Email,$ContactNumber){
$connexion = connectToDB();
$insert = $connexion->prepare('INSERT INTO inactive VALUES(:ID_No,
:User_Password,
:First_Name,
:Last_Name,
:Email,
:Contact_Number
)');
try {
// executing the request
$success = $insert->execute(array(
'ID_No'=>'',
'User_Password'=>$UserPassword,
'First_Name'=>$FirstName ,
'Last_Name'=>$LastName ,
'Email'=>$Email,
'Contact_Number'=>$ContactNumber
));
if($success)
// OK
else
// KO
}
catch (Exception $e){
echo "Error: ".$e->getMessage();
}
}
To make a select:
// If you want to display X user per pages for example
function getAllInactiveUsers($page, $numberInactiveUserPerPage){
$connexion = connectToDB();
$firstInactiveUser = ($page - 1) * $numberInactiveUserPerPage;
$selectAllInactiveUsers = $connexion->prepare('SELECT * FROM inactive ORDER BY ID_No DESC LIMIT '.$firstInactiveUser.','.$numberInactiveUserPerPage);
return $selectAllInactiveUsers ;
}
To get the results of this methods, just do something like this:
$inactiveUsers= getAllInactiveUsers(1,15); // for page 1, display 15 users
$inactiveUsers->execute();
while($row = $inactiveUsers->fetch(PDO::FETCH_OBJ)){
$id = $row->ID_No;
$first_name = $row->First_Name;
// etc...
}
Hope that's help :)
I am not sure if this helps you, but as an alternative you could delete the last entry in the table:
$delQ = mysql_query("SELECT * FROM ph ORDER BY id DESC LIMIT 1" );
while(( $ar = mysql_fetch_array($delQ)) !== false){
mysql_query("DELETE FROM ph WHERE id= $ar[id]");
}

Select data from database and update it PHP/PDO

I need to make a PHP code that gets data from server, updates it and echos that updated data to user. I am beginner with PHP so I have no idea how to do this. This is the code I have have now.
So how do I change the code to make it update data ?
<?php
include 'config.php';
$ID = $_GET['ID'] ;
$sql = "select * from table where ID = \"$ID\" and condition = false ";
// This is what I need the table to be updated "Update table where where ID = \"$ID\" set condition = true" ;
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->query($sql);
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
$dbh = null;
echo '{"key":'. json_encode($data) .'}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
?>
one idea is to create a different database connection file consisting of a pdo connection and reuse it in your application. on how to do that.
in database.php you can do it like
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
//catch the exception here and do whatever you like to.
}
and everywhere you want to use the connection you can do
require_once 'Database.php';
and some of the sample CRUD (Create, Read, Update, Delete) using PDO are.
//Create or Insert
$sth = $dbh->prepare("INSERT INTO folks ( first_name ) values ( 'Cathy' )");
$sth->execute();
//Read or Select
$sth = $dbh->query('SELECT name, addr, city from folks');
//Update
$sth = $dbh->prepare("UPDATE tablename SET col = val WHERE key = :value");
$sth->bindParam(':value', $value);
$sth->execute();
//Delete
$dbh->query('DELETE FROM folks WHERE id = 1');
you should also study about named and unnamed placeholders, to escape SQL injections etc. you can read more about PDO with a very easy to understand tutorial by nettuts here
hope this helps you.
Try this. I think it is along the lines of what you are looking for:
$query = "select * from table where ID = \"$ID\" and condition = false ";
$query_result = #mysql_query($query);
$query_row = mysql_fetch_assoc($query_result);
$update_query = "UPDATE table SET condition = true WHERE ID = {$row['ID']};";
if( #mysql_query($update_query) ) {
echo "Update succeeded!";
} else {
echo "Update failed!";
}
<?php
$ID = 1;
try {
$db = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$select_statement = $db->prepare('select * from table1 where id = :id and `condition` = false');
$update_statement = $db->prepare('update table1 set `condition` = true where id = :id');
$select_statement->execute(array(':id' => $ID));
$results = $select_statement->fetchAll();
$update_statement->execute(array(':id' => $ID));
echo '{"key":' . json_encode($results) .'}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
?>

Categories