I have a connection to a database and want to update(override) an existing string called profile by a new one.
$uid = 1;
$serProfile = 'abc';
$sql = 'UPDATE
Users
SET
profile = ?
WHERE
id = ?';
$stmt = $db->prepare($sql);
if (!$stmt) { safeExit($db->error, 'msgError'); }
$stmt->bind_param('si', $serProfile, $uid);
if (!$stmt->execute()) { safeExit($stmt->error, 'msgError'); }
$stmt->close();
However, although the variables exist, the fields exist and there are no errors, the values in the database do not get changed. How to resolve this behaviour?
Test this one
$sql = 'UPDATE Users SET profile = :profile WHERE id = :id';
$stmt = $db->prepare($sql);
$stmt->execute(array('id'=>$uid,'profile'=>$serProfile));
Related
First, according to another SO post, I tried combining the two statements into one.
<?php
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, 1);
$sql = "UPDATE users SET pass = :password WHERE usrn = :id;
SELECT prim FROM users WHERE usrn = :id;";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":id", $_SESSION["idPersist"]);
$stmt->bindParam(":password", password_hash($_POST["password"], PASSWORD_DEFAULT));
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC); //// line 71
?>
However, this kept throwing the error: Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error on line 71.
I couldn't find any relevant solutions to this issue, so I decided to simply split up the two statements.
<?php
$sql = "UPDATE users SET pass = :password WHERE usrn = :id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":id", $_SESSION["idPersist"]);
$stmt->bindParam(":password", password_hash($_POST["password"], PASSWORD_DEFAULT));
$stmt->execute();
$sql = "SELECT prim FROM users WHERE usrn = :id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":id", $_SESSION["idPersist"]);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$_SESSION["session"] = $result["prim"];
?>
But a var_dump($result) is returning Bool(false), so obviously something is not working right with fetching the result and storing it as a variable, it seems, in both cases.
I'm new to PHP and MySQL, so I'm at a loss right now.
Change this,
$sql = "SELECT prim FROM users WHERE usrn = :id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":id", $_SESSION["idPersist"]);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$_SESSION["session"] = $result["prim"];
To this,
$sql = "SELECT prim FROM users WHERE usrn = :id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":id", $_SESSION["idPersist"]);
$stmt->execute(); // Your problem
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$_SESSION["session"] = $result["prim"];
You are missing the execution of the query.
My goal is to update 4 column in my table in a single query.But end up only 1 column is updated,the other 3 is not.
My query is like this
$stmt = $this->conn->prepare("UPDATE users_info SET profile_image_path = ?,user_bio = ? ,gender = ?,date_of_birth = ? WHERE user_id = ?");
$stmt->bind_param("sssii",$profile_image_upload_url,$user_bio,$gender,$date_of_birth,$user_id);
$result = $stmt->execute();
$stmt->close();
return $result;
Here is my code for the query call
//update to database
global $user_id;
$db = new DBhandler();
$update_result = $db->callForQueryFunction($user_id,$user_bio,$date_of_birth,$gender,$profile_image_string);
$response = array();
if($update_result){
$response['error'] = false;
$response['message'] ="sucess";
}else{
$response['error'] = true;
$response['message'] ="fail";
}
After I run in advanced rest client ,with the the following query
user_bio=hihi&gender=f&profile_image_string=somestringhere&date_of_birth=2015-08-16
After run the query,the result is always "success",but in Mysql table only profile_image_path column is updated,the rest 3 column user_bio,date_of_birth and gender all are not updated.
Here is my database structure
I work for hours still haven't figure it out what's wrong with the code or my database structure.
Update:
I tried with bind_param for s with $date_of_birth,but still no luck with it
$stmt->bind_param("ssssi",$profile_image_upload_url,$user_bio,$gender,$date_of_birth,$user_id);
UPDATE
I actually using this example from Androidhive,the sample code is as below
/**
* Updating existing task
* method PUT
* params task, status
* url - /tasks/:id
*/
$app->put('/tasks/:id', 'authenticate', function($task_id) use($app) {
// check for required params
verifyRequiredParams(array('task', 'status'));
global $user_id;
$task = $app->request->put('task');
$status = $app->request->put('status');
But I use the same method as below to grab the value,but after var_dump() all the value is NULL.Here is my code
$app->put('/updateuserdetails','authenticate',function ()use ($app){
$user_bio = $app->request()->put('userbio');
$gender =$app->request()->put('gender');
$date_of_birth = $app->request()->put('dob');
$profile_image_string = $app->request()->put('profilestring');
I try this as well.The value of user_bio,gender,date_of_birth are all still null.
$app->post('/updateuserdetails','authenticate',function ()use ($app){
$user_bio = $app->request()->post('userbio');
$gender =$app->request()->post('gender');
$date_of_birth = $app->request()->post('dob');
$profile_image_string = $app->request()->post('profilestring');
I just cant figure out what is going wrong here
Update
After I test it in Postman by send data with x-www-form-urlencoded it come out with this error,which I cant get any solution
Try the following:
$stmt = $this->conn->prepare("UPDATE users_info SET profile_image_path = :image, user_bio = :bio, gender = :gender, date_of_birth = :dob WHERE user_id = :id");
$stmt->bindParam(":image", $profile_image_upload_url, PDO::PARAM_STR);
$stmt->bindParam(":bio", $user_bio, PDO::PARAM_STR);
$stmt->bindParam(":gender", $gender, PDO::PARAM_STR);
$stmt->bindParam(":dob", $date_of_birth, PDO::PARAM_STR);
$stmt->bindParam(":id", $user_id, PDO::PARAM_INT);
$result = $stmt->execute();
$stmt->close();
return $result;
Hi i am creating an android app which i am currently at a halt because my sql skills are not up to scratch. I am using json.response to run the following php.
Situation: I am checking the table column (users_watched) to see if the user_id exists inside it based on title_text, since its a number i am using ,1,(example) commas around the number so it doesn't get confused with something like 101, and returns that value. If the user_id is not in the row, then add it to the end of the string.
Text Data: user_id = '10,' - watched_title = 'video_title' - temp_user_id = ',10,'
$user_id = $_POST["user_id"];
$watched_title = $_POST["watched_title"];
$temp_user_id = $_POST["temp_user_id"];
$like_input = "'%".$temp_user_id."%'";
$statement = mysqli_prepare($con, "UPDATE videos SET users_watched = CONCAT(users_watched, '?') WHERE users_watched NOT LIKE ? AND title_text = ?");
mysqli_stmt_bind_param($statement, "sss", $user_id, $like_input, $watched_title);
mysqli_stmt_execute($statement);
Result: It is not adding the value to the end of the appropriate string.
Expected Output Add user_id = 10, to the end of the string based on videos_watched
<?php
$user_id = $_POST["user_id"];
$watched_title = $_POST["watched_title"];
$temp_user_id = $_POST["temp_user_id"];
$like_input = "%".$temp_user_id."%";
try {
$con = new PDO('mysql:host=$host;dbname=$dbname','$username', '$pass');
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $con->prepare("UPDATE videos SET users_watched = CONCAT(users_watched, :userid) WHERE users_watched NOT LIKE :like_input AND title_text = :watched_title");
$stmt->bindParam(':userid', $userid);
$stmt->bindParam(':like_input', $like_input);
$stmt->bindParam(':watched_title', $watched_title);
$stmt->execute();
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
I am trying to delete a row that matches a string that is passed in to the method.
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$data = array($_POST["username"]);
$stmt = $conn->prepare("DELETE FROM Table WHERE username = username=? ");
$stmt->execute($data);
I tried a few combinations of the SQL statement but cannot get one to work
// Store user input in a variable
$data = $_POST["username"];
// Prepare the query
$stmt = $conn->prepare("DELETE FROM Table WHERE username=:username");
// Bind the value
$stmt->bindValue(':username', $data, PDO::PARAM_STR);
// Execute the query
$success = $stmt->execute();
// If query succeeded, display the number of affected rows
if ($success) {
$affected_rows = $stmt->rowCount();
echo $affected_rows;
}
Spot the SQL error:
username = username=?
Should be
username = ?
I've tried following the PHP.net instructions for doing SELECT queries but I am not sure the best way to go about doing this.
I would like to use a parameterized SELECT query, if possible, to return the ID in a table where the name field matches the parameter. This should return one ID because it will be unique.
I would then like to use that ID for an INSERT into another table, so I will need to determine if it was successful or not.
I also read that you can prepare the queries for reuse but I wasn't sure how this helps.
You select data like this:
$db = new PDO("...");
$statement = $db->prepare("select id from some_table where name = :name");
$statement->execute(array(':name' => "Jimbo"));
$row = $statement->fetch(); // Use fetchAll() if you want all results, or just iterate over the statement, since it implements Iterator
You insert in the same way:
$statement = $db->prepare("insert into some_other_table (some_id) values (:some_id)");
$statement->execute(array(':some_id' => $row['id']));
I recommend that you configure PDO to throw exceptions upon error. You would then get a PDOException if any of the queries fail - No need to check explicitly. To turn on exceptions, call this just after you've created the $db object:
$db = new PDO("...");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
I've been working with PDO lately and the answer above is completely right, but I just wanted to document that the following works as well.
$nametosearch = "Tobias";
$conn = new PDO("server", "username", "password");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $conn->prepare("SELECT `id` from `tablename` WHERE `name` = :name");
$sth->bindParam(':name', $nametosearch);
// Or sth->bindParam(':name', $_POST['namefromform']); depending on application
$sth->execute();
You can use the bindParam or bindValue methods to help prepare your statement.
It makes things more clear on first sight instead of doing $check->execute(array(':name' => $name)); Especially if you are binding multiple values/variables.
Check the clear, easy to read example below:
$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname LIMIT 1");
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname', 'Bloggs');
$q->execute();
if ($q->rowCount() > 0){
$check = $q->fetch(PDO::FETCH_ASSOC);
$row_id = $check['id'];
// do something
}
If you are expecting multiple rows remove the LIMIT 1 and change the fetch method into fetchAll:
$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname");// removed limit 1
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname', 'Bloggs');
$q->execute();
if ($q->rowCount() > 0){
$check = $q->fetchAll(PDO::FETCH_ASSOC);
//$check will now hold an array of returned rows.
//let's say we need the second result, i.e. index of 1
$row_id = $check[1]['id'];
// do something
}
A litle bit complete answer is here with all ready for use:
$sql = "SELECT `username` FROM `users` WHERE `id` = :id";
$q = $dbh->prepare($sql);
$q->execute(array(':id' => "4"));
$done= $q->fetch();
echo $done[0];
Here $dbh is PDO db connecter, and based on id from table users we've get the username using fetch();
I hope this help someone, Enjoy!
Method 1:USE PDO query method
$stmt = $db->query('SELECT id FROM Employee where name ="'.$name.'"');
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
Getting Row Count
$stmt = $db->query('SELECT id FROM Employee where name ="'.$name.'"');
$row_count = $stmt->rowCount();
echo $row_count.' rows selected';
Method 2: Statements With Parameters
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=?");
$stmt->execute(array($name));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
Method 3:Bind parameters
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=?");
$stmt->bindValue(1, $name, PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
**bind with named parameters**
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=:name");
$stmt->bindValue(':name', $name, PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
or
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=:name");
$stmt->execute(array(':name' => $name));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
Want to know more look at this link
if you are using inline coding in single page and not using oops than go with this full example, it will sure help
//connect to the db
$dbh = new PDO('mysql:host=localhost;dbname=mydb', dbuser, dbpw);
//build the query
$query="SELECT field1, field2
FROM ubertable
WHERE field1 > 6969";
//execute the query
$data = $dbh->query($query);
//convert result resource to array
$result = $data->fetchAll(PDO::FETCH_ASSOC);
//view the entire array (for testing)
print_r($result);
//display array elements
foreach($result as $output) {
echo output[field1] . " " . output[field1] . "<br />";
}