how to update multiple data using php - php

i am a newbie in here and i have a problem that me myself cannot find the exact solution... here it is... i need to build a system that will update all the staff information. through this system, a staff in human resource department will enter all the staffs information. i have been create this code to update the staffs information but it seems not function with what i really want.... i just want to update by rows however, it turns to update all rows in the database...
<?php
session_start();
include ("includes/database.php");
include ("includes/security.php");
include ("includes/config.php");
$nama=$_SESSION["nama"];
$pwd=$_SESSION["status"];
$nama=$_POST["st_nama"];
$siri1=$_POST["st_siri"];
$siri2=$_POST["st_siri2"];
$siri3=$_POST["st_siri3"];
$jawatan=$_POST["st_jawatan"];
$gred=$_POST["st_gred"];
$gredh=$_POST["st_gredh"];
$gelaran=$_POST["st_gelaran"];
$elaun=$_POST["st_elaun"];
$id=$_GET["id"];
$dataPengguna2= mysql_query("SELECT * FROM tbl_rekod where id='$id'");
mysql_query("UPDATE tbl_rekod set st_nama='$nama', st_siri='$siri1', st_siri2='$siri2', st_siri3='$siri3', st_jawatan='$jawatan', st_gred='$gred', st_gredh='$gredh', st_gelaran='$gelaran', st_elaun='$elaun' WHERE id='$id'") or die (mysql_error());
$status = "REKOD BERJAYA DIKEMASKINI!<br/><a href = 'stafflogin.php'><strong>KEMBALI KE LAMAN UTAMA</strong></a>";
?>

