Cannot update database - php

<?php
session_start();
if (isset($_POST['userid']) && isset($_POST['password']))
{
// if the user has just tried to log in
$userid = $_POST['userid'];
$password = $_POST['password'];
$db_conn = new mysqli('localhost', 'user', 'passwd', 'dbname');
if (mysqli_connect_errno()) {
echo 'Connection to database failed:'.mysqli_connect_error();
exit();
}
$query = 'select * from users '
."where userid like'$userid' "
." and password like sha1('$password')";
$result = $db_conn->query($query);
if ($result->num_rows >0 )
{
// if they are in the database register the user id
$_SESSION['valid_user'] = $userid;
}
$db_conn->close();
}
?>
<?
$db_conn = new mysqli('localhost', 'user', 'passwd', 'dbname');
if (mysqli_connect_errno()) {
echo 'Connection to database failed:'.mysqli_connect_error();
exit();
}
if (isset($_POST['submit'])) {
if (empty($_POST['name']) || empty ($_POST['dob']) || empty ($_POST['contact'])|| empty ($_POST['address'])|| empty ($_POST['email'])) {
echo "All records to be filled in";
exit;}
}
$name = $_POST['name'];
$dob = $_POST['dob'];
$contact = $_POST['contact'];
$address = $_POST['address'];
$email = $_POST['email'];
$userid = $_SESSION['valid_user'];
$sql = "UPDATE users SET name=$name, dob=$dob, contact=$contact, address=$address, email=$email
WHERE userid ='$userid'";
$result = $db_conn->query($sql);
if (!$result)
echo "Your query failed.";
else
echo "User Information Updated ";
?>
<meta http-equiv="refresh" content="5;URL=members.php" />
I got your query failed when I run it. Anyone have any clue why my database dont get updated?
I'm pretty sure my sql works. Is there any mistake in my coding?

Your query is okay, except that you're not using prepared statements.
The issue lies in your variables. echo them and see what's in them.
Since we don't have access to your database it's hard for us to verify if something else might be wrong with your query. You could for example create an SQL Fiddle.
Something else you should read up on: SQL Injection
Prepared statements look like this:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$city = "Amersfoort";
/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $city);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($district);
/* fetch value */
$stmt->fetch();
printf("%s is in district %s\n", $city, $district);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>

Looks like your exist statement is wrong..
if (isset($_POST['submit']))
{
if (empty($_POST['name']) || empty ($_POST['dob']) || empty ($_POST['contact'])|| empty ($_POST['address'])|| empty ($_POST['email']))
{
echo "All records to be filled in";
**exit**;
}
}

Related

I can't run my PHP program and I received several errors

This is the image of the warning I got
I am new and I really want to learn PHP.
<?php
include 'mysql.conf.php';
if(isset($_POST['submit']))
{
if(!empty($_POST['user']) && !empty($_POST['password']))
{
$user = $_POST['user'];
$password = $_POST['password'];
$select = "SELECT * FROM admin where user=$user && password=$password";
$sql=mysql_query($select) or die(mysql_error());
if($sql)
{
echo "Login";
}
else
{
echo "Cannot Login";
}
}
}
?>
Below is my code for the mysql.conf.php
<?php
$name = "localhost";
$user = "root";
$pass = "gasamul";
$connect = mysql_connect($name, $user, $pass) or die(mysql_error());
$db = "portfolio";
if($connect)
{
$db = mysql_select_db($db) or die(mysql_error());
if($db)
{
//echo 'Database Connect';
}
}
else
{
echo 'Database can\'t connect';
}
?>
The name of my database is portfolio. I also named my table admin.
Since the error is stating clear that mysql_* extension is already deprecated and it is suggesting that you use mysqli_* or PDO extension.
Lets try the first option - mysqli_*. We establish first the connection to your database in mysql.conf.php:
$connect = new mysqli("localhost", "root", "gasamul", "portfolio");
/* CHECK CONNECTION */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
Then, we can proceed with logintest.php:
include 'mysql.conf.php';
if(isset($_POST['submit']) && !empty($_POST['user']) && !empty($_POST['password']))
{
if($stmt = $con->prepare("SELECT * FROM admin WHERE user = ? AND password = ?")){ /* PREPARE YOUR QUERY */
$stmt->bind_param("ss", $_POST['user'], $_POST['password']); /* BIND THESE TWO VARIABLES TO THE QUERY ABOVE RESPECTIVELY; s STANDS FOR strings */
$stmt->execute(); /* EXECUTE THE QUERY */
$stmt->store_result(); /* STORE THE RESULT */
$noofrows = $stmt->num_rows; /* GET THE NUMBER OF RESULT */
if($noofrows > 0){ /* CHECK IF RESULT IS MORE THAN 0 */
echo "Login";
} else {
echo "Cannot Login";
}
$stmt->close(); /* CLOSE THE PREPARED STATEMENT */
}
}
You can also check out password_hash() for securing your password in your database.

