insert checkbox selected value into database on submit in php [duplicate] - php

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Improve this question
Looking for a good tutorial on how to update a mysql database using a php form?

Updating data can be pretty simple. Let's start with a form, for starters:
<form method="post" action="submit.php">
<input type="text" name="id" value="12" />
<input type="text" name="value" value="Jonathan" />
<input type="submit" />
</form>
This form will send the data over to our submit.php script where we can handle it, and pass it into our database. Since our form method is "post," all of our values will be sent through the POST super array in PHP (this is not the case if you are using file uploaders). So within our submit.php page, we can print the ID and Value values like this:
print $_POST["id"]; // the name of the HTML element is the key
print $_POST["value"]; // again, note that we use the name as the key
You'll want to be careful about passing user-submitted values directly into your queries, so it's nice to clean up the data using a function like mysql_real_escape_string():
$id = mysql_real_escape_string( $_POST["id"] );
$value = mysql_real_escape_string( $_POST["value"] );
The next thing we'll want to do is place these in a query:
$sql = "UPDATE mytable SET value = '{$value}' WHERE id = {$id}";
This is a good time not state that I don't encourage you to use this example code in a live environment. You'll want to look up sql-injections, and how to avoid them. The code I'm providing here is merely an example. After our values are entered, the query that will be ran actually looks like this:
UPDATE mytable SET value = 'Jonathan' WHERE id = 12
Now, in order to run this, we need to be connected to a database.
$host = "localhost";
$user = "root";
$pass = "";
$database = "myDatabase";
$conn = mysql_connect($host, $user, $pass) or die( mysql_error() );
mysql_select_db($database) or die( mysql_error() );
All we're doing here is storing our mysql-user-account credentials in arrays, and passing them into a connect-function. This code should be pretty self-explanatory, but let me know if it's at all unclear.
Once you've got that, you're ready to run your query. Remember that we stored it in an array called $sql:
$result = mysql_query( $sql ) or die( mysql_error() );
That's it. You did it! The data, assuming nothing went wrong, is now updated in your database. There are numerous ways you can increase the information provided back to the user via this script. Also worth noting is that you'll want to sanitize your data before even allowing the script to run - if it's not acceptable data (somebody trying to inject their own queries) you'll want to spit it back.
Check out the MySQL Functions in the PHP Documentation for more goodies, and be sure to return here when you have more specific questions!

Related