This will help fix your sql injection issue, and may also fix update 1 vs multiple rows issue. This method uses the PDO library in PHP. You can see more info on using PDO on the PHP site. It replaces the mysql_ set of commands which are no longer included in the PHP releases.
// Below replaces the mysql_connect() so it requires db credentials filled in
try {
$host = 'hostname';
$db = 'databasename';
$user = 'username';
$pass = 'password';
$con = new PDO("mysql:host=$host;dbname=$db",$user,$pass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
}
// This replaces the die("error message") potion of a mysql_connect() set-up
catch (Exception $e) {
$_errors['connect']['message'] = $e->getMessage();
$_errors['connect']['error_code'] = $e->getCode();
}
$nama = $_SESSION["nama"];
$pwd = $_SESSION["status"];
$nama = $_POST["st_nama"];
$siri1 = $_POST["st_siri"];
$siri2 = $_POST["st_siri2"];
$siri3 = $_POST["st_siri3"];
$jawatan = $_POST["st_jawatan"];
$gred = $_POST["st_gred"];
$gredh = $_POST["st_gredh"];
$gelaran = $_POST["st_gelaran"];
$elaun = $_POST["st_elaun"];
$id = $_GET["id"];
// You should do just a preliminary check that the id is a numeric value
// No sense in continuing if someone tries to foil the natural
// order of your code
if(is_numeric($id)) {
// The next 3 lines would be equivalent to the mysql_query("statement here")
// as well as a more robust version of mysql_real_escape_string(). It does more,
// but for sake of explanation it does that and more.
$dataPengguna2 = $con->prepare("SELECT * FROM tbl_rekod where id=:id");
// Binding paramaters basically sanitizes the value being inserted into your query
$dataPengguna2->bindParam(':id',$id);
$dataPengguna2->execute();
// There is no indication of what you are doing with the select above
// Set up the update statement
$query = $con->prepare("UPDATE tbl_rekod set st_nama=:st_nama, st_siri=:st_siri, st_siri2=:st_siri2, st_siri3=:st_siri3, st_jawatan=:st_jawatan, st_gred=:st_gred, st_gredh=:st_gredh, st_gelaran=:st_gelaran, st_elaun=:st_elaun WHERE id=:id");
// Bind all the values to sanitize against injection
// You could do a function that loops through an array of values,
// but this is one way to do it manually
$query->bindParam(':st_nama',$nama);
$query->bindParam(':st_siri',$siri1);
$query->bindParam(':st_siri2',$siri2);
$query->bindParam(':st_siri3',$siri3);
$query->bindParam(':st_jawatan',$jawatan);
$query->bindParam(':st_gred',$gred);
$query->bindParam(':st_gredh',$gredh);
$query->bindParam(':st_gelaran',$gelaran);
$query->bindParam(':st_elaun',$elaun);
$query->bindParam(':id',$id);
$query->execute();
// Print out error info. There may be something of value here
// that may help you figure out why it's trying to update all your rows
// instead of just the one.
print_r($query->errorInfo());
$status = "REKOD BERJAYA DIKEMASKINI!<br/><a href = 'stafflogin.php'><strong>KEMBALI KE LAMAN UTAMA</strong></a>";
} ?>

Related

Trying to get property of non-object when using a SESSION variable in sql query

So I'm currently coding a system where when they log in, they get a specialized panel for their ranking.
By default they are called User, and the Admins get, well, Admin.
When I am trying to get the verification that they are an Admin.
error_reporting(E_ALL); // i've been trying to find the bugs with this
require_once('db.php'); //using the good ol $conn = new mysqli
session_start();
if(!isset($_SESSION['username']) || empty($_SESSION['username'])){
header("location: login.php");
exit;
//to detect if they are logged in or not
}
//here is a failed attempt where I tried to "escape" the $_SESSION variable
// which still doesn't work
$username = $conn->real_escape_string($_SESSION['username']);
// I've tried this query with the $_SESSION variable escaped, with it's alias
// etc.
$query1 = "SELECT * FROM `users` WHERE `rank` = Admin AND
`username`='".$username."'";
// preparing to execute
$result = $conn->query($query1);
// this is where I detect if there is a row, set it to use Admin things
// which I will code later, for now just var holders.
if ($result->num_rows > 0) {
$rank = 'Admin';
} else {
$rank = 'User';
}
I've looked everywhere about property of non-object, but I only find old 2008 posts, which I've tried to implement, but end up not working.
Using XAMPP (apache) with PHP 7
You need to correct your SQL
"SELECT * FROM `users` WHERE `rank` = Admin AND `username`='".$username."'"
to
"SELECT * FROM `users` WHERE `rank` = 'Admin' AND `username`='".$username."'"
Note: single quote between Admin
I would suggest, to use below SQL instead, and store the rank value to SESSION directly.
"SELECT rank FROM `users` WHERE `username`='".$username."'"
Since you are using mysqli consider using prepared statements. By concatenating the variable values into the query string you are prone to SQL injection!.
more on prepared statements here: php.net/prepared-statements.
You were also missing some ' ' in your query, although when using prepared statements you don't need to add any apostrophes on input variables, while the apostrophes around constant strings must be included (they are missing in your example rank='Admin').
Here is the corrected code:
Note: I moved the session_start() to the top of the document to ensure it works properly, since it will not work if any output occurs before calling the function.
session_start();
error_reporting(E_ALL);
require_once('db.php'); //using the good ol $conn = new mysqli
if(empty($_SESSION['username']))
{
header("location: login.php");
exit();
}
$query1 = $conn->prepare("SELECT * FROM users WHERE rank='Admin' AND username=?");
$query1->bind_param("s", $_SESSION['username']);
$query1->execute();
$query1->store_result();
$result = $query1->num_rows;
if ($result > 0)
{
$rank = 'Admin';
}
else
{
$rank = 'User';
}

PHP login script using bind_result in subsequent query mysqli

I'm trying to build a relatively simple PHP login script to connect to MySQL database running on my home server. I know the connection works as I've gotten some data returned as I would expect. However, I am having trouble getting the full script to work.
Essentially, I'm taking in a username/password from the user, and I first do a lookup to get the user_id from the users table. I then want to use that user_id value to do a comparison from user_pswd table (i'm storing usernames and passwords in separate database tables). At one point, I was able to echo the correct user_id based on the username input. But I haven't been able to get all the issues worked out, as I'm pretty new to PHP and don't really know where to see errors since I load this onto my server from a remote desktop. Can anyone offer some advice/corrections to my code?
The end result is I want to send the user to another page, but the echo "test" is just to see if I can get this much working. Thanks so much for the help!
<?php
ob_start();
$con = new mysqli("localhost","username","password","database");
// check connection
if (mysqli_connect_errno()) {
trigger_error('Database connection failed: ' . $con->connect_error, E_USER_ERROR);
}
$users_name = $_POST['user'];
$users_pass = $_POST['pass'];
$user_esc = $con->real_escape_string($users_name);
$pass_esc = $con->real_escape_string($users_pass);
$query1 = "SELECT user_id FROM users WHERE username = ?;";
if ($result1 = $con->prepare($query1)) {
$result1->bind_param("s",$user_esc);
$result1->execute();
$result1->bind_result($userid);
$result1->fetch();
$query2 = "SELECT user_pswd_id FROM user_pswd WHERE active = 1 AND user_id = ? AND user_pswd = ?;";
if ($result2 = $con->prepare($query2)) {
$result2->bind_param("is",$userid,$pass_esc);
$result2->execute();
$result2->bind_result($userpswd);
$result2->fetch();
echo "test", $userpswd;
$result2->free_result();
$result2->close();
} else {
echo "failed password";
}
$result1->free_result();
$result1->close();
}
$con->close();
ob_end_clean();
?>