Selecting multiple data from a database through PHP

I have a search form that is able to retrieve the username of a user, however I can't figure out how to get it to return more than that, I want it to display the first names and last names too.
Below is the code at the minute that works, but when I try and add in more variables, for example if ($stmt = $connection->prepare ("SELECT Username FROM users WHERE Username LIKE ?")) then it doesn't return anything at all and asks to insert a search query.
I have also tried if ($stmt = $connection->prepare ("SELECT Username FROM users WHERE Username LIKE %?%")) and LIKE "%?%")), but no results.
search.php
<?php
include 'connection.php';
if(isset($_POST['searchsubmit']))
{
include 'searchform.php';
$name=$_POST['name'];
if ($stmt = $connection->prepare ("SELECT Username FROM users WHERE Username LIKE ?"))
{
$stmt->bind_param('s', $name);
$stmt->execute();
$stmt->bind_result($personresult);
$stmt->fetch();
?>
<center>
<BR>
<h1>Search Results are as follows:</h1>
<h2>USERNAMES</h2>
<BR>
<?php
print_r($personresult);
?>
</center>
<?php
}
else
{
echo "<p>Please enter a search query</p>";
}
}
else
{
echo "NOT SET!";
}
You are only calling Username .. You need to be calling *
SELECT * FROM users WHERE Username LIKE ?
This is my personal script I use:
<?php
$dbservername = "localhost";
$dbusername = "db_user";
$dbpassword = "pass";
$dbname = "db";
// Create connection
$conn = new mysqli($dbservername, $dbusername, $dbpassword, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (!empty($_POST["username"])) {
$username = $_POST["username"];
}
if (!empty($_POST["password"])) {
$password = $_POST["password"];
}
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo $row["Username"] . " " . $row["Firstname"] . " " . $row["Lastname"] . "<br>";
if ($row["Username"] == $username && $row["Password"] == $password) {
echo "success";
// do more stuff here like set session etc
} else {
$echo "incorrect username and/or password";
}
}
}
?>
Are you initializing the statement object with mysqli_stmt_init?
See mysqli_stmt_init and mysqli-stmt.prepare
If the database server cannot successfully prepare the statement,
PDO::prepare() returns FALSE or emits PDOException (depending on error
handling)
add this line in connection.php right after creating connection object:
$connection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
At least, you can trace possible errors
<?php
include 'connection.php';
if( isset( $_POST['searchsubmit'] ) ) {
include 'searchform.php';
$name=$_POST['name'];
if ( $stmt = $connection->prepare ("SELECT `Username`,`firstname`,`lastname` FROM `users` WHERE `Username` LIKE ?") ) {
/* not 100% sure about whether this is required here like this or not but usually a like expression uses '%' as a wildcard */
$var='%'.$name'.%';
$stmt->bind_param('s', $var );
$res=$stmt->execute();
/* 3 columns selected in query, 3 columns bound in results */
$stmt->bind_result( $personresult, $firstname, $lastname );
if( $res ){
$stmt->fetch();
echo "
<center>
<BR>
<h1>Search Results are as follows:</h1>
<h2>USERNAMES</h2><!-- 3 columns/variables -->
{$personresult},{$firstname},{$lastname}
<BR>
</center>";
}
} else {
echo "<p>Please enter a search query</p>";
}
} else {
echo "NOT SET!";
}
$stmt->close();
$connection->close();
?>

PHP to mySQL check if user exists

I have a script that updates/creates user from an iOS device. Now i want to have the script also check if the user already exists in the database. I am going to restrict this to username for now, so no more than ONE unique username may exist. I have an if-statement in my PHP but i cannot get it to work - help please :).
<?php
header('Content-type: application/json');
if($_POST) {
$username = $_POST['username'];
$password = $_POST['password'];
if($username && $password) {
$db_name = 'dbname';
$db_user = 'dbuser';
$db_password = 'dbpass';
$server_url = 'localhost';
$mysqli = new mysqli('localhost', $db_user, $db_password, $db_name);
$userexists = mysql_query("SELECT * FROM users WHERE username='$username'");
/* check connection */
if (mysqli_connect_errno()) {
error_log("Connect failed: " . mysqli_connect_error());
echo '{"success":0,"error_message":"' . mysqli_connect_error() . '"}';
}
if(mysql_num_rows($userexists) != 0) {
echo '{"success":0,"error_message":"Username Exist."}';
}
else {
$stmt = $mysqli->prepare("INSERT INTO users (username, password, email) VALUES (?, ?, ?)");
$password = md5($password);
$stmt->bind_param('sss', $username, $password, $email);
/* execute prepared statement */
$stmt->execute();
if ($stmt->error) {error_log("Error: " . $stmt->error); }
$success = $stmt->affected_rows;
/* close statement and connection */
$stmt->close();
/* close connection */
$mysqli->close();
error_log("Success: $success");
if ($success > 0) {
error_log("User '$username' created.");
echo '{"success":1}';
}
else {
echo '{"success":0,"error_message":"Username Exist."}';
}
}
}
else {
echo '{"success":0,"error_message":"Passwords does not match."}';
}
}
else {
echo '{"success":0,"error_message":"Invalid Username."}';
}
}
else {
echo '{"success":0,"error_message":"Invalid Data."}';
}
?>
You could SELECTthe table before trying to insert username. If it already exists (= you have a result) you dont simply insert.
Better yet, use ON DUPLICATE IGNORE or something like that.

