Cant veryfi data from mysql database - php

I have a table ver_code in my database and inside the table there is only one row called code and i have inserted few verification code like ABCDEF , GHIJKL for instance now my following code has failed to verify code from my table using a simple form below
<?php
if (isset($_POST['ver_code']))
{
$ver_code = $_POST['ver_code'];
if(!empty($ver_code)){
try{
$conn = new PDO("mysql:host=localhost;dbname=pro1", "pro1", "4931//4931");
}
catch(PDOException $pe)
{
die('Connection error, because: ' .$pe->getMessage());
}
$sql = "SELECT `code` FROM `ver_code`";
$stmt = $conn->query($sql);
if(!$stmt)
{
die("Execute query error, because: ". $conn->errorInfo());
}
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$row = $stmt->fetch();
if($row['code'] == $ver_code['code']){
echo "Account Verified ! ";
}else{
echo "Invalid Verification Code !";
}
}else{
echo "Plz enter a verification code ... ";
}
}
?>
<form action="index2.php" method="POST" >
<input type="text" name="ver_code" />
<input type="submit" value="Verify" />
</form>

i doubt this line
$row['code'] == $ver_code['code']
it should be
$row['code'] == $ver_code; as $ver_code is simple post variable not an array.
EDIT: if you need to verify from all rows
$stmt = $conn->prepare("SELECT `code` FROM `ver_code` where code= ?");
$stmt->bindParam(1,$ver_code);
$stmt->execute();
if($stmt->rowCount()>0){
echo "Account Verified ";
}else{ echo "Invalid Verification Code";}

Related

PHP code inserts into sql db with text box inputs but not with select options (dropdowns)

