I am currently building a lightweight blogging platform with some nice Material Design but i have run into a problem. I have a table with ID's and I want to change the value of public in my table so that you can hide articles from the blog, to do so I made a loop but it only works on the first id and none of the other id's. Here is my code:
try {
if (isset($_POST['submit'])) {
$stmt = $db->query('SELECT postID FROM blog_posts ORDER BY postID DESC');
while ($row = $stmt->fetch()) {
// set public based on the submitted value from your form
$public = empty($_POST['public'][$row['postID']]) ? 0 : 1;
// do the update
$stmt = $db->prepare('UPDATE blog_posts SET public = ? WHERE postID = ?');
$stmt->execute(array($public, $row['postID']));
header('Location: index.php');
}
}
} catch (PDOException $e) {
echo $e->getMessage();
}
If it is of any use here is my full page of PHP, also my fully loaded page can be found here
Thanks in advance.
Please put this header('Location: index.php'); outside the while-loop and don't override the $stmt instead use another one :
//.......
//.......
while ($row = $stmt->fetch()) {
// set public based on the submitted value from your form
$public = empty($_POST['public'][$row['postID']]) ? 0 : 1;
// do the update
//Create another statement
$stmt2 = $db->prepare('UPDATE blog_posts SET public = ? WHERE postID = ?');
$stmt2->execute(array(
$public,
$row['postID']
));
}
header('Location: index.php');
//.......
//.......
Related
I'm making a function that i have to check if a userid is in this table already: if not he has to get into another page yet. But for some reason I get "NULL" back instead of the number of the userID.
my class:
public function countHobbies($userID){
try{
$conn = Db::getConnection();
$statement = $conn->prepare("select * from hobby where userID = '".$userID."'");
$userID = $this->getUserID();
$statement->execute();
$aantal = $statement->fetchAll(PDO::FETCH_ASSOC); //
$aantal->execute();
}
catch(throwable $e){
$error = "Something went wrong";
}
}
and this is on my html page:
$userArray = $_SESSION['user_id'];
$userID = implode(" ", $userArray);
$hobby = new Hobby();
$count = $hobby->countHobbies($userID);
if($count == false){
echo "no";
//header('Location: hobby.php');
}
else{
echo "yes";
}
There are at least two things you need to fix:
Always use parameter binding on the SQL statement. It may not be a security problem in this particular instance, but do get into the habit of using prepared statements. Because otherwise you'll find yourself in situations where you should've but didn't. https://www.php.net/manual/en/security.database.sql-injection.php
The $userID variable must be assigned before it is used.
In the end, it could look like this:
$userID = $this->getUserID();
$statement = $conn->prepare("select * from hobby where userID = ?");
$statement->bind_param("s", $userID);
I have problem without any error in my code that update row ..
if(!isset($error)){
try {
$sql = "UPDATE `invoice` SET `client`='".$client."', `company`='".$company."' , `clientemail`='".$clientemail."' , `mobailclient`='".$mobailclient."' , `startdate`='".$startdate."' , `enddate`='".$enddate."' WHERE `id` ='".$id."'";
$count = $db->exec($sql);
//redirect to invoice page
header('Location: invoice.php');
exit;
//else catch the exception and show the error.
} catch(PDOException $e) {
$error[] = $e->getMessage();
}
}
This is my code , i try to get variable $sql and go to mysql phpmyadmin and its work good ,, but in file not work and i dont get any error
==== Update ====
i try this and not work
try {
$sql = 'UPDATE invoice SET client = :client, company = :company, clientemail = :clientemail, mobailclient = :mobailclient, startdate = :startdate, enddate = :enddate WHERE id = :id';
$statement = $db->prepare($sql);
$statement->bindParam(":client", $client);
$statement->bindParam(":company", $company);
$statement->bindParam(":clientemail", $clientemail);
$statement->bindParam(":mobailclient", $mobailclient);
$statement->bindParam(":startdate", $startdate);
$statement->bindParam(":enddate", $enddate);
$statement->bindParam(":id", intval($_GET['id']) );
$statement->execute();
if($statement->rowCount() > 0) // will return 1 if any row is updated
{
echo "<script>alert('".$statement->rowCount()."')</script>";
}
else
{
echo "<script>alert('No record updated')</script>";
}
Your query is opened for SQL Injection. You should use parameterized query which provide a kind of protection against SQL injection but will not provide 100% of protection. Kindly visit this Post for more details.
Try the following code by replacing table and column names.
$client = "my name";
$company = "my-company";
$id= 2;//make sure your table has a record with that specific id
$sql = 'UPDATE invoice SET client = :client, company = :company WHERE id = :id'; // here i am updating only two columns
//You can add more column that you want to upate like ColumnName = :ParameterIdentifier
//Where ParameterIdentifier Is the name of parameter used in bindParam as in my example company
$statement = $db->prepare($sql);
$statement->bindParam("client", $client); //Binding parameter for client
$statement->bindParam("company", $company); //Binding parameter for company
$statement->bindParam("id", $id);
$statement->execute();
if($statement->rowCount() > 0) // will return 1 if any row is updated
{
echo "Record updated successfully";
}
else
{
echo "No record updated";
}
So I am grabbing the amount of rows in a specific table where the username is already in the database like so:
$second_sql = $db->prepare("SELECT * FROM users WHERE username = :username");
$second_sql->bindParam(':username', $username);
$second_sql->execute();
if($second_sql->rowCount() == 1) {
$db = null;
header("Location: ../login/");
} else {
$statement->execute();
$db = null;
}
The problem is it's not working. If you need more of the script just tell me.
Some databases does not report the row count with PDO->rowCount() method.
SQLite, for instance.
So don't use rowCount(); doing so makes your code less portable.
Instead use the COUNT(*) function in your query, and store the result in a variable.
Finally, use that variable to fetch the one and only column (users) using the fetchColumn() method.
So you can play with this:
try {
$second_sql = $db->prepare("SELECT COUNT(*) from users WHERE username = :username");
$second_sql->bindParam(':username', $username, PDO::PARAM_STR);
$second_sql->execute();
$count = $second_sql->fetchColumn();
} catch (PDOException $e) {
// Here you can log your error
// or send an email
// Never echo this exception on production
// Only on development fase
echo "Error: " . $e->getMessage();
}
if ($count) {
$db = null;
header("Location: ../login/");
} else {
$statement->execute();
$db = null;
}
Perhaps you wanna test you condition for a single row:
if ($count == 1)
Hope this helps you.
Cheers!
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();
}
}
I've got several functions in my functions.php file. I'd like to add queries to the functions, but when I do that, it doesn't work. It just doesn't show the results of the query. When when I add the query to the main page and include the function, it DOES work.
I'm including the config file, so that is not the problem. I also thought about the scope, so I added GLOBAL $mysqli; to the function, but it still does not work. Any idea what the problem is here? I rather include the queries inside the functions so I do not have to add them to the main page.
My function:
function friends($friendship) {
GLOBAL $mysqli;
$friendship = mysqli_query($mysqli,"SELECT * FROM friends WHERE friend_one = '$my_username' OR friend_one = '$username'
AND friend_two = '$username' OR friend_two = '$my_username'
AND invite_sent = 1 AND invite_accepted = 1 ");
if (mysqli_num_rows($friendship) == 1){
return true;
} else {
return false;
}
}
This is the part to check whether I am friends with someone.
<?php if (friends($friendship) == true) : ?>
We are friends hooray!
<?php endif; ?>
EDIT #1 - COMBINED
So this is how the function looks like after combining the code of the main page with the function:
function friends($friendship) {
$user_id = $_SESSION['user_id'];
//Zoek de username op van ingelogde user
$stmt = $mysqli->prepare("SELECT username, email FROM members WHERE user_id = ? ");
$stmt->bind_param('i', $user_id);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($my_username, $my_email);
$stmt->fetch();
$stmt->close();
$username = $_GET["username"];
//Zoek de gebruiker en zijn/haar gegevens in de db
$stmt = $mysqli->prepare("SELECT user_id, gender, email, protected FROM members WHERE username = ? ");
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($userid, $gender, $email, $protected);
$stmt->fetch();
$stmt->close();
$friendship = mysqli_query($mysqli,"SELECT * FROM friends WHERE friend_one = '$my_username' OR friend_one = '$username'
AND friend_two = '$username' OR friend_two = '$my_username'
AND invite_sent = 1 AND invite_accepted = 1 ");
if (mysqli_num_rows($friendship) == 1){
return true;
} else {
return false;
}
}
How about making sure all of your variables are available in the query?
function friends($friendship, $my_username, $username) {
//Added $my_username, $username to the function call
//since they are on the main page but not declared in the function otherwise
GLOBAL $mysqli;
$friendship = mysqli_query($mysqli, "SELECT * FROM friends WHERE (friend_one = '$my_username' OR friend_one = '$username')
AND (friend_two = '$username' OR friend_two = '$my_username')
AND (invite_sent = 1 AND invite_accepted = 1)") or die(mysqli_error($mysqli)); //Throw an error if the query fails
if (mysqli_num_rows($friendship) == 1){
return true;
} else {
return false;
}
}
I would also caution against using the GLOBAL and I'd add on some error checking to help diagnose problems.
<?php
//Add the variables here as well...
$friends = friends($friendship, $my_username, $username);
if($friends == true)
echo 'We are friends hooray!';
} else {
//Do something?
};
?>
For all of the variables that your function will use, like $my_username in this case, you will have to either declare and initialize them inside the function or pass them in the form of the parameters to this function like #jason has described in the answer.
The reason why these queries are working on your main page is that your code(the query) is able to access variables since they are defined in that particular scope.
Since this function 'friends' has no idea about what $my_username is, you will simply need to either define the variables in this function or pass them in the form of parameters.