php login form not working correctly

I'm trying to create a simple login functionality but it's not working, and I'm relatively new to mysqli so please bear with me. I just want to check if the email address and password are correct and if they are then log the user in. Thanks in advance.
Here is my login code that checks the credentials:
UPDATED CODE - I added the report all and I'm now getting internal server error
<?php
require_once 'connect.php';
mysqli_report(MYSQLI_REPORT_ALL);
session_start();
if (!isset($_SESSION['email'])) {
$e = trim($_REQUEST['email']);
$email = $mysqli->real_escape_string($e);
$p = trim($_REQUEST['password']);
$password = $mysqli->real_escape_string($p);
/*
if ($result = $mysqli->query("SELECT email, password, user_id" .
" FROM users" .
" WHERE email = '$email' AND password = '$password'")) {
printf("Select returned %d rows.\n", $result->num_rows);
echo 'Total results: ' . $result->num_rows;
}
*/
if ($stmt = $mysqli->prepare("SELECT email, password, user_id FROM users WHERE email=? AND password=?")) {
/* bind parameters for markers */
$stmt->bind_param("ss", $email, $password);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($email, $password);
/* fetch value */
$stmt->fetch();
if ($stmt->num_rows==1) {
$row = $stmt->fetch_assoc(MYSQLI_NUM);
$user_id = $row['user_id'];
$_SESSION['user_id'] = $user_id;
$_SESSION['email'] = $email;
header("Location: home.php");
/* close statement */
$stmt->close();
} else {
printf("Error message: %s\n", $mysqli->error);
}
/*
if ($result->num_rows==1) {
$row = $result->fetch_assoc(MYSQLI_NUM);
$user_id = $row['user_id'];
if ($query_group = $mysqli->query("SELECT *" .
" FROM user_groups" .
" WHERE user_id = '".$user_id."'")) {
//No more setcookie
$_SESSION['user_id'] = $user_id;
$_SESSION['email'] = $email;
} else {
echo 'Did not work';
}
}
*/
/* free result set */
// $result->close();
}
}
?>
And here is connect.php to connect to the database:
<?php
$mysqli = new mysqli("data", "username", "password", "db");
if($mysqli->connect_errno > 0){
die('Unable to connect to database [' . $mysqli->connect_error . ']');
}
?>
did you try to remove one of the brackets in the end of ypur code. I guess you have to remove one of them.

Username check comes back as username already exist when it doesnt

I have a code that checks if a username exists or not, but when I run the code and enter in a username i inserted into my database using phpmyadmin it says the username dosent exist, am wondering where i went wrong?
here is my php code:
<?php
require_once 'connect.php';
$conn = dbConnect();
if (isset($_POST['username']))
{
$sql = $conn->prepare("SELECT COUNT(id)
FROM users
WHERE username = :username");
$sql->execute(array(":username" => $_POST['username']));
$rows_number = $sql->fetchColumn();
if($rows_number ==0)
{
echo "Username doesn't exist";
exit;
}
else
{
echo "Username already exists";
exit;
}
}
?>
here is my php connect.php:
<?php
function dbConnect(){
$db = null;
$db_host = "localhost";
$db_username ="user";
$db_pass ="pass";
$db_name = "accounts";
try{
$db = new PDO('mysql:host='.$db_host.';dbname'.$db_name,$db_username,$db_pass);
}
catch (PDOException $e) {
echo '<p>Cannot connect to database !!</p>';
exit;
}
return $db;
}
?>
Seeing as I do not have 50+ rep I can't comment but post your connect.php code and exclude the username and password so I can see if its the connect.php that's giving the problem
Edit: your problem lye's here:
';dbname'.$db_name,$db_username,$db_pass);
it should be
';dbname='
and then append on your variable $db_name. Further explanation is the ';dbname is equal to the value you gave your variable.
You may not have initialized the query statement
/* create a prepared statement */
<?php
$stmt = $mysqli->stmt_init();
if ($stmt->prepare("SELECT District FROM City WHERE Name=?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $city);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($district);
/* fetch value */
$stmt->fetch();
printf("%s is in district %s\n", $city, $district);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>

Categories