PDO query returns nothing - php

I have a problem with my query, it returns nothing.
if($champ == "type_id")
{
$bdd = new PDO("mysql:dbname=maruecondi_db;host=localhost","root","");
$request = $bdd->prepare('SELECT * FROM type_commercant WHERE type=:old');
$request->execute(array(':old' => $old));
while($row = $request->fetch())
{
$bdd1 = new PDO("mysql:dbname=maruecondi_db;host=localhost","root","");
$request1 = $bdd1->prepare('UPDATE commercant SET type_id=:type_id WHERE id=:id');
$request1->execute(array(':type_id' => $row['id'],':id' => $id));
}
}
I'm getting variables from ajax request (JQUERY) and i initialize them before, i avoid you the code.
Other requests on the page works.
I have currently no way to see if somethings got wrong, due to ajax call. (No php orange boxes / pdo message)
I tried to solve to problems, and i discovered that we go into the if.
I deleted the first query which contains the while, i replaced $row['id'] by a value, and i worked.
Since the beginning, i keep copying and pasting the connection to my database so no problem.
So my problem is here:
$request = $bdd->prepare('SELECT * FROM type_commercant WHERE type=:old');
$request->execute(array(':old' => $old));
while($row = $request->fetch())
I don't see what i've done wrong...
$request = $bdd->prepare('SELECT * FROM type_commercant');
$request->execute();
while($row = $request->fetch())
This works, so i tried this:
$request = $bdd->prepare('SELECT * FROM type_commercant');
$request->execute();
while($row = $request->fetch())
{
if($row['type'] == $old)
{
$request1 = $bdd->prepare('UPDATE commercant SET type_id=:type_id WHERE id=:id');
$request1->execute(array(':type_id' => $row['id'],':id' => $id));
}
}
We don't go in the condition if($row['type'] == $old), but i delete this condition, and when i replace with something like this:
while($row = $request->fetch())
{
$request1 = $bdd->prepare('UPDATE commercant SET adresse=:type_id WHERE id=:id');
$request1->execute(array(':type_id' => $row['id'],':id' => $id));
}
It works... i checked $row['type'], $row['id'], $old in array(':type_id' => $row['id'], all variable got the string attented. So what's the problem?
Thanks in advance !

Hmm, how to say that...
I was updating the data with the old data i explain myself:
$bdd = new PDO("mysql:dbname=maruecondi_db;host=localhost","root","");
$request = $bdd->prepare('SELECT id FROM type_commercant WHERE type=:old');
$request->execute(array(':old' => $old));
was getting the old ID from type_commercant, and i was doing this:
$request1 = $bdd1->prepare('UPDATE commercant SET type_id=:type_id WHERE id=:id');
$request1->execute(array(':type_id' => $row['id'],':id' => $id));
So i replaced the old ID by... the old ID.
Sorry for that mistake, thanks anyway for reading me and trying so solve this problem :D

Try to call PDO::exec() for doing UPDATE or DELETE .
$bdd = new PDO("mysql:dbname=maruecondi_db;host=localhost","root","");
if($champ == "type_id")
{
$stmt = $bdd->prepare('SELECT * FROM type_commercant WHERE type=:old');
$stmt->execute(array(':old' => $old));
$rows = $stmt->fetchAll();
// Uncomment this to know what you get
// var_dump($rows);
foreach ( $rows as $row ) {
$bdd->exec(
"UPDATE commercant
SET type_id = " . $bdd->quote($row['id']) .
" WHERE id = " . $bdd->quote($id)
);
}
}
You can use this code for debugging.
var_dump( $bdd->errorInfo() );

Related

Button to update MySQL column not working

I want to update my database with an SQL statement once someone clicks a button on the website. I've tried something, no success. Can you guys help me ? Here's the code:
http://pastebin.com/D0S83Jgh
Don't know if I made this question correctly, I'm new here.
Your prepared statement is wrong.
The code I use with pdo to do a query is this:
$sqlUpd = $upd->prepare("UPDATE league_signups SET approved='1' WHERE id = :id");
$q->bindParam(':id', $id, PDO::PARAM_STR);
$q->execute();
Should work like a charm.
Get this code out of the main loop: while($row = $q->fetch(PDO::FETCH_ASSOC)) {}
<?php
include('pdoconnect.php');
$id = isset($row['id'];
if(isset($_REQUEST['approve']))
{
$sqlUpd = "UPDATE league_signups SET approved='1' WHERE id=$id";
$q = $upd->prepare($sqlUpd);
$q->execute();
}
if(isset($_REQUEST['unapprove']))
{
$sqlUpd = "UPDATE league_signups SET approved='0' WHERE id=$id";
$q = $upd->prepare($sqlUpd);
$q->execute();
}
?>
Put this code after the loop ending or the beginning of your code...
The data you want to update comes from the checkbox am I right? then you may want to make a loop to update all the values selected with checkbox to the corresponding action 'approve' or 'unapproved'
remove include('pdoconnect.php'); its utterly unnecessary if you are including this file from the beginning already
<?php
// checkbox[] it's an array...
$UpdateIDs = (isset($_REQUEST['checkbox'])) ? $_REQUEST['checkbox'] : [];
// check if $_REQUEST['approve'] is set else check if $_REQUEST['unapprove'] is set else set $approve to null;
$approved = (isset($_REQUEST['approve']) ?
$_REQUEST['approve'] :
(isset($_REQUEST['unapprove'])) ? $_REQUEST['unapprove'] : null;
if(!is_null($approved))
{
try {
foreach($UpdateIDs as $ID)
{
$stmt = $upd->prepare("UPDATE league_signups SET approved=:approved WHERE id=:id");
$stmt->execute([
':approved' => $approved,
':id' => $ID
]);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}

cant update mysql data with json

look this my code for update data in mysql
$id = intval($_REQUEST['id']);
$user = htmlspecialchars($_REQUEST['username']);
$pass = htmlspecialchars($_REQUEST['password']);
include 'koneksi.php';
$sql = "update account set username='$user',password='$pass',where user_id=$id";
$result = #mysql_query($sql);
if ($result){
echo json_encode(array(
'user_id' => $id,
'username' => $user,
'password' => $pass
));
} else {
echo json_encode(array('errorMsg'=>'Some errors occured.'));
}
;
and the result in some errors occured
how solved this :D
You have not posted any errors, so I am going to go based on what I know.
on this line:
$result = #mysql_query($sql);
You should remove the # which will supress your warnings, because you have an error in your mysql query.
Your query will evaluate to this
update account set username='matt', password='my_pass', where user_id=100
The issue is the comma after the password, there should not be one before your WHERE.

returning multiple rows from mysql in php

I'm trying to write a PHP-script that will fetch multiple rows from MySQL and return them as a JSONObject, the code works if I try to only fetch 1 row but if I try to get more than one at a time the return string is empty.
$i = mysql_query("select * from database where id = '$v1'", $con);
$temp = 2;
while($row = mysql_fetch_assoc($i)) {
$r[$temp] = $row;
//$temp = $temp +1;
}
If I write the code like this it returns what I expect it to, but if I remove the // from the second row in the while loop it will return nothing. Can anyone explain why this is and what I should do to solve it?
You are using an obsolete mysql_* library.
You are SQL injection prone.
Your code is silly and makes no sense.
If you really wan to stick to it, why simply not do:
while($row = mysql_fetch_assoc($i)) {
$r[] = $row;
}
echo json_encode($r);
And finally, an example using PDO:
$database = 'your_database';
$user = 'your_db_user';
$pass = 'your_db_pass';
$pdo = new \PDO('mysql:host=localhost;dbname='. $database, $user, $pass);
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
try
{
$stmt = $pdo->prepare("SELECT * FROM your_table WHERE id = :id");
$stmt->bindValue(':id', $id);
$stmt->execute();
$results = $stmt->fetchAll(\PDO::FETCH_ASSOC);
}
catch(\PDOException $e)
{
$results = ['error' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine());
}
echo json_encode($results);
You don't need the $temp variable. You can add an element to an array with:
$r[] = $row;

Simple PDO update is not working

The problem is on :soundid if I type manually soundid='soundidfromPOST' received from POST, the row is updated, but with soundid=:soundid ... nothing. Why?
PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION and error_reporting enabled.
public function save($args) {
$userid = Controller::getUserConnection();
if ($userid) {
$soundid = $_POST['soundid'];
$track_title = $_POST['track_title'];
$track_artist = $_POST['track_artist'];
$track_album = $_POST['track_album'];
$track_genre = $_POST['track_genre'];
$track_description = $_POST['track_description'];
$played = 1;
$statement = $this->_db->prepare("UPDATE sounds SET title=:track_title, artist=:track_artist, album=:track_album, genre_id=:track_genre, description=:track_description, played=:played WHERE soundid=:soundid AND userid=:userid AND ip=:ip");
$statement->bindParam(':soundid',$soundid,PDO::PARAM_STR);
$statement->bindParam(':userid',$userid,PDO::PARAM_INT);
$statement->bindParam(':track_title',$track_title,PDO::PARAM_STR);
$statement->bindParam(':track_artist',$track_artist,PDO::PARAM_STR);
$statement->bindParam(':track_album',$track_album,PDO::PARAM_STR);
$statement->bindParam(':track_genre',$track_genre,PDO::PARAM_INT);
$statement->bindParam(':track_description',$track_description,PDO::PARAM_STR);
$statement->bindParam(':ip',$_SERVER['REMOTE_ADDR'],PDO::PARAM_STR);
$statement->bindParam(':played',$played,PDO::PARAM_INT);
$statement->execute();
echo 'saved!';
}
}
I would do the following to make it cleaner and because you don't need to bind everything explicitly (please note I didn't use all your variables):
Assign all your post data that you want to use in the query to an array:
$data = array(
'userid' => $userid,
'sounddid' => $_POST['soundid'],
'track_title' => $_POST['track_title'],
'track_artist' => $_POST['track_title'],
'ip' => $_SERVER['REMOTE_ADDR'],
);
Write you query:
$sth = $this->_db->prepare("
UPDATE sounds SET
title = :track_title,
artist = :track_artist
WHERE soundid = :soundid
AND userid = :userid
AND ip = :ip
");
Pass in your data array to be executed:
$result = $sth->execute($data);

mysql_fetch_array within while loop is working in localhost but not working in host server

$result = mysql_query('SELECT * FROM phpfox_education_question where subject_id = 2 and ques_id =1');
var_dump($result);
//var_dump result is :- "resource(64) of type (mysql result)" in localhost and web host,but
while($row = mysql_fetch_array($result))
{
var_dump($row); //**NOTHING DISPLAYED in web host server but in localhost**
}
Give this a try:
$query = "SELECT * FROM phpfox_education_question WHERE subject_id = '2' AND ques_id = '1'";
$result = mysql_query($query) or die(mysql_error()); // <--- added this
echo "Results: ".mysql_num_rows($result)."<br />"; // <--- added this to output result count
while($row = mysql_fetch_array($result))
{
print_r($row); //**NOTHING DISPLAYED in web host server but in localhost**
}
This is used depreciated code btw
Try adding this:
var_dump(mysql_num_rows($result));
To see if there are any rows to be fetched, if not, that's your answer.BTW, in PDO this code looks like this:
$db = new PDO('mysql:dbname=default_db_name;host=127.0.0.1',$user,$pass);
//use prepared statmenets
$stmt = $db->prepare('SELECT * FROM your_db.phpfox_education_question WHERE subject_id = :subject_id AND ques_id = :ques_id');
//pass binds when executing the stmt
$stmt->execute(array(':subject_id' => 2, ':ques_id' => 1));
//number of rows found:
var_dump($stmt->rowCount());
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{//fetch rows as assoc array
var_dump($row);
}
Note that this is a basic example, there's a lot more you can do with PDO
Update:
To get more debugging info, try this:
try
{
$db = new PDO();//connect, pass correct data here
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);//cause PDO to throw PDOExceptions on error
$stmt = $db->prepare('SELECT * FROM your_db.phpfox_education_question WHERE subject_id = :subject_id AND ques_id = :ques_id');
$stmt->execute(array(':subject_id' => 1, ':ques_id' => 2));
var_dump($stmt->rowCount());
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
var_dump($row);
}
}
catch(PDOException $e)
{
echo $e->getMessage();
$db = null;
return;
}
echo 'No problems with query<br/>';
$db = null;//disconnecto
Make sure no errors are being thrown, if there are, check the messages, find out what is going wrong and fix it. If you can't find a way to fix them, we're here to help, of course.

Categories