PHP SQL update failed

In database login replace x with y in column z where username=$usr.
That's what I'm trying to create (at least I hope you understand what I mean).
My code, right now is:
<?php
session_start();
$servernaam = "server";
$susr = "user";
$spswd = "password";
$sdbnaam = "database name";
$usr = $_SESSION['usr'];
$qa = "1";
$conn = mysqli_connect($servernaam, $susr, $spswd, $sdbnaam);
$sql = "UPDATE login SET qa='$qa' WHERE username=$usr";
header("Location: Page_1.php");
?>
Question:
In the database, nothing changes. The cell I want to change stays at it's previous value.
Thanks in advance!
After asking someone who had a lot of knowlage of php and sql I've got the awnser!
This:
$sql = "UPDATE login SET qa='$qa' WHERE username=$usr";
should have been
This:
$sql = "UPDATE `login` SET `qa`='$qa' WHERE `username`='$usr'";
And I didn't add
This:
$result = $conn->query($sql);
wich actually runs the sql script.

Putting MySQL data from database into a variable

I'm making a luck based website and I want to make sure they have enough spins on their account before they spin.
I did see http://www.w3schools.com/php/php_mysql_select.asp but its not really what I'm looking for.
I have these rows with the names: id username email password spins.
I can deduct amounts from spins but I can't put the exact amount of their spins on a PHP variable to put in a $SESSION for a different page.
Here's how much I have so far.
$numSpin = "SELECT * FROM $tbl_name WHERE spins";
Then put it in a $SESSION
$_SESSION['spinNum'] = $numSpin;
How would I go on to doing this? This does not work as is.
It seems as if you are extremely new to coding so I'll try to help you out.
Here is the code you can use and I'll explain below.
<?php
session_start();
$host = 'localhost'; $db = 'db-name'; $user = 'db-user'; $pw = 'db-pwd';
$conn = new PDO('mysql:host='.$host.';dbname='.$db.';charset=utf8', $user, $pw);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$tbl_name = 'table-name-here';
$un = $username;
$sql = "SELECT * FROM $tbl_name WHERE username=:un";
$query = $conn->prepare($sql);
$query->bindValue(':un', $un, PDO::PARAM_STR);
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC);
$totalRows = $query->rowCount();
} catch (PDOException $e) {
die("Could not get the data: " . $e->getMessage());
}
$_SESSION['spinNum'] = $row['name-of-your-field-with-spin-numbers'];
?>
Then...
if($_SESSION['spinNum'] >= 1) {
// allow them to do something
} else {
echo "I'm sorry. It looks like you don't have any spins left. Please try again later.";
}
This code is written using pdo_mysql. You might want to read up on it here.
Line 2 starts your session
Lines 3-5 creates a connection to your database. Make sure to replace "db-name", "db-user" & "db-pwd" with your information.
On line 8 replace "table-name-here" with your database table name
On line 9 you can set "10" to whatever minimum number you want to make sure the account holder has.
On line 19 change "name-of-your-field-with-spin-numbers" to the actual name of the field in your database table that stores the account users available spins.
Now you can use $_SESSION['spinNum'] on your other pages.
Don't forget to use session_start(); at the top of any page where you want to use session variables.

