I'm currently trying to insert username, pw to a DB, and check if the username already exists.
The problem is that the SQL (select) syntax doesn't work, nor does the (insert). I've checked around for a couple of hours in forums and Stackoverflow, and my current code is the following.
What might be the problem?
Thanks, Jimmie.
<?php
$servername = "localhost";
$username = "name";
$password = "pw";
$dbname = "dbaname";
$mysqli = new mysqli($servername, $username, $password, $dbname);
if ((isset ($_POST["identity"])) && (isset ($_POST["pin"])) && (isset ($_POST["token"])))
{
$identity = htmlspecialchars($_POST['identity'], ENT_QUOTES, "ISO-8859-1");
$pin = htmlspecialchars($_POST['pin'], ENT_QUOTES, "ISO-8859-1");
$token = htmlspecialchars($_POST['token'], ENT_QUOTES, "ISO-8859-1");
echo "$identity";
if($token == "xyz13D;A##:!#")
{
$result = $mysqli->query("SELECT `identity` FROM Users WHERE `identity` = '" . $identity . "'");
if($result->num_rows == 0)
{
echo "successCreat";
// Perform queries
mysqli_query($mysqli,"SELECT * FROM Users");
mysqli_query($mysqli,"INSERT INTO Users (identity,pin,userActivity, identityCreated) VALUES ('$identity', '$pin',1,now())");
}
else
{
echo "failureCreate";
}
}
else
{
echo"Wrong Key";
}
}
$mysqli->close();
?>
Assuming that identity is a primary key, then you can check the error flags after executing an INSERT query to see if an error occurred.
mysqli_query( $mysqli, "INSERT INTO ... " ); //< ... Represents query
if (mysqli_error( $mysqli )) {
echo "Failure";
}
else {
echo "Success";
}
Also, you should properly escape input as stated in the comments. In addition, you should check whether or not the connection attempt was successful using mysqli_connect_error.
Finally, there might be an issue in your SQL suntax which mysqli_error will also catch. A last possibility is that the POST data isn't being set properly and the code is being ignored completely.
Related
Good day,i am trying to insert data into mysql table using php its kinda working but i can't see data in phpmyadmin
<?php
$con=mysqli_connect('localhost','root','');
if(!$con)
{
echo("not connected");
}
if(!mysqli_select_db($con,'exam'))
{
echo 'db not selected';
}
$header = $_POST['header'];
$date = $_POST['date'];
$categ = $_POST['categ'];
$moder = $_POST['moder'];
$posttxt = $_POST['posttxt'];
$theme = $_POST['theme'];
$author = $_POST['author'];
$sql = "INSERT INTO postex (header,date,categ,moder,posttxt,theme,author) VALUES ('$header','$date','$categ','$moder','$posttxt','$theme','$author')";
if
(empty($header) || empty($date) || empty($categ) || empty($moder) || empty($posttxt) || empty($theme) || empty($author))
{
echo "<Br>feel the fields!!!";
}
else{
echo("<br>added,wait for redirect");
}
?>
Ok, before anymore wrong answers come up using mysql_, it's mysqli_query($con, $sql) that wasn't used to execute the query.
RTM http://php.net/manual/en/mysqli.query.php
and take care of that sql injection that you're leaving yourself open to, if/when you go live with this.
https://en.wikipedia.org/wiki/SQL_injection
with a prepared statement
https://en.wikipedia.org/wiki/Prepared_statement
while making sure the POST arrays do contain values (and the form uses a POST method with matching named inputs) and that there are no characters passing through that MySQL could complain about, for example: apostrophes.
Escape the data going in, in any respect.
Check for errors via PHP and the query:
http://php.net/manual/en/function.error-reporting.php
http://php.net/manual/en/mysqli.error.php
Nota:
You should first check if any of the fields are (not) empty, then execute the query.
I.e. and pseudo conditionals:
if(none empty and good to go){
// execute the query
}
else{
// do something else
}
Plus, if you're using your entire code inside the same file, being the form and php/mysql, then you should check if any of the POST arrays are set/not empty first. That will throw a few errors and give you undesired results.
<?php
function db(){
$servername = "servername";
$username = "username";
$password = "password";
$database = "database";
// Create connection
$conn = new mysqli($servername, $username, $password,$database);
$conn->query("SET CHARACTER SET utf8");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
return false;
}else{
return $conn;
}
}
$data=db();
$insert="INSERT INTO movies (bla1, bla2, bla3) VALUES (blavalue1, blavalue2, blavalue3)";
$dotaz=mysqli_query($data,$insert);
if($dotaz){
echo "OK";
}else{
echo "Wrong";
}
?>
I believe my PHP to be functioning perfectly, therefore I think it's a query error. When I proceed, with form details stored in the session... it happily returns my Posted information but doesn't seem to be pulling anything from my database - there is a row in my database containing the email address I am using. Does anybody see anything blatantly wrong with this PHP?
Thanks for your help.
<?php
session_start();
$servername = "localhost";
$username = "privatedbroot";
$password = "not4ulol";
$dbname = "pdb_inventory";
$status = $_GET["action"];
$_SESSION["Cemail"] = $_POST["CEMAIL"];
$_SESSION["Access"] = md5($_POST["ACCESS"]);
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT CEMAIL, ACCESS FROM POPU WHERE `CEMAIL`= ".$_SESSION['Cemail'];
echo $sql;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if ($_SESSION["Access"] == $row["ACCESS"]){
echo "password correct!";
} else {
echo "password wrong!";
}
}
}else{
echo "ur email is wrong m8.";
}
?>
Try this:
$cemail = $_SESSION['Cemail'];
$sql = "SELECT CEMAIL, ACCESS FROM POPU WHERE `CEMAIL`= '$cemail'";
I have got a MySQL Table named 'MainData' and i have 3 columns 'username', 'email' and 'pass'. I have a snipped of my code, it all works except when i try to convert the users $_POST input into an md5 hash. When i leave the md5 encryption's off and all of the passwords are visible in the database it works but when i use md5 it doesnt work and just echo's 'Sorry, the username or password was incorrect.'
Here is the snipped of my code:
<?php
$servername = "localhost";
$username = "avxtechn_benph64";
$password = "admin123";
$dbname = "avxtechn_users";
$dbtable = "MainData";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$usr = $_POST["user"];
$psr = $_POST["password"];
$sql = "SELECT username, pass FROM " . $dbtable;
$result = $conn->query($sql);
$nameCount = 0;
$UserName = 0;
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
if ( $usr == $row["username"] && md5($psr) == $row["pass"]) {
$nameCount = $nameCount + 1;
$UserName = $usr;
}
}
} else {
echo "nil";
}
if ($nameCount > 0) {
echo ' Welcome back, ' . $UserName;
}else{
echo 'Sorry, that username or password was incorrect.';
}
$conn->close();
?>
This is the full code.
Here is the PHPMyAdmin database:
I guess that your problem is you stored passwords in your database before as a plain text.
So to get your authentification work now you should:
if ( $usr == $row["username"] && $psr == $row["pass"]) {
or
if ( $usr == $row["username"] && (md5($psr)) == md5($row["pass"])) {
but the best way is to convert your data (make backup first for sure) by running this query:
UPDATE MainData SET pass = MD5(pass)
then your code can start to work. but check the pass type before converting to assure that it can hold larger strings.
I would strongly recommend to change your code.
Use the following SQL code:
$result = $conn->query('SELECT count(*) as nr WHERE username = ' . $username . ' AND pass = MD5('. $password .'));
You should have an integer of 1 in "nr" if the login is valid.
Make Mysql do a single count of the usernames having that user/password combination.
Also MySQL is able to do the MD5 method for you.
( Instead of looping all the results in your resultset. )
EDIT:
Please sanitize your input before adding it into queries.
I am trying to get this piece of code to check if the line already exists in the database.
These lines get inserted into the database:
512150 # Merlinz is banned permanently by SO_Conner. # banned untill never for RDM
Now this piece of code checks if it already exists in the DB, if it doesn't exist we insert it.
$search = "permanently";
$logfile = "ban_list.txt";
$timestamp = time();
// Read from file
$file = fopen($logfile, "r");
?> <head> <title>Searching: <?php echo $search ?></title> </head> <?php
while( ($line = fgets($file) )!= false)
{
if(stristr($line,$search))
{
$check = mysql_query("SELECT * FROM `pincodes` WHERE `Pincode` = '$pincode' ");
if(mysql_num_rows($check) == 1) {
die(); }
else
{
$servername = "localhost";
$username = "root";
$password = "pass";
$dbname = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(stristr($line,$search))
$sql = "INSERT INTO `ingamebanlist` (Ban, Timestamp) VALUES ('$line', '$timestamp')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
// case insensitive
echo "<font face='Arial'> $line </font><hr>";
}
}
Like I said, it is still inserting it into my Database even though the line is present in the database.
Thanks }
if(mysql_num_rows($check)>0) {
echo " ";
}
else
{
change your line of code to this,
this would check if it already exist.
Flies Away
Try checking in the following manner
if(mysql_num_rows($check) !== FALSE)
Also try printing the query to see how the value is embedding for debugging purpose...
If it's a ban list based on a unique username why not alter the table to make the column unique. This code will also delete duplicates in the column 'Ban'.
ALTER IGNORE TABLE ingamebanlist ADD UNIQUE (Ban);
Next, mysql_num_rows() is deprecated in php 5.5
http://php.net/manual/en/function.mysql-affected-rows.php
Your best bet (even if your mysql functions work) is to change the mysql function calls to mysqli function calls. They are more secure and up to date.As well as making sure there is a constant in your code so your not switching between them.
If you change the mysql commands to mysqli this should work.
mysqli_affected_rows($conn);
Lastly, if you change the 'Ban' column to unique and make use of the mysqli_affected_rows this code should be all you need to insert when doesn't exist.
mysqli_query($conn,"INSERT INTO `ingamebanlist` (Ban, Timestamp) VALUES ('$line', '$timestamp')");
$num = mysqli_affected_rows($conn);
if($num > 0)
{
echo "Successfully Inserted";
}
else if($num == 0)
{
echo "Line already exists";
}
else
{
echo "Insert Error";
}
I have to give users the ability to log in for an assignment. At first, it seemed to me this script was simple enough to work, but everytime I try to log in with an existing account it gives me the "login failed" message. I don't know where my mistake lies. It's a PostgreSQL database, I'll enclose an image of it below.
<?php
require 'databaseaccess.php';
try {
$conn = new PDO('pgsql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USERNAME,DB_PASSWORD);
} catch (PDOException $e) {
print "Error: " . $e->getMessage() . "\n";
phpinfo();
die();
}
$username = $_POST['username'];
$password = $_POST['password'];
$tablename = "users";
// sql-injection counter
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$qry = $conn->prepare("SELECT * FROM $tablename WHERE userid = :username and userpass = :password");
$qry->bindParam(':username', $username, PDO::PARAM_STR, 16);
$qry->bindParam(':password', $password, PDO::PARAM_STR, 16);
$qry->execute();
$result = pg_query($qry);
$count = pg_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if ($count == 1) {
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $username;
header("location:logingelukt.php");
} elseif ($count = -1) {
echo "there has been an error";
} else{
print $count;
echo "login failed";
}
?>
I have no problems connecting to the database, so that's not an issue, it's just that it always sees $count as something else than zero. Another oddity is that the print $count command doesn't output anything.I use the account I made with postgresql outside of the page, which is just admin:admin. Also, I'm sure the right variables are getting passed from the form.
EDIT: After using var_dump($result), as advised by kingalligator, it seems that $result is indeed NULL, thus empty. I'm gonna try using fetch() instead of pg_query().
I think the issue is that you're mixing PDO and pg_ functions.
Replace:
$result = pg_query($qry);
$count = pg_num_rows($result);
With:
$result = $qry->fetchAll();
$count = count($result);
PDO Function reference can be found here: http://www.php.net/manual/en/class.pdostatement.php
Have you confirmed that you're actually getting data returned from your query? Try this:
var_dump($result);
To ensure that data is being returned from your query. You can still have a successful connection to a database, yet have a query that returns nothing.
You probably should check your column userid at WHERE clause. I don't know the table columns, but is strange that 'userid' has the name of the user in:
"SELECT * FROM $tablename WHERE userid = :username and userpass = :password"
Maybe it is causing the problem.