I have 3 columns in my table username, password and element. The value of element is 1. So I created a webpage If user insert the correct username and password I want my PHP to check that If element = 1 then do something I want and change element to 0. But If it is 0 so PHP do nothing. My problem is it's display white screen.
<?php
require_once("function/func_connect.php");
require_once("function/func_check.php");
require_once("function/websend.php");
$objLogin = checkPassword($_POST['user_name'],$_POST['user_password'],$Cfg["table"]["user"]);
if($objLogin == false)
{
include("state/login_failed.html");
exit();
}
if($objLogin == true)
{
// I think the problem cause here How do I fix?
mysql_query("SELECT element FROM authme WHERE username = $_POST['user_name']");
echo "success";
}
mysql_close();
?>
Thank you and sorry for my bad english.
Your basic error is you are not wrapping your string value in quotes.
mysql_query("SELECT element FROM authme WHERE username = $_POST['user_name']");
should be
mysql_query("SELECT element FROM authme WHERE username = '$_POST['user_name']'");
But, just as important, you are wide open to SQL injections. You need to fix that ASAP.
You also need to turn on error reporting so you can see your errors instead of getting just a white screen.
FYI, you shouldn't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Related
This question already has answers here:
mysqli_affected_rows in PHP insert
(3 answers)
Closed 6 years ago.
I'm working with PHP and mysqli, what the program is doing is that it is asking for a reset code and email address if the email add and reset code are found in the database it sets the password,this part of the function is working,
I need help with this part: what I need to do is tell the user if the password was set or not so if the update was successful or not.
What I'm working on:
$uinsert = "UPDATE member SET password = '$password' WHERE emailadd = '$emailadd' AND resetCode = '$resetcode'";
$update = mysqli_query($mysqli, $uinsert) or die(mysqli_error($mysqli));
if(mysqli_affected_rows($update) == 1 ){ //ifnum
header("location: ../index.php"); // Redirecting To Other Page
}
else{
echo "<script> alert('Incorrect code, try again!');</script>";
}
Note: $mysqli is my connection string
"#Fred-ii- Thank you so much that works! – Coffee coder 58 secs ago"
Use if(mysqli_affected_rows($mysqli) >0 ) or no comparison at all.
Sidenote: ==1 is only comparing for 1, as opposed to >0 which you may be trying to update more than one row. However and on the rare occasion, >0 is required where this has also happened to me before; that is the reason of my answer.
affected_rows() uses the connection, not the one for the query.
http://php.net/manual/en/mysqli.affected-rows.php
Plus, if you're storing plain text passwords, use password_hash() since it's much safer:
http://php.net/manual/en/function.password-hash.php
Sidenote: If you do decide to move over to that function, make sure that you do not manipulate the password at all. Hashing/verifying it takes care of that and you may be doing more harm than good in doing so and limiting passwords.
I.e.: A valid password of test'123 would be interpreted as test\'123 and rendering FALSE when using real_escape_string() for example.
Or you may still be using hash_hmac as per your other question Comparing/check if correct Password from mysqli database [hash_hmac]
and a prepared statement:
https://en.wikipedia.org/wiki/Prepared_statement
It is also best to add exit; after header. Otherwise, your code may want to continue to execute.
header("location: ../index.php");
exit;
Change the parameter of mysqli_affected_rows(), the parameters must be the mysql connection
mysqli_affected_rows($update)
to
mysqli_affected_rows($mysqli)
Please see this reference
https://www.w3schools.com/php/func_mysqli_affected_rows.asp
if (mysqli_affected_rows($mysqli) == 1 ) {
Because mysqli_affected_rows() does not use the query $update as its parameter, it uses the connection variable: $mysqli
pass your mysqli connection object ($connection) to mysqli_affected_rows(connection_object) to check affected rows.
connection_object is like - $con=mysqli_connect("localhost","bd_user","db_password","your_db_name");
So , code will be
if(mysqli_affected_rows($con)== 1 ){
header("location: ../index.php");
}
Good evening everyone, I'm having issues with my below code, Variable $uname is declared from a http post but for some reason the print out the the err log stays blank where it should show the results of the MySQL query
Field in table is called firstname (no caps)
$da= mysqli_query($c,
"SELECT * FROM users WHERE username='".$uname."'") or die(mysqli_error($c));
while ($row = mysqli_fetch_assoc($da)) {
error_log("User $Uname: match.");
error_log("FN : ".$row['firstname']."");
}
Any ideas ?
Add a message to tell you if no results were found by the query.
Since there can be only one user with a given username (I assume), you don't need a while loop. Just fetch that one row.
$row = mysqli_fetch_assoc($da));
if ($row) {
error_log("User $uname: match.");
error_log("FN : ".$row['firstname']."");
} else {
error_log("User $uname: no match.");
}
You also had a typo in your echo statement, $Uname should have been $uname.
First of all use a prepared statement: for security reasons you should never trust user inputs, prepared statements do the escaping for you.
Other than that I only see two reasons why nothing is logged:
error reporting is turned off ( this seems unlikely since you expect to see something in there)
the query is returning an empty result set and the while loop is skipped
try to print $uname or the full query and execute it
The PHP code I have inserts the HTML form data from the previous page into the database and in the same SQL statement return the PostID back from the inserted data. The PostID column is AUTO_INCREMENTING. I have been researching this problem for a week or two now and have found no significant solutions.
<?php
include("dbconnect.php");
mysql_select_db("astral_database", $con);
session_start();
$username = $_SESSION['username'];
$forumtext = $_POST["forumtext"];
$forumsubject = $_POST["forumsubject"];
$postquery = 'INSERT INTO Forums (Creator, Subject, Content) VALUES ("$username", "$forumsubject", "$forumtext"); SELECT LAST_INSERT_ID()';
$result = mysql_query($postquery, $con);
if (!$con) {
echo "<b>If you are seeing this, please send the information below to astraldevgroup#gmail.com</b><br>Error (331: dbconnect experienced fatal errors while attempting to connect)";
die();
}
if ($username == null) {
echo "<b>If you are seeing this, please send the information below to astraldevgroup#gmail.com</b><br>Error (332: Username was not specified while attempting to send request)";
die();
}
if ($result != null) {
echo "last id: " . $result;
$fhandle = fopen("recentposts.txt", "r+");
$contents = file_get_contents("recentposts.txt");
fwrite($fhandle, json_encode(array("postid" => $result, "creator" => $username, "subject" => $forumsubject, "activity" => time())) . "\n" . $contents);
fclose($fhandle);
mysql_close($con);
header("location: http://astraldevgroup.com/forums");
die();
} else {
die("<b>If you are seeing this, please send the information below to astraldevgroup#gmail.com</b><br>Error (330: Unhandled exception occured while posting forum to website.)<br>");
echo mysql_error();
}
mysql_close($con);
?>
First off, the mysql_query doesn't return anything from the SELECT statement. I haven't found anything that will properly run both the SELECT statement and the INSERT statement in the same query. If I try running them in two different statements, it still doesn't return anything. I tried running the following statement in the SQL console and it ran perfectly fine without errors.
INSERT INTO Forums (Creator, Subject, Content) VALUES ("Admin", "Test forum 15", "This is a forum that should give me the post id."); SELECT LAST_INSERT_ID();
The mysql_query function does not run multiple statements
Reference: http://php.net/manual/en/function.mysql-query.php
mysql_query() sends a unique query (multiple queries are not supported) to the currently active database on the server ...
That's one reason your call to mysql_query isn't returning a resultset.
The most obvious workaround is to not try to run the SELECT in the same query. You could use a call to the mysql_insert_id instead.
Reference: PHP: mysql_insert_id http://php.net/manual/en/function.mysql-insert-id.php
Answers to some of questions you didn't ask:
Yes, your example code is vulnerable to SQL Injection.
Yes, the mysql_ interface has been deprecated for a long time.
Yes, you should being using either PDO or mysqli interfaces instead of the deprecated mysql_ functions.
FOLLOWUP
Re-visiting my answer, looking again at the question, and the example code.
I previously indicated that the code was vulnerable to SQL Injection, because potentially unsafe values are included in the SQL text. And that's what it looked like on a quick review.
But looking at it again, that isn't strictly true, because variable substitution isn't really happening, because the string literal is enclosed in single quotes. Consider what the output from:
$foo = "bar";
echo '$foo';
echo '"$foo"';
Then consider what is assigned to $postquery by this line of code:
$postquery = 'INSERT ... VALUES ("$username", "$forumsubject", "$forumtext")';
Fixing that so that $username is considered to be a reference to a variable, rather than literal characters (to get the value assigned to $username variable incorporated into the SQL text) that would introduce the SQL Injection vulnerability.
Prepared statements with bind placeholders are really not that hard.
$result will never be null. It's either a result handle, or a boolean false. Since you're testing for the wrong value, you'll never see the false that mysql_query() returned to tell you that the query failed.
As others have pointed out, you can NOT issue multiple queries in a single query() call - it's a cheap basic defense against one form of SQL injection attacks in the PHP mysql driver. However, the rest of your code IS vulnerable other forms of injection attacks, so... better start reading: http://bobby-tables.com
Plus, on the logic side, why are you testing for a null username AFTER you try to insert that very same username into the DB? You should be testing/validating those values BEFORE you run the query.
I need to insert data from a table named wishlist into another table (wishlisturi_salvate) and altough the insert looks ok, something doesn't work right and no inseration is being made.Thanks for the help, I really appreciate it.
<?php
session_start();
include ('conex.php');
$sel2="select id_wishlist from wishlisturi_salvate";
$que2=mysql_query($sel2);
while($rez2=mysql_fetch_array($que2))
{
$a=$rez2['id_wishlist'];
}
$id_wishlist=$a;
echo $id_wishlist;
$sel="SELECT * from wishlist";
$que=mysql_query($sel);
while ($rez=mysql_fetch_array($que))
{
$insert="INSERT INTO 'wishlisturi_salvate'('id_user', 'id_wishlist', 'id_produs', 'nume_produs', 'pret_produs', 'cantitate_produs', 'suma')
VALUES('".$_SESSION['id']."','".$id_wishlist."','".$rez['id_produs']."','".$rez['nume_produs']."','".$rez['pret_produs']."','".$rez['cantitate_produs']."','".$rez['suma']."')";
if(!mysql_query($insert)) echo "fml";
echo "<br>".$insert;
}
if(mysql_query($insert))
{
header("location:user.php");
}
else echo "Nu s-a facut inserarea";
?>
No insertion is being made most likely because of the errors inside the query:
Right of the bat, there is already an error:
INSERT INTO 'wishlisturi_salvate'('id_user', 'id_wishlist', 'id_produs', 'nume_produs', 'pret_produs', 'cantitate_produs', 'suma')
The proper quoting of table/column names must be backtickts, not single quotes
INSERT INTO `wishlisturi_salvate` (`id_user`, `id_wishlist`, `id_produs`, `nume_produs`, `pret_produs`, `cantitate_produs`, `suma`)
Or just omit them, its okay in this case.
Obligatory Note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Sidenote:
If you haven't already, always turn on error reporting:
error_reporting(E_ALL);
ini_set('display_errors', '1');
First of all I'll rcomend you to use PDO or mysqli instead of mysql to avoid SQL injection.
Anyway, if you want to insert elements from one table to another one I recommend you to use an insert statment with a subselect. That way it'll be faster and you will waste less memory.
Not an answer, more of an observation ; It will be far more efficient to loop through your results to build up a single SQL insert multiple statement that you send to the db once.
$insert = "INSERT INTO 'wishlisturi_salvate'('id_user', 'id_wishlist', 'id_produs', 'nume_produs', 'pret_produs', 'cantitate_produs', 'suma') VALUES ";
foreach( of your results ){
$insert .= "(x,y,z,a,b,c,d),";
}
// now trim off last comma, then send to db.
// or create an array then join it to the $insert
Same info can be read here : http://www.electrictoolbox.com/mysql-insert-multiple-records/
So i have this so far..
if(isset($_POST['Decrypt']))
{
$dbinary = strtoupper($_POST['user2']);
$sqlvalue = "SELECT `value` FROM `license` WHERE `binary` = '$dbinary'";
$dvalue = mysql_query($sqlvalue) or die(mysql_error());
}
I have a field where the user enters a binary code which was encrypted. (The encrypt part works). This is supposed to retrieve the value from the database. When ever i do it, instead of the value showing up, it says "Resource id #11".
There's nothing wrong with your quoting. In fact, everything looks right so far.
The thing is, right now $dvalue is just a resource to the SQL database. You have to fetch the contents with one more line:
$dvalue = mysql_fetch_array($dvalue);
In the future, you might want to start using PDO or MySQLi instead of the mysql functions, because those are deprecated as of 5.5.0. The advantage of PDO and MySQLi is that they offer security from SQL Injection, which is when users run their own SQL code by inputting something like x'; DROP TABLE members; --.
Don't use the mysql_ functions anymore. They are deprecated. Use PDO or MySQLi instead.
That being said, you are only running the query, and not retrieving any results. You will have to call a function like mysqli_fetch_array to get data from the resource ID that mysqli_query will return.
My advice is to go back to the tutorials and documentation and try again with one of these other extensions. Good luck.
Read this page: W3 Schools page on MySQL select useage. Basically $dvalue is a result set id and you'll need to actually fetch the array out of the database in another step. Also, mysql_* functions are deprecated. Lookup and use the mysqli_* functions instead.
while($row = mysqli_fetch_array($dvalue))
{
echo $row['value'];
echo "<br>";
}