Connecting to a database in SQL and PHP [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I'm making a website that uses SQL and PHP functionalities. How do I connect to a database?
I would advise you begin by looking here.
You need to ensure that you have created user credentials with the correct permissions to query the database before you try this. You can do this through the cPanel of your web server (I'm going to assume you are using a web hosted server for this question).
Once you have a working and tested connection to the database, you can then start looking at the mySQLi documentation here. Which will show you how to execute and retrieve results from a database query and how to handle the returned data with PHP.
I see you are seriously downvoted.
I learned it the hard way and I am still learning to post here.
Stack sites are supposed to be searched first. If your question is already answered then people downvote you.
The solution to your question:
In your mysql or phpmyadmin you can set whether you use a password or not. The best way to learn is to set mysql with a password in my opinion. If you will launch a website online finally, you have to take security measures anyway.
If you make contact to your mysql database with you have to set:
username, password, database and servername ( for instance localhost).
The most secure way is using the OOP / prepared method:
$servername ='localhost';
$username='yourname';
$password='12345';
$dbname='name_database';
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($stmt = $conn->prepare("SELECT idnum, col2, col FROM `your_table` WHERE idnum ='5' ")) {
$stmt->execute();
$res = $stmt->get_result();
$qrow = mysqli_num_rows($res);
while ($row = mysqli_fetch_assoc($res)) {
var_dump($qrows); // number of rows you have
$total = implode(" / " , $row);
var_dump($total);
$idnum = $row['idnum'];
var_dump($idnum);
}
The easiest way that I do with my site is make a file called db.php containing:
<?php
$host = 'localhost';
$user = 'root';
$pass = 'password';
$db = 'databasename';
$mysqli = new mysqli($host,$user,$pass,$db) or die($mysqli->error);
..then in the index.php file, at the top:
<?php
require_once('db.php')
?>

Login using base64_encode(md5($Login.$Pass, true)); [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm having some troubles to make a login page. I'm still a beginner at PHP programming, but my login system works if it gets the right login and ID or the right login and email, but it doesnt work with the password.
That's how the password is encrypted on the registering page:
$Salt = base64_encode(md5($Login.$Pass, true));
That's a part of my login system:
$Login = StrToLower(Trim($_POST['login']));
$Password = Trim($_POST['passwd']);
$Password = "0x".md5($Login.$Password);
$sql = "select * from users where name ='".$Login."' and passwd ='".$Password."' ";
Thanks in advance.
Before investing any additional effort in your login code, I would instead highly suggest spending your time researching the topics of SQL injection and PHP's parameterized query features. As posted, your code is a textbook example of login code that is trivial to hack with SQL injection.
Currently, it appears to me that simply entering the following in the "name" login field would allow me to login every time:
' or True;
I apologize that this is not a direct answer to your question but I do not yet have the reputation points to use comments. We all must start learning somewhere but coding a login feature is not to be taken on early in your PHP learning process. Even after years of experience, many people will still advise to never roll your own authentication and instead use an existing framework (good advice in my opinion).
The problem is that when you stored the password you encrypted it like:
base64_encode(md5($Login.$Pass, true))
and when you check the password you are saying that your password is encrypted like:
"0x".md5($Login.$Password);
As an example:
I am using user = 'user' and password = 'password'
You are storing the password like 1ECu0YmhP/lw2sfn6PmHsg== and when you check the password, this is 0xd5745f9425eceb269f9fe01d0bef06ff
Testing Code:
$ php -a
php > echo base64_encode(md5('user'.'password', true));
1ECu0YmhP/lw2sfn6PmHsg==
php > echo "0x".md5('login'.'password');
0xd5745f9425eceb269f9fe01d0bef06ffphp >
Suggestions:
You should sanitize your variables Read: http://php.net/manual/en/function.mysql-real-escape-string.php
mysql is depricated, please start using msqli or PDO (recommended) Read: http://php.net/manual/en/book.pdo.php
For a better and more secure password encryption please use password_hash Read: http://php.net/manual/en/function.password-hash.php & http://php.net/manual/en/faq.passwords.php
I am not sure that you got the Lea Tano answer.
You don't need to decode base64.
You need encode it!!!
:-) so change your code to something like this:
$Login = StrToLower(Trim($_POST['login']));
$Password = Trim($_POST['passwd']);
$Password = base64_encode(md5($Login.$Password, true));
$sql = "select * from users where name ='".$Login."' and passwd ='".$Password."' ";

Access a database without a password? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am new to SQL database and was wondering If a user can have access to a database without providing a password. Or do I have to pass in an empty password field 'PWD' => ''
Sample code with password filed removed:
$connInfo = array(
'Database' => 'mystore',
'UID' => 'admin_user',
/*password field removed*/
'ReturnDatesAsStrings' => true
);
$connectString = sqlsrv_connect('some.sever.name', $connInfo) or die("Can't connect to the database");
$query = 'SELECT * FROM products';
$data = sqlsrv_query($connectString, $query) or die(print_r(sqlsrv_errors(SQLSRV_ERR_ALL), true));
while ($row = sqlsrv_fetch_array($data))
{
//Graduate
echo "<tr>";
echo " " .$row['NAME'] ." - " .$row['EMAIL'] ." ";
echo "</tr><br>";
}
sqlsrv_free_stmt($data);
sqlsrv_free_stmt($query);
?>
I am doing this for a testing purposes and not going to upload this in to a website without a password. Can you please tell me if the syntax of the above code is valid?
There are only two ways to connect to SQL Database:
1) Using SQL Password where you need to specified the credentials
2) or using domain authentication, where the credentials are same as you logged in your pc:
Option 1: Data source=localhost; initial catalog=master;trusted connection = true
Option 2: Data source=localhost; initial catalog=master;Integrated security=SSPI
But you can check the following link where you will find any connection string to most databases and all variants of connection:
http://www.connectionstrings.com/
Regards.
Majahide
The simplest way I can think that you can do what you say is by creating a user with an empty string as a password. You can do that directly in your RDMBS administrator.
However, from my personal point of view, that is a really dumb thing to do:
Anyone who has that username can access your data. Even if you provide read-only permissions to such username, that would be undesirable.
Your attempt to do such thing only denotes that you are lazy and that you are trying to take shortcuts, instead of following the (elementary) rules.
Besides that, instead of asking others to test your code, do it yourself. If you have any specific questions regarding specific problems, then feel free to ask.
Final note: Your question shows that you are using SQL server... but you are tagging as MySQL... was that accidental, or deliberate?

How to update data in an SQL database [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have already build a functioning login page which redirects the user the index.php file.
From previous help, I was able to get the wage and display it on the page depending on which user logs in. This is the table users in the database user_registration
user_id username password email wage
1 johnsmith jsmith99 jsmith#gmail.com 100
2 davidscott dscott95 davidscott#gmail.com 90
The part i am stuck on is creating a functioning form that the user can update their wage to the sql database.
Can someone please help me with the php code?
This is the form i already have in place:
<form id="change-wage" action="update.php" method="post">
<input type="text" id="new_wage" name="new_wage">
<input type="button" value="Save">
</form>
EDIT: this is the code, The aim of it is that the user can update the wage value in the table by filling in the textbox and pressing submit. any Ideas how i can acieve this?>
<?php //CHANGING THE WAGE
$username = '$_SESSION['MM_Username'];';
if (isset($_POST['submit'])){
$wage = $_POST['wage-new'];
//connect to server
mysql_connect ("localhost","root","") or die ("Could not connect");
mysql_select_db("user_registration") or die ("Could not connect to the database");
mysql_query ("UPDATE users SET wage='$wage' WHERE username = '$username'") or die ("Could not update");
}
?>
I wont give you the code unless you demonstrate as previous commentator said. However I will give you a an overview so you can work at it your self.
update.php
Check if your is logged in.
if TRUE, continue.
get the new wage from the form
$new_wage = $_POST['new_wage'];
Be sure to validate and clean the $new_wage variable.
Next stage assumes your using PDO
$params = array($new_wage, $logged_in_user_id);
$update = "UPDATE user_registration SET wage=? WHERE user_id=?";
$pdo->prepare($update);
$pdo->execute($params);
First of all if you are using session variables make sure you start the session -session_start();
$username = '$_SESSION['MM_Username'];';
should be
$username = $_SESSION['MM_Username']; (without single quotes)
$wage = $_POST['wage-new'];
should be
$wage = $_POST['new_wage']; as you named it in your html file
you are selecting database user_registation and I assume it should be user_registration
And last, think about switching to PDO or mysqli.

Create website with a page to show online users including username and picture [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am in the stages of the class diagram, I was creating the class diagram for a website I am planning to create. It was going fine until I reached the stage of wanting to have a web page that displayed the online users e.g. showing their username and profile picture of all online users. I am not sure on how I would do this, the image is of what I have so far. I would appreciate any help or guidance.
Here is my current class diagram http://imgur.com/sgjJwkc
You could also set up a column for user's status (logged in, logged out) and make it toggle between 0 (logged out) and 1 (logged in). You could update this information every 5 seconds (in the background of course) using an AJAX call. Something like this:
//JAVASCRIPT
<script>
$(document).ready(function() {
setInterval(function() {
$.post('Path To PHP File', {x : Pass Variables, y: If You Want}, function(res)
//Do something with the result (res)
);
}, 5000);
});
</script>
//PHP FILE
<?php
//If you passed any variables to the script:
$x = $_POST['x'];
$y = $_POST['y'];
//Connect to your database
$dbConn = "I hope you're using PDO for this.";
//Create your query
$sql = "SELECT * FROM users WHERE status=1";
$res = $dbConn->prepare($sql);
$res->execute();
//Return/echo results
foreach($res as $x) {
echo "<div id='useTheIdToStyleTheResults'>".$x['name']."</div>";
}
?>
res is whatever your php script returns. You can simply run an SQL query on your database in that script to get all users who are logged in and use a foreach() loop to return each item as an html div element. Style those elements to your liking and there you go. If you have questions, just ask!
EDIT:
After reading a little more of your question, SQL JOIN and UNION are a couple of concepts you might want to look into.
http://www.w3schools.com/sql/sql_join.asp
EDIT #2:
//Define Variables
$hostname = '127.0.0.1';
$username = 'userName';
$password = 'passWord';
$dbname = 'database in use';
//Create Connection
try {
$con = new PDO("mysql:host=$hostname;dbname=$dbname",$username,$password);
$con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
//echo "Connected to database"; //Uncomment statement to the left to check for connection
} catch (PDOException $e) {
print "Unable to connect: " . $e->getMessage();
mysql_close($con);
die();
}
?>
I would update a timestamp in the user's row every time they load a page and on the load of the online users I would check for timestamps that are fairly recent.
Pseudocode:
SELECT username,avatar FROM users WHERE last_active >= time()-900;

Categories