This question already has answers here:
How can I detect a create, update, delete query is successful in Codeigniter
(2 answers)
Closed 2 years ago.
I searched online and most of them suggest to use num_rows or similar functions to check if the query has been successful in CodeIgniter, however I am using an update function
$data = array(
'title' => $title,
'name' => $name,
'date' => $date
);
$this->db->where('id', $id);
$this->db->update('mytable', $data);
// Produces:
// UPDATE mytable
// SET title = '{$title}', name = '{$name}', date = '{$date}'
// WHERE id = $id
How would I check if this query was successful.
Use $this->db->affected_rows()
affected_rows() won’t give you proper results with this method, due to the very nature of how it works. Instead, update_batch() returns the number of rows affected.
ELSE TRY USING:
$result = $this->db->update('mytable', $data);
if ($result) {
return 1;
}
Related
This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 2 years ago.
I'm new to PHP, I have no clue what I'm doing. I'm trying to perform an insert into my MSSQL database. Not really sure why this is not working.
function Register_WBG_Tester($Email, $FullName, $ChatHandle, $Product, $PreferedGenre, $PreviousTester, $AgeGroup, $PlayTime, $Discord, $NDA)
{
sqlsrv_configure('WarningsReturnAsErrors',0);
$query;
$result;
$query = (string)"
DECLARE #Response AS BIT = 0;
IF NOT EXISTS(SELECT Email FROM [dbo].[WBG_Tester] WHERE [Email] = $Email) BEGIN
INSERT INTO [dbo].[WBG_Tester]
([Email]
,[Full_Name]
,[Chat_Handle]
,[Product]
,[Prefered_Genre]
,[Previous_Tester]
,[Age_Group]
,[Play_Time]
,[Discord]
,[NDA_Agreement])
VALUES
($Email
,$FullName
,$ChatHandle
,$Product
,$PreferedGenre
,$PreviousTester
,$AgeGroup
,$PlayTime
,$Discord
,$NDA
)
SET #Response = 1
END ELSE BEGIN
SET #Response = 0
END
SELECT #Response"
$result =(bool)mssql_query($query);
return $result;
}
I've never worked with PHP before, mostly work with .Net I would prefer to exec calling a stored proc rather then string query. Any help would be great. Everything I've found was for MySQL. seems to be preferred for PHP.
This is how you can execute store procedures in php
sqlsrv_prepare ( resource $conn , string $sql [, array $params [, array $options ]] ) : mixed
Prepares a query for execution. This function is ideal for preparing a query that will be executed multiple times with different parameter values.
$sql = "EXEC stp_Create_Item #Item_ID = ?, #Item_Name = ?";
$stmt = sqlsrv_prepare($conn, $sql, $procedure_params);
if (!sqlsrv_execute($stmt)) {
echo "Your code is fail!";
die;
}
while($row = sqlsrv_fetch_array($stmt)){
//Stuff
}
For more details please visit, php official documentation.
This question already has answers here:
delete using where and or
(4 answers)
Why does this PDO statement silently fail?
(2 answers)
Closed 4 years ago.
I'm coding a blog to get experience with php.
I want the admin to be able to delete a post, but when I click the delete-button which should actually bring me to a function that deletes the post I get the error Call to a member function execute() on boolean.
Here is the code of the postsRepository.php which interacts with the database and the function in the postsAdminController.php:
public function deletePost($id)
{
$table = $this->getTableName();
$model = $this->getModelName();
$stmt = $this->pdo->prepare("DELETE * FROM `{$table}` WHERE id = :id");
$stmt->execute([
'id' => $id
]);
}
public function deletePost()
{
$id = $_GET['id'];
if ($this->postsRepository->deletePost($id)) {
header("Location: posts-admin");
return;
} else {
}
}
I've var_dumped the $id right before the $stmt, it's correct and the shown error says the it is because of $stmt->execute([.
The $stmt is stated as false when I var_dumped it, but why?
The correct syntax for DELETE is
DELETE FROM tableName WHERE ...
Remove the * in your query.
$stmt is false because "If the database server cannot successfully prepare the statement, PDO::prepare() returns FALSE or emits PDOException (depending on error handling)."
For more informations, check the documentation
This question already has answers here:
Can PHP PDO Statements accept the table or column name as parameter?
(8 answers)
Closed 6 years ago.
Here is my prepared statement
$stmt = $db->prepare("UPDATE user SET :property=:value WHERE `id`=:id");
$stmt->execute([':property' => $property, ':value' => $value]);
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
How can I quickly verify that the query has gone through successfully?
I was thinking maybe an if() around the execute part?
Try this
if($stmt->rowCount() > 0){
echo 'SUCCESS';
}else{
echo 'ERROR';
}
All you need to do is test the returned $stmt like this.
Remember both the prepare and the execute can fail and should be checked
$stmt = $db->prepare("UPDATE user SET :property=:value WHERE `id`=:id");
if ( $stmt == false ) {
print_r($db->errorInfo());
exit;
}
$stmt->execute([':property' => $property, ':value' => $value]);
if ( $stmt == false ) {
print_r($db->errorInfo());
exit;
}
This query will definitely fail
Now I look closer, you have a huge syntax error in the query. You cannot parameterise column or table names.
You also pave 3 parameters and only 2 values
This question already has answers here:
Update the value of a field in database by 1 using codeigniter
(3 answers)
Closed 24 days ago.
$sql = ("update Inventory SET ? = ?+1 WHERE ID= ?");
$query = $this->db->query($sql, array($field,$field,$id))->affected_rows();
The error:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near ''Upvotes' = 'Upvotes'+1 WHERE ID= 386464' at line 1
Basically it's adding quotes around the Upvotes field causing it to be a malformed query what's the most practical way to remove the single quotes or rewrite the query entirely?
The answers here arn't quite right, as they are expecting you to already have the upvote count. I think this is what you're looking for:
$this->db->where('ID', $ID);
$this->db->set('Upvotes', 'Upvotes+1', FALSE);
$this->db->update('Inventory');
Use the line below to confirm the output it should give you something like:
echo $this->db->last_query();
UPDATE Inventory SET Upvotes = Upvotes+1 WHERE ID = 386464
The third paramater of false tells CI to not protect the query with backticks.
When possible, try to use CI's query builder to lower the chances of syntax errors. As per Codeigniter Documentation:
$data = array(
'title' => $title,
'name' => $name,
'date' => $date
);
$this->db->where('id', $id);
$this->db->update('Inventory', $data);
In your case, you are probably looking for something like this:
$data = array(
'Upvotes' => $upvotes + 1
);
$this->db->where('CARD_ID', '386464');
$this->db->update('Inventory', $data);
Now, if you want to run a custom code that you cant run using CI's query builder class, then do this:
$custom_sql = "update Inventory SET Upvotes = Upvotes + 1 WHERE CARD_ID = 86464";
$query = $this->db->query($custom_sql);
This question already has answers here:
Can I bind an array to an IN() condition in a PDO query?
(23 answers)
MySQLi Bind Param with an array for IN [duplicate]
(2 answers)
Closed 9 years ago.
I'm trying to write code that basically finds your facebook friends that are on my website. I succeed in phpmyadmin running the query but for some reason when i try to run the code from php it doesn't work
Here's the php code. Whenever i take the $string echo and place it in mysql it works just fine, but for whatever reason when running it in php the query is not returning any results.
$fql = "SELECT uid FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = 100000903067831) AND is_app_user = 'true'";
$param = array(
'method' => 'fql.query',
'query' => $fql
);
$this->load->library('facebook');
echo $this->facebook->getLoginUrl();
$fqlResult = $this->facebook->api($param);
$userIDarray = array();
foreach($fqlResult as $result)
{
echo $result['uid']."<br>";
array_push($userIDarray, intval($result['uid']));
}
$string = implode(', ',$userIDarray);
echo $string;
$vars = array($string);
$query = $this->db->query("SELECT * FROM users WHERE users.facebook_id IN (?)", $vars);
echo var_dump($query);
foreach($query->result() as $data)
{
echo var_dump($data);
}
You cannot pass multiple parameters in a single ?.
You need to construct the options for IN yourself using concatenation.
Like so:
foreach($fqlResult as $result)
{
echo $result['uid']."<br>";
array_push($userIDarray, intval($result['uid']));
}
$string = implode(', ',$userIDarray);
$query = $this->db->query("SELECT * FROM users WHERE users.facebook_id
IN ('.$string.')");
Note that you need to make sure your items in the $userIDarray are properly escaped.
Because you're not using parameters, but you've injected these values into your SQL you are in danger of SQL injection attacks.
You are passing them through intval which guarantees that the strings will only contain 0..9 and - so you are safe from that here.
If the data is not numeric, you need use mysqli_real_escape_string to compensate for the fact that you're bypassing PDO's parameters.