i am basicly trying to update user information with a dynamic query.Everything good but when i try to execute query its return always false.
function updateUser($username, $email, $pass){
$arr = [];
$values = [];
$params = [];
if(isset($username))
{
array_push($arr, "userName = :username");
array_push($values, $username);
array_push($params, ":username");
}
if(isset($email))
{
array_push($arr, "userEmail = :email");
array_push($values, $email);
array_push($params, ":email");
}
if(isset($pass))
{
array_push($arr, "userPassword = :pass");
array_push($values, $pass);
array_push($params, ":pass");
}
$sql = "UPDATE users SET " . implode(", ", $arr) . " WHERE userId = :uId";
$query = $db->prepare($sql);
foreach ($params as $key) {
foreach ($values as $value) {
$query->bindValue($key, $value, PDO::PARAM_STR);
}
}
$query->bindValue(":uId", $_SESSION["userId"]);
if($query->execute() && $query->rowCount() > 0)
return true;
else
return false // always false return
}
this is my array datas:
this is funny. i can't answer my question.
i found the solution. it is because of double foreach loop.
$i = 0;
foreach ($params as $key) {
$query->bindValue($key, $values[$i], PDO::PARAM_STR);
$i++;}
Related
I'm trying to simplify a repetitive script that I'm doing in PHP. I've looked at a few loop options but since it involves rowsets being returned from a MySQL stored procedure it's not acting properly. I'm doing this same script about 15 times to return all the data. Ultimately I'm looking to pass back a json_encode array to the ajax calling it. The results I keep getting when trying to put it in a loop is a 500 error or a poorly constructed array.
$stmt->execute();
$values = array();
$stmt->execute();
$values = array();
$rowCount = $stmt->rowCount();
if ($rowCount > 0) {
$row = $stmt->fetchAll(PDO::FETCH_NUM);
$values = array();
foreach ($row as $rowvalue) {
$values[] = array($rowvalue[0], $rowvalue[1], $rowvalue[2], $rowvalue[3], $rowvalue[4], $rowvalue[5]);
}
$stmt -> nextRowset();
$row = $stmt->fetchAll();
foreach ($row as $rowvalue) {
$values[] = array($rowvalue[0], $rowvalue[1], $rowvalue[2], $rowvalue[3], $rowvalue[4], $rowvalue[5]);
}
$stmt -> nextRowset();
$row = $stmt->fetchAll();
foreach ($row as $rowvalue) {
$values[] = array($rowvalue[0], $rowvalue[1], $rowvalue[2], $rowvalue[3], $rowvalue[4], $rowvalue[5]);
}
...
echo json_encode($values);
}
Updated to use the code example below:
$sql = 'CALL fo_SELECT_Operations_Detail(?,?,?)';
$facility = $_POST['facility'];
$startweek = $_POST['startweek'];
$endweek = $_POST['endweek'];
$sql->bindParam(1, $facility, PDO::PARAM_STR);
$sql->bindParam(2, $startweek, PDO::PARAM_STR);
$sql->bindParam(3, $endweek, PDO::PARAM_STR);
$stmt = $conn->query($sql);
$values = array();
do {
$rows = $stmt->fetchAll(PDO::FETCH_NUM);
foreach ($rows as $r) {
$values[] = array($r[0], $r[1], $r[2], $r[3], $r[4], $r[5]);
}
} while ($stmt->nextRowset());
// all processed so now send JSON
echo json_encode($values);
We all forget that SP's which create rowsets also create an annoying empty one as well that has to be Next'd over, but not actually unloaded. The && $stmt->columnCount() looks after getting nextRowset() called but not actually attempting to process it in any way.
$sql = 'CALL fo_SELECT_Operations_Detail(?,?,?)';
$stmt->prepare($sql);
$stmt->bindParam(1, $_POST['facility'], PDO::PARAM_STR);
$stmt->bindParam(2, $_POST['startweek'], PDO::PARAM_STR);
$stmt->bindParam(3, $_POST['endweek'], PDO::PARAM_STR);
$stmt = $conn->execute();
$values = array();
do {
$rows = $stmt->fetchAll(PDO::FETCH_NUM);
foreach ($rows as $r) {
$values[] = [$r[0], $r[1], $r[2], $r[3], $r[4], $r[5]];
}
} while ($stmt->nextRowset() && $stmt->columnCount());
// all processed so now send JSON
echo json_encode($values);
Can anyone see what is wrong with this script? I have verified that the data is in the $_POST array and the query-string is also formed correctly, but for some reason when this gets executed, the column(s) to be updated get emptied in the database..?
/* Get the ID for the house to be modified by using a hidden-field 'hiddenDescription' */
$stmt = $db->prepare('SELECT id FROM talot WHERE kuvaus = :description');
$stmt->bindParam(':description', $_POST['hiddenDescription'], PDO::PARAM_STR);
$stmt->execute();
if($row = $stmt->fetch(PDO::FETCH_ASSOC)){
// The column names in the database
$col_names = array("kaupunki", "osoite", "pintaAla", "koko", "vuosi", "hinta", "otsikko", "kuvaus", "valittaja");
$comma = ",";
$i = 0;
$unprepared = 'UPDATE talot SET ';
/* Go through the POST -array and add the column name and :$key (for binding) into the query string. Also add comma */
foreach($_POST as $key => $value){
if(!empty($_POST[$key])){
// Skip hiddenDescription
if($key != 'hiddenDescription'){
$unprepared .= "$col_names[$i] = :$key".$comma;
}
// If $key was hiddenDescription decrement $i;
else{
$i--;
}
}
$i++;
}
// chop the last comma.
$prepared = chop($unprepared, ',');
$prepared .= ' WHERE id = :id';
$stmt = $db->prepare($prepared);
$i = 0;
/* Go through the POST -array and bind values that are not empty. Again skip hiddenDescription. */
foreach($_POST as $key => $value){
if(!empty($value)){
if($key != 'hiddenDescription'){
$stmt->bindParam(":$key", $value, PDO::PARAM_STR);
}
else{
$i--;
}
}
$i++;
}
// Bind the ID received in the first database query.
$id = (int)$row['id'];
$stmt->bindParam(":id", $id, PDO::PARAM_INT);
$result = $stmt->execute();
if($result){
echo 1;
}
Thanks!
Alright.. Solved this hehe.
This:
foreach($_POST as $key => $value){
if(!empty($value)){
if($key != 'hiddenDescription'){
$stmt->bindParam(":$key", $value, PDO::PARAM_STR);
}
else{
$i--;
}
}
$i++;
}
Changed to this:
foreach($_POST as $key => &$value){
if(!empty($value)){
if($key != 'hiddenDescription'){
$stmt->bindParam(":$key", $value, PDO::PARAM_STR);
}
else{
$i--;
}
}
$i++;
}
(bindParam needs &$variable):
i am using This code for showing user data record but this code is not work on my side
I want to echo out specific user data. I created a function where I insert multiple arguments (each argument represents a column in the database) and then echo whichever column I want with a simple line of code.
Index.php
include('function.php');
$conn = new MySQLi(localhost, root, password, database);
$user_id = $_SESSION['login_user']; // like 1
$user = user_data($conn, $user_id, 'login', 'pass', 'nikename', 'email');
if(empty($user)){
echo 'error'; // always showing this error
}else{
echo $user['nickename'];
}
Always Showing echo 'error';
function user_data($conn, $user_id){
$data = array();
$user_id = (int)$user_id;
$func_num_args = func_num_args();
$func_get_args = func_get_args();
if ($func_num_args > 1) {
unset($func_get_args[0]);
unset($func_get_args[1]);
$valid = array('login', 'pass', 'nikename', 'email');
$fields = array();
foreach($func_get_args as $arg) {
if(in_array($arg, $valid)) $fields[] = $arg;
}
$fields = '`' . implode ('`, `', $fields) . '`';
if($stmt = $conn->prepare("SELECT $fields FROM `users` WHERE `user_id` = ?")) {
$stmt->bind_param('si', $fields, $user_id);
$stmt->execute();
//here I am trying to convert the result into an array
$meta = $stmt->result_metadata();
while ($field = $meta->fetch_field()) {
$parameters[] = &$row[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $parameters);
while ($stmt->fetch()) {
foreach($row as $key => $val) {
$x[$key] = $val;
}
$results[] = $x;
}
return $results;
$stmt->close();
}
}
}
Seeing and analyzing your code several times, I think the below will solve your issue.
Add this before your while/fetch loop
$row = array();
stmt_bind_assoc($stmt, $row);
so your code will look like this
$row = array();
stmt_bind_assoc($stmt, $row);
while ($stmt->fetch()) {
foreach($row as $key => $val) {
$x[$key] = $val;
}
$results[] = $x;
}
Also make sure you read the full documentation of bind_param on php.net here
Thanks and Best Regards
I guess, instead of
if($stmt = $conn->prepare("SELECT $fields FROM `users` WHERE `user_id` = ?")) {
$stmt->bind_param('si', $fields, $user_id);
you should go with
if($stmt = $conn->prepare("SELECT $fields FROM `users` WHERE `user_id` = ?")) {
$stmt->bind_param('i', $fields, $user_id);
Bind parameters. Types: s = string, i = integer, d = double, b = blob
As far as you have one argument with type INT you need to pass 'i' as a first parameters.
Try debugging over line by line in that function where you will get exact flaw by var_dump().
Here, I'm inserting the dynamic array values into database table. it inserting the datas into database table perfectly. But, I need a little bit modification with this code.. it inserting the datas with ,. But, I want to store the array values in a separate row.
NOW I GOT
id field_name
1 aaa, bbb, ccc, ddd
BUT I NEED
id field_name
1 aaa
2 bbb
3 ccc
4 ddd
How can I achieve that?
$choose_general_rules = $_POST['choose_general_rules'];
$choose_no_of_questions = $_POST['choose_no_of_questions'];
$choose_mark_questions = $_POST['choose_mark_questions'];
$choose_question_name = $_POST['choose_question_name'];
$question = array();
foreach($choose_question_name as $value) {
$question[] = $value;
}
$result_question = implode(',', $question);
$answer_1 = $_POST['answer_1'];
$answer_one = array();
foreach($answer_1 as $value) {
$answer_one[] = $value;
}
$result_answer_one = implode(',', $answer_one);
$answer_2 = $_POST['answer_2'];
$answer_two = array();
foreach($answer_2 as $value) {
$answer_two[] = $value;
}
$result_answer_two = implode(',', $answer_two);
$answer_3 = $_POST['answer_3'];
$answer_three = array();
foreach($answer_3 as $value) {
$answer_three[] = $value;
}
$result_answer_three = implode(',', $answer_three);
$answer_4 = $_POST['answer_4'];
$answer_three = array();
foreach($answer_3 as $value) {
$answer_three[] = $value;
}
$result_answer_three = implode(',', $answer_three);
try
{
$stmt = $dbh->prepare("INSERT INTO choose_the_correct_answer ( reference_id, general_rules, no_of_questions, mark_each_questions, question, answer_option_one, answer_option_two, answer_option_three, answer_option_four ) VALUES ( :ref_id, :choose_general_rules, :choose_no_of_questions, :choose_mark_questions, :choose_question_name, :answer_1, :answer_2, :answer_3, :answer_4 )");
$stmt->bindParam(':ref_id', $lastid, PDO::PARAM_INT);
$stmt->bindParam(':choose_general_rules', $choose_general_rules, PDO::PARAM_STR);
$stmt->bindParam(':choose_no_of_questions', $choose_no_of_questions, PDO::PARAM_STR);
$stmt->bindParam(':choose_mark_questions', $choose_mark_questions, PDO::PARAM_STR);
$stmt->bindParam(':choose_question_name', $result_question, PDO::PARAM_STR);
$stmt->bindParam(':answer_1', $result_answer_one, PDO::PARAM_STR);
$stmt->bindParam(':answer_2', $result_answer_two, PDO::PARAM_STR);
$stmt->bindParam(':answer_3', $result_answer_three, PDO::PARAM_STR);
$stmt->bindParam(':answer_4', $result_answer_three, PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e)
{
echo "Error Inserting datas into database :" .$e->getMessage();
}
You should change everything in this code:
implode(',', $question);
into
implode("\n", $question);
Of course the same
implode(',', $answer_one);
into
implode("\n", $answer_one);
and so on
I want to return a set of values from function till the point they exist....
for example....
function abc($i="3"){
for($a=1;$a<=$i;$a++) {
$name='t'.$i;
$$name = "ae".$a;
}
//now i am returning values
return array($t1,$t2,$t3,$t4,$t5,$t6,$t7,$t8,$t9,$t10);
//but i only want to return $t1,$t2,$t3 depending on $i
}
Thanks....
#therefromhere
I am also creating an array in the loop , I'll paste the original code so that you can understand it in a better way
function extracting_comments($table, $fields,$condition,$order,$limit){
$query="SELECT ".$fields."
FROM ".$table."
WHERE ".$condition."
ORDER BY ".$order."
LIMIT ".$limit." ";
if($stmt = $this->conn->prepare($query)) {
$stmt->execute();
$row = array_pad(array(), $stmt->field_count, '');
$params = array();
foreach($row as $k=>$v) {
$params[] = &$row[$k];
echo $params[0];
}
call_user_func_array(array($stmt,'bind_result'),$params);
$i=0;
while($stmt->fetch()) {
$i++;
$name='t'.$i;
$$name = array();
foreach ($row as $b=>$elem) {
$atul[$b]=$row[$b];
}
$$name=$atul;
}
return array($t1,$t2,$t3,$t4,$t5,$t6,$t7,$t8,$t9,$t10);
$stmt->close();
}
}
now their are only 5 rows of data so their is no point returning $t6,$t7,$t8,$t9,$t10
and i want to fix it ,and i am calling the function using
$extract=extracting_comments($table, $fields,$condition,$order,$limit);
please help...thanks
Just build the array in your for loop:
function abc($i=3) {
$array = array();
for ($a=1; $a<=$i; $a++) {
$array[] = "ae".$a;
}
return $array;
}
After you edited your question an revealed us your actual problem, see here my proposal:
function extracting_comments($table, $fields, $condition, $order, $limit) {
$retVal = array();
$query = "SELECT ".$fields."
FROM ".$table."
WHERE ".$condition."
ORDER BY ".$order."
LIMIT ".$limit." ";
if ($stmt = $this->conn->prepare($query)) {
$stmt->execute();
$row = array_pad(array(), $stmt->field_count, '');
call_user_func_array(array($stmt, 'bind_result'), $row);
while ($stmt->fetch()) {
$retVal[] = $row;
}
$stmt->close();
return $retVal;
}
}
I believe this will help you. You have very complicated code with a lot of side effects and bug, you'd better to consider to redisgn it. Also putting statements after return will no have any effect, since it wouldn't be invoked.
function extracting_comments($table, $fields,$condition,$order,$limit){
$query="SELECT ".$fields."
FROM ".$table."
WHERE ".$condition."
ORDER BY ".$order."
LIMIT ".$limit." ";
if($stmt = $this->conn->prepare($query)) {
$stmt->execute();
$row = array_pad(array(), $stmt->field_count, '');
$params = array();
foreach($row as $k=>$v) {
$params[] = &$row[$k];
echo $params[0];
}
call_user_func_array(array($stmt,'bind_result'),$params);
$i=0;
$result = array();
while($stmt->fetch()) {
$i++;
foreach ($row as $b=>$elem) {
$atul[$b]=$row[$b];
}
$result[]=$atul;
}
$stmt->close();
return $result;
}
}
It'd be cleaner to build the array as you go along, then you wouldn't need the temporary variables:
function abc($i="3") {
$myArray = array();
for($a=1;$a<=$i;$a++) {
$myArray[] = "ae" . $a; // add new values to the end of the array
}
return $myArray;
}
If you want to check if the variables exist (and are not null), use isset().