PHP deleting a row with a string - php

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 = ?

Related

Mysqli returns the wrong data

I would like to echo out the values of the column username and tried it like this:
public function username_exists($username) {
$conn = new mysqli($this->servername, $this->username, $this->password, $this->db_name);
$result = mysqli_query($conn, "SELECT username FROM fe_users WHERE username = $username");
while ($row = mysqli_fetch_assoc($result)) {
echo $row["username"];
}
}
When I run this code, for some reason it always returns the string 33, which is also stored in my database but it is definitely not the value of the column username. Why am I getting this output and how can I display the username which is stored in the table fe_users?
You need to quotes around $username
SELECT username FROM fe_users WHERE username = '$username'"
Better use bind and prepare statement. It automatically escape your string and free from sql injection attack
/* prepare statement */
$stmt = $conn->prepare( "SELECT username FROM fe_users WHERE username = ?");
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->bind_result($col1);
/* fetch values */
while ($stmt->fetch()) {
printf("%s %s\n", $col1);
}
/* close statement */
$stmt->close();

How to access last inserted id in PDO with static variable?

Below is my code.I want to access the last inserted id. Since I use static connection variable , it gives me error accesssing it in this way:
$insertedId = $stmt->connection::$pdo->lastInsertId() ;
public function addCar()
{
$this->rate=$param6;
if(!empty($this->name))
{
$sql="INSERT INTO car(car_name,car_maker,car_type,car_colour,num_passanger)VALUES('{$this->name}','{$this->maker}', '{$this->type}','{$this->colour}','{$this->passanger}')";
$stmt =connection::$pdo->prepare($sql);
$stmt->execute();
echo "inserted id ".$insertedId = $stmt->lastInsertId() ;
}
//$this->rentalRate();
}
UPDATE:
Simple way to use the lastInsertId() is:
// your connection with database
$con = new PDO("mysql:host=$hostname;dbname=$dbname",$dbuser,$dbpass);
// insert query
$query = "INSERT INTO tbl_name SET col_name1 = ?, col_name2 = ?";
// '$con' is your PDO connection variable
$stmt = $con->prepare($query);
$stmt->bindParam(1, $variable1); // value for col_name1 to be stored
$stmt->bindParam(2, $variable2); // value for col_name2 to be stored
$stmt->execute();
....
// gives current inserted id
$lastId = $con->lastInsertId();
In your case try: $lastId = connection::$pdo->lastInsertId();

How to fetch data from database using prepare statement in php?

I have a database in which I have user_id & associated_id.There can be multiple associated_id for a single user_id. Now I want to fetch all the associated_ids into a single array. I have tried this method but don't know how to get them in array.
$stmt = $this->conn->prepare("SELECT * FROM my_contacts WHERE user_id = ?");
$stmt->bind_param("s", $user_id);
if ($stmt->execute())
{
while ($stmt->fetch())
{
//what to write here
}
//echo var_dump($user);
$stmt->close();
}
Try this:
$stmt = $mysqli->prepare("SELECT associated_id FROM my_contacts WHERE user_id = ?")) {
$stmt->bind_param('s', $user_id); // Bind "$user_id" to parameter.
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
// get variables from result.
$stmt->bind_result($associated_id);
$stmt->fetch();
The results will be stored in the $associated_id array.
You can bind parameters like this and use fetchall method to get all the results in a array
$stmt = $this->conn->prepare("SELECT * FROM my_contacts WHERE user_id = :user_id");
$stmt->bind_param(":user_id", $user_id, PDO::PARAM_INT);
if ($stmt->execute())
{
$result = $stmt->fetchall(PDO::FETCH_ASSOC);
//echo var_dump($user);
$stmt->close();
}
According to your code you used mysqli.
$stmt = $this->conn->prepare("SELECT * FROM my_contacts WHERE user_id = ?");
if($stmt->execute()){
$result = $stmt->get_result();
if($result->nom_rows > 0){
while($row = $result->fetch_assoc()){
var_dump($row)
}
}else{
echo "Sorry NO data found";
}
}else{
echo "Some thing is wrong";
}
here you can't used $stmt->bind_result(); instead of use $stmt->get_result()
$stmt->bind_result(); is only used when you define field in select query
with * you need to used $stmt->get_result()
refer this link for more information
Example of how to use bind_result vs get_result

PHP PDO how do i include fetch assoc and numrows

trying to convert all my old mysql_* operations into new and, from what i've heard, improved PDO, but this query wont seem to run successfully, I am trying to select all from the table PEOPLE where the username = $username (which has previously been declared $username = $_SESSION['username'];)
$query = "SELECT * FROM people WHERE username=?";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $username);
$stmt->execute();
$num_rows = $stmt->fetchColumn();
if ($num_rows == 1) {
// ...
}
THE WORKING CODE IS:
$query = "SELECT * FROM people
WHERE username=?";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $username);
$stmt->execute();
$num_rows = $stmt->fetchColumn();
$user = $stmt->fetchObject();
if ($user) {
//do something
}
$stmt->fetchColumn does not fetch the number of rows; in this case it will fetch the first column from the first row of the result set. Since that will not be equal to 1 generally your test will fail.
In this case there is also no real need to count the number of returned rows because you are expecting either one or zero (if the username does not exist). So you can simply do:
$stmt->execute();
$user = $stmt->fetchObject();
if (!$user) {
// not found
}
else {
echo "User $user->username found!";
}
The if(!$user) test works because if there is no row to fetch $user will be false (see the documentation for fetchObject).
$query = "SELECT * FROM people WHERE username = :username";
$stmt = $conn->prepare($query);
$stmt->bindParam(':username', $username);
$stmt->execute();
while ($row = $stmt->fetchObject()) {
// do stuff
}
Use PDOStatement::rowCount as the num_rows and PDOStatement::fetch(PDO::FETCH_ASSOC) as fetch_assoc equivalent.
You want
if ($stmt->num_rows == 1) {
instead.

MySQL: Update statement shows no errors but changes nothing

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

Categories