Through hours of research and looking through code in questions submitted on this site, I was finally able to get the select options (dropdowns) to pull data from my database tables into the dropdown lists on my html form.
However, my issue is that when the fields on the form were inputs they inserted the new information into the database just fine. Unfortunately, now that I've implemented the dropdown lists as part of the form, none of the information from the form inserts into the database anymore. Clicking on the 'submit' button returns the response that it was successful, but when I check the table in the database, the new information is not there.
I'm sorry I haven't been able to figure this piece of functionality out by myself. I noticed my last question received negative feedback, so I'm leary to even submit this one, but I really need some help.
Will you please look through the following code and let me know what I'm missing or have coded incorrectly? I just need to know what I need to do to make the selected values from the dropdown lists insert into the 'dvd' table and 'categoryname' and 'genretype' fields, respectively.
<?php
session_start();
//include the header
include ('../main/header.php');
// Check if the form has been submitted.
if (isset($_POST['submitted'])) {
require_once ('../../../mysqli_connect.php'); // Connect to the db.
$errors = array(); // Initialize error array.
// Check for a first name.
if (empty($_POST['title'])) {
$errors[] = 'You forgot to enter a title.';
} else {
$title = mysqli_real_escape_string($dbc, $_POST['title']);
}
// Check for a category.
if (empty($_POST['numavail'])) {
$errors[] = 'You forgot to enter quantity purchased.';
} else {
$numavail = mysqli_real_escape_string($dbc, $_POST['numavail']);
}
// Check for a category.
if (empty($_POST['categoryname'])) {
$errors[] = 'You forgot to enter a category.';
} else {
$categoryname = mysqli_real_escape_string($dbc, $_POST['categoryname']);
}
// Check for a genre.
if (empty($_POST['genretype'])) {
$errors[] = 'You forgot to enter a genre.';
} else {
$genretype = mysqli_real_escape_string($dbc, $_POST['genretype']);
}
if (empty($errors)) { // If everything's OK.
// Add the movie to the database.
// Check for existing record.
$query = "SELECT id FROM dvd WHERE title='$title'";
$result = mysqli_query($dbc, $query);
if (mysqli_num_rows($result) == 0) { // if there is no such movie title
$query = "INSERT INTO dvd (title, numavail, categoryname, genretype)
VALUES ('$title', '$numavail', '$categoryname', '$genretype')";
// Make the query.
if ($result) { // If it ran OK.
echo "<p><b>Success! The new movie has been added.</b></p>";
echo ('<p><div style="margin-top:30px;">');
echo ('<span style="float:left;">');
echo ('<FORM METHOD="LINK" ACTION="../dvd/index.php"><INPUT TYPE="submit" VALUE="Back to DVDs" STYLE="margin:0px 15px 0px 0px;"></form></span></div></p>');
echo ('<br style="clear:both;"></br>');
exit();
} else { // If it did not run OK.
$errors[] = 'The movie could not be added due to a system error. We apologize for any inconvenience.'; // Public message.
$errors[] = mysqli_error($dbc); // MySQL error message.
}
} else { // Title is already taken.
$errors[] = 'The movie title entered already exists.';
}
} // End of if (empty($errors)) IF.
mysqli_close($dbc); // Close the database connection.
} else { // Form has not been submitted.
$errors = NULL;
} // End of the main Submit conditional.
// Begin the page now.
if (!empty($errors)) { // Print any error messages.
echo '<p class="error">The following error(s) occurred:<br />';
foreach ($errors as $msg) { // Print each error.
echo "$msg<br />";
}
echo '</p>';
echo '<p style="color:red; font-weight:bold;"><em>Please try again.</em></p></br>';
}
// Create the form.
?>
<h1>Add a Movie</h1>
<h2>Please complete all of the fields below:</h2>
<form action="../dvd/add.php" method="post">
<p>Title: <input type="text" name="title" size="15" maxlength="15" value="<?php echo $_POST['title']; ?>"></p>
<p>Quantity Purchased: <input type="text" name="numavail" size="15" maxlength="30" value="<?php echo $_POST['numavail']; ?>"></p>
<p>
<?php
include ('../../../mysqli_connect.php'); // Connect to the db.
$ddlquery = "SELECT categoryname FROM category ORDER BY categoryname ASC";
$ddlresult = mysqli_query($dbc, $ddlquery) or die("Bad SQL: $ddlquery");
echo 'Category: <select name="categoryname" size="1">';
while($ddlrow=mysqli_fetch_array($ddlresult, MYSQLI_ASSOC)){
echo "<option value='".$ddlrow['categoryname']."'>" . $ddlrow['categoryname'] . "</option>";
}
echo "</select>";
?>
<p>
<?php
$ddlquery2 = "SELECT genretype FROM genre ORDER BY genretype ASC";
$ddlresult2 = mysqli_query($dbc, $ddlquery2) or die("Bad SQL: $ddlquery");
echo 'Genre: <select name="genretype" size="1">';
while($ddlrow2=mysqli_fetch_array($ddlresult2, MYSQLI_ASSOC)){
echo "<option value='".$ddlrow2['genretype']."'>" . $ddlrow2['genretype'] . "</option>";
}
echo "</select>";
?>
<p>
<input type="submit" name="submit" value="Submit">
<input type=reset value=Reset>
<input type="hidden" name="submitted" value="TRUE"></p>
</form>
<?php
// Include footer.php
include("../../includes/footer.php");
?>
You forgot to actually run the insert into database
$result = mysqli_query($dbc, $query);
if (mysqli_num_rows($result) == 0) { // if there is no such movie title
$query = "INSERT INTO dvd (title, numavail, categoryname, genretype)
VALUES ('$title', '$numavail', '$categoryname', '$genretype')";
// Make the query.
$result = mysqli_query($dbc, $query); // <---- ADD HERE
if ($result) { // If it ran OK.
....

mysqli query returns the column name as one row in php

this is my login.php file
<?php require ("database_connect.php");?>
<!DOCTYPE html>
<html>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"])?>">
Name : <input type="text" name="name"><br/>
Password : <input type = "text" name="password"><br/>
<input type="submit" name="login" value="Log In">
</form>
<?php
$name=$password="" ;
if($_SERVER["REQUEST_METHOD"]=="POST" and isset($_POST["login"])){
$name = testInput($_POST["name"]);
$password = testInput($_POST["password"]);
}//if ends here
//testInput function
function testInput($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
}//testInput ends here
if(isset($_POST["login"]) && isset($_POST["name"]) && isset($_POST["password"]) && !empty($_POST["name"]) && !empty($_POST["password"])){
//echo "Name ".$_POST["name"];
if($result = mysqli_query($conn,"SELECT * FROM users WHERE name='$name' and password='$password'")){
if($result->num_rows > 1){
echo "you are logged in";
while ($row = $result->fetch_assoc()){
echo "Name ".$row["name"]."-Password ".$row["password"];
}//while loop ends here
}//if ends here
/* free result set */
$result->close();
}
else{
print "Wrong Credentials "."<br>";
die(mysqli_error($conn));
}
}
//close connection
$conn->close();
?>
</body>
</html>
One problem is that my query
if($result = mysqli_query($conn,"SELECT * FROM users WHERE name='$name' and password='$password'")) returns column names as one row. I don not know whether it is ok ? The other thing whether I put wrong name or password or correct , in both cases I do not get any output. What I am doing wrong here ? And if you can please tell me how to write a mysqli query in php with correct format with a comprehensive example . I searched on google but there are different ways so I am confused specially when column names and variables come in the query.
Your test_input function is weak/unsafe, also, mysql_query is depricated, use mysqli and prepared statements as explained here: http://php.net/manual/en/mysqli.prepare.php
Furthermore, I included a section of code I use for my login system (bit more sophisticated using salts etc, you should be able to compile it in a piece of script suitable for you.
//get salt for username (also check if username exists)
$stmtfc = $mysqli->stmt_init();
$prep_login_quer = "SELECT salt,hash,lastlogin FROM users WHERE name=? LIMIT 1";
$stmtfc->prepare($prep_login_quer);
$stmtfc->bind_param("s", $username);
$stmtfc->execute() or die("prep_login_quer error: ".$mysqli->error);
$stmtfc->store_result();
if ($stmtfc->num_rows() == 1) {
$stmtfc->bind_result($salt,$hash,$lastlogin);
$stmtfc->fetch(); //get salt
$stmtfc->free_result();
$stmtfc->close();
I don't know what do you mean but thats how i query mysqli
$query = mysqli_query($db, "SELECT * FROM users WHERE name='$name' AND password='$password'");
if($query && mysqli_affected_rows($db) >= 1) { //If query was successfull and it has 1 or more than 1 result
echo 'Query Success!';
//and this is how i fetch rows
while($rows = mysqli_fetch_assoc($query)) {
echo $rows['name'] . '<br />' ;
}
} else {
echo 'Query Failed!';
}
i think thats what you mean
EDIT:
<?php require ("database_connect.php");?>
<!DOCTYPE html>
<html>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"])?>">
Name : <input type="text" name="name"><br/>
Password : <input type = "text" name="password"><br/>
<input type="submit" name="login" value="Log In">
</form>
<?php
$name = null ;
$password= null ;
if($_SERVER["REQUEST_METHOD"]=="POST" and isset($_POST["login"])){
$name = mysqli_real_escape_string($conn, $_POST["name"]); //I updated that because your variables are not safe
$password = mysqli_real_escape_string($conn, $_POST["password"]);
}//if ends here
//testInput function
function testInput($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
}//testInput ends here
if(isset($_POST["login"]) && isset($_POST["name"]) && isset($_POST["password"]) && !empty($_POST["name"]) && !empty($_POST["password"])){
if($result = mysqli_query($conn,"SELECT * FROM users WHERE name='{$name}' and password='{$password}'")){
print "rows are ".mysqli_num_rows($result)"<br>";//number of rows
if($result && mysqli_affected_rows($conn) >= 1){//If query was successfull and it has 1 or more than 1 result
echo "you are logged in<br>";
while ($row = mysqli_fetch_assoc($result)){
echo "Name ".$row["name"]."-Password ".$row["password"];
}//while loop ends here
}//if ends here
/* free result set */
mysqli_free_result($result);
}
else{
print "Wrong Credentials "."<br>";
die(mysqli_error($conn));
}
}
//close connection
mysqli_close($conn);
?>
</body>
</html>
try to change this query
$result = mysqli_query($conn,"SELECT * FROM users WHERE name='$name' and password='$password'")
to
$result = mysqli_query($conn,"SELECT * FROM users WHERE name='$name' and password='$password' limit 1")
then you will get only one row , and try to change
$row = $result->fetch_assoc()
to
$row = $result->mysqli_fetch_row()
then you can display the results by colomn number instead of colomn name
<?php
mysql_connect("abc.com","user","password");
mysql_select_db("database name");
$query1="select * from table_name";
$exe1= mysql_query($query1);
$row= mysql_fetch_assoc($exe1);
if($row["email"]==$_POST["email"] && $row["[password"]==$_POST["password"]) {
echo "Login successfully";
} else {
echo "error in login";
}
?>
enter your column name in row["email"] and $row["password"]

Execute query update with form from a query

I am trying to create a button on my user list page to delete that row, or make that user an admin.
Here is the info for the user query and html:
<?php
$query = "SELECT * FROM users";
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch(PDOException $ex)
{
die("An Error has occured. Please contact the server administrator for assistance.");
}
$rows = $stmt->fetchAll();
?>
<?php foreach($rows as $row) : ?>
<?php
if($row['usertype'] == 2) {
$usertype = "<span style='color:#F7FE2E;'>Donator</span>";
} elseif($row['usertype'] == 3) {
$usertype = "<span style='color:red;'>Admin</span>";
} elseif($row['usertype'] == 4) {
$usertype = "<span style='color:orange;'>Owner</span>";
} else {
$usertype = "<span style='color:#585858;'>Normal</span>";
}
?>
<tr>
<!--<td><?php echo $row['id']; ?></td>-->
<td><?php echo htmlentities($row['username'], ENT_QUOTES, 'UTF-8');?></td>
<!--<td><?php echo htmlentities($row['email'], ENT_QUOTES, 'UTF-8');?></td>-->
<td><?php echo htmlentities($row['steamid'], ENT_QUOTES, 'UTF-8');?></td>
<td><?php echo $usertype?></td>
<td><form action="" method="post">
<input type="submit" name="admin" value="Promote" />
</form></td>
</tr>
<?php endforeach; ?>
And the code where I prepare and execute my update query:
if(!empty($_POST['admin']))
{
$query = "UPDATE `users` SET `usertype` = '3' WHERE `id` = " . $row['id'];
// $query_params = array(':id' => $row['id']);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch(PDOException $ex)
{
die("An Error has occured. Please contact the server administrator for assistance.");
}
}
Unfortunately I when I run this current setup, it updates the very last row. To further ask what I am looking for, is I have a list of users:
where "admin_b" is a button that forced $_POST['admin']
Billy admin_b
Bob admin_b
Jill admin_b
Jack admin_b
UPDATE:
So in my form I have an input with <input type="hidden" name="id" value="<?php $row['id']; ?>" /> and added this to my SQL $query = "UPDATE users SET usertype = '3' WHERE id = :id"; $query_params = array(':id' => $_POST['id']);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch(PDOException $ex)
{
die("An Error has occured. Please contact the server administrator for assistance.");
}
send an id with $_POST request, now you are always update user with id = $row['id']
WHERE `id` = " . $row['id'];
row[id]edit?=edit.php= ...
and let's say you have list all the members and beside them is an href, the code above will execute, it will display let's say Billy?edit.php=1, wherein 1 is his primary key, then for the next, when you scroll the cursor to the next href of the next user, Jim, it will display, Jim?edit.php=2, in your edit.php,
if(isset($_POST['edit])){
code goes here to make the user an admin..
You can also make an href for the delete, similar to this edit..
This is just an idea/hint that I can give to you, but your problem can be solved in many different ways, it just depends on your approach on how you could do it :D goodluck.

PHP : Data which is of one digit is not deleted, but two digit data gets deleted

I have 2 PHP pages to delete employee data from table. For that, user inserts employee id, and press delete, to delete data from table.
Now, problem is, whenever I inserts id of one digit(2,3,8 etc), id is not deleted. However, if two digit id is inserted (12,19,99 etc), it gets deleted.
Please help me to solve where I am wrong.
Here is my code for first PHP page:
<form action="deleteemp.php" method="post" onSubmit="return confirm('Are you sure to delete?')">
Enter id to delete data<input type="text" name="EmpId" required>
<button type="submit" >Delete</button>
</form>
Here is my action PHP page,
<?php
$EmpId = $_POST['EmpId'];
$connection = mysql_connect("localhost", "root", "");
if (!$connection) {
die("Connection failed " . mysql_error());
}
$db_conn = mysql_select_db("hms", $connection);
if (!$db_conn) {
die("Connection failed " . mysql_error());
}
$query = "DELETE FROM employee_details WHERE emp_id = " . $EmpId;
$db_result = mysql_query($query, $connection);
if ($db_result) {
echo "Data Deleted Successfully !";
echo "<br>";
echo "<a href='homepage.php'>Back to homepage</a>";
} else {
echo "Data Not there. Try Again !<br>";
echo "<a href='deleteemp1.php'>Search again</a>";
}
echo "data not here" is incorrect. mysql_query returns boolean false on FAILURE. An empty result (no matching IDs) is NOT a failure. It's a successful query which happens to have an empty result set.
Your code should be more like
$result = mysql_query($query) or die(mysql_error());
if (mysql_affected_rows($result) == 0) {
die("No rows deleted");
}
And note that you are vulnerable to sql injection attacks, and using an obsolete/deprecated DB library.
Try this
$query = "DELETE FROM employee_details WHERE emp_id = '$EmpId'";
$db_result = mysql_query($query, $connection);
if ($db_result)
{
echo "Data Deleted Successfully !";
echo "<br>";
echo "<a href='homepage.php'>Back to homepage</a>";
}
else
{
echo "Data Not there. Try Again !<br>";
echo "<a href='deleteemp1.php'>Search again</a>";
}
This seems some exceptional issue, so try typecasting before passing value to SQL query.
Try using this for assigning value to $EmpId:
$EmpId = (int) $_POST['EmpId'];
can you try to change below code from
$query = "DELETE FROM employee_details WHERE emp_id = " . $EmpId;
TO
$query = "DELETE FROM employee_details WHERE emp_id =".$EmpId;
Just try. This might work for you

Trying to create a simple cumulative addition script in PHP (or JS):

Trying to create a simple cumulative addition script in PHP (or JS):
1) enter any integer(4 digits or less), click submit, number entered is displayed and saved on the same web page
2) enter another number, click submit, number entered is added to previous number and total is saved and displayed on the web page
Repeat …….
Example: the mantra counter at garchen.net
Below is the code I have so far
In Index.php:
<form method="post" action= "process-mantra-form-ami.php" >
<p><strong>Amitabha Million Mantra Accumulation: </strong><br></p>
<div style="margin-left: 20px;">
<p>OM AMI DEWA HRI</p>
<input type="text" name="accumulation" size="10" maxlength="6">
<input type="submit" value="Submit Your Mantra" name="B1"><br>
<span id="mani">Amitabha Mantra Count: <?php echo $newValue; ?> </span>
<p></p>
</div>
</form>
I am getting confused about the form processing php. Im attempting to use my local mamp server for the db. Do I create a connection, create a database, and a table, insert form data into table, and retrieve data back to index.php all at the same time in the process-mantra-form-ami.php file?
You guys made it seem easy in my last post, but there seems to be a lot to it. I know my code below is incomplete and not quite correct. Help!
PROCESS-MANTRA-FORM-AMI.PHP code below
<?php
// Create connection
$con=mysqli_connect("localhost:8888","root","root","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$accumulation = mysqli_real_escape_string($con, $_POST['accumulation']);
// Create database
$sql="CREATE DATABASE my_db";
if (mysqli_query($con,$sql)) {
echo "Database my_db created successfully";
} else {
echo "Error creating database: " . mysqli_error($con);
}
// Create table "Mantras" with one column 'Num'
$sql="CREATE TABLE Mantras (Num INT)";
if (mysqli_query($con,$sql)) {
echo "Table mantras created successfully";
} else {
echo "Error creating table: " . mysqli_error($con);
}
// Insert form data into table
$sql="INSERT INTO Mantras (Num INT)
VALUES ('$num')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
// update database
mysqli_query($con,"UPDATE Mantra SET Num = num + 1");
}
mysqli_close($con);
?>
<div>
<h2>Thank you for your <?php echo $num; ?> Amitabha Mantras!</h2>
<p>Remember to dedicate your merit.</p>
<p>Return to the main site</p>
</div>
try this out... (sorry, bored tonight)
http://php.net/manual/en/book.mysqli.php
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
$conn->query($sql)
$conn->prepare($sql)
$conn->error
http://php.net/manual/en/class.mysqli-stmt.php
$stmt->bind_param('ss',$val1,$val2)
$stmt->bind_result($res1,$res2)
http://php.net/manual/en/mysqli.construct.php
<?php
$host = 'localhost'; // localhost:8888
$user = 'root';
$pass = ''; // root
$dbnm = 'test';
$conn = mysqli_connect($host,$user,$pass,$dbnm)
or die('Error ' . $conn->connect_error);
// for testing.... so i can run the code over and over again and not
// get errors about things existing and stuff
run_statement($conn,"drop database if exists `my_db`;",'cleared old db');
run_statement($conn,"drop table if exists `mantras`;",'cleared old table');
run_statement($conn,"drop table if exists `two_col_table`;",'cleared old table');
// Create database
$sql = 'create database my_db';
$err = run_statement($conn,$sql,'Database creation');
if (!$err) $conn->select_db('my_db');
// Create table "Mantras" with one column 'Num'
$sql = 'create table mantras (num int)';
$err = run_statement($conn,$sql,'Table mantras');
if (!$err) {
$sql = 'insert into mantras (num) values ( ? )';
$stmt = $conn->prepare($sql);
$stmt->bind_param('d',$num); // d is for digit but s (string) would work too
$num = 1;
$stmt->execute();
$num = 2;
$stmt->execute();
$stmt->close();
echo ($conn->error) ? "insert errored: {$conn->error}" : 'insert ran succesfully';
// update database
$sql = 'update mantras set num = num + 1';
run_statement($conn,$sql,'Update database');
}
// Create table "test" with two columns
$sql = 'create table two_col_tbl (num int, txt varchar(10))';
$err = run_statement($conn,$sql,'Table two_col_tbl');
if (!$err) {
// demonstrating how to bind multiple values
$sql = 'insert into two_col_tbl values ( ?, ? )';
$stmt = $conn->prepare($sql);
$stmt->bind_param('ds',$num,$txt);
$num = 1; $txt = 'hello';
$stmt->execute();
$num = 2; $txt = 'world';
$stmt->execute();
$stmt->close();
// select statement
$sql = 'select num, txt from two_col_tbl';
$stmt = $conn->prepare($sql);
$stmt->bind_result($db_num, $db_txt);
$stmt->execute();
print '<table><tr><th colspan=2>two_col_tbl</tr><tr><th>num</th><th>txt</th></tr>';
while ($stmt->fetch()) {
print "<tr><td>$db_num</td><td>$db_txt</td></tr>";
}
print '<table>';
$stmt->close();
}
$conn->close();
function run_statement($conn,$statement,$descr) {
if ($conn->query($statement))
echo "$descr ran successfully";
else echo "$descr failed: {$conn->error}";
return $conn->error;
}
?>
<div>
<h2>Thank you for your <?php echo $num; ?> Amitabha Mantras!</h2>
<p>Remember to dedicate your merit.</p>
<p>Return to the main site</p>
</div>

Categories