Problems updating MySQL, "username" in a table using PHP

I'm probably not using the best method to create a user system, but it doesn't need to be fancy. I also know that I'm not the most organized
The logins and everything are alright, but I'm having a problem updating the credentials.
For example, I'm allowing users to change their username. I have the "Change Username" (Not that name) form to submit to update-username.php.
I already have mysql_real_escape_string, in the function "cleanString" in another page. My textarea submitting already has the old text in it, so you can change and view it before hand.
$user_id = "";
if(isset($_POST['id']))
{
$user_id = $_POST['id'];
}
$query = "SELECT username,email,display_name,access,password FROM users WHERE user_id='$user_id'";
$results = mysql_query($query);
if(!$results) { //Check to see if query failed
die(mysql_error());
}
$resultsfetch=mysql_fetch_array($results);
$username = $resultsfetch['username'];
$usernamenew = $_POST['usernameinput'];
if(isset($_POST['usernameinput'])) {
$usernamenew = cleanString($_POST['usernameinput']);
}
if($usernamenew !=$username){
$submit = "UPDATE users SET username = '$usernamenew' WHERE user_id = '$user_id'";
mysql_query($submit);
if(!$submit) { //Check to see if query failed
die(mysql_error());
}
}
It's probably something stupid or simple that I missed, or something really huge. Mainly because I am absent minded.
$submit = sprintf("UPDATE users SET username = '%s' WHERE user_id = %d",mysql_real_escape_string($usernamenew),mysql_real_escape_string($user_id));
If the page is loaded, $user_id will be NULL so noting will be updated! Make sure that this page loads, by sending $_POST['id'] . if these things are correct, check this.
"Did the database user have any permission to update the table? "
I have re-arranged your code. added comments where i changed. Try this
if (isset($_POST['id'], $_POST['usernameinput'])) { // Check if both POST id and usernameinput is available
$user_id = (int)$_POST['id']; //assuming this is an integer
$query = "SELECT username,email,display_name,access,password FROM users WHERE user_id='$user_id'";
$results = mysql_query($query);
if (!$results) {//Check to see if query failed
die(mysql_error());
}
if (mysql_num_rows($result) > 0) { //verify if there is really a user with such id
$resultsfetch = mysql_fetch_array($results);
$username = $resultsfetch['username'];
$usernamenew = cleanString($_POST['usernameinput']);
if ($usernamenew != $username) {
$submit = "UPDATE users SET username = '$usernamenew' WHERE user_id = '$user_id'";
if (!mysql_query($submit)) {//Check to see if query failed
die(mysql_error());
}
}
}else{
die("no such user with userid=$user_id");
}
}
Warning: mysql_ function is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used.
So, I guess I figured it out. It's an issue with my code carrying over to the next page.
The code I had been shown only broke the page, whether it be missing an integer, or something else. I'm not 100% sure.
Thanks for all the help guys, but now I know the issue.
EDIT:
I had forgotten to echo the $user_id in my hidden field.

Categories