Inserting user updates into SQL with PHP - php

I think I am really close now - there are no more nasty Orange boxes with errors in - the only problem I can see at the moment is that once I update the table (after the
$qry = "UPDATE 'members' ('employer', 'flat') WHERE login='$login_name' VALUES ". " ('$employ', $address')";
) I get the message "No rows updated" echo to the screen!
Any ideas what the problem is?
Thanks.
<?php
//Start session
session_start();
$_SESSION['SESS_LOGIN'];
//Include database connection details
require_once('config.php');
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$errflag = false;
//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
//Sanitize the POST values
$employ = clean($_POST['employer']);
$address = clean($_POST['flat']);
?>
<?Php
//Insert employer and address into database row for logged in user.
$login_name = $_POST['login_name'] ;
$qry = "UPDATE 'members' ('employer', 'flat') WHERE login='$login_name' VALUES ". " ('$employ', $address')" ;
$result = #mysql_query($link, $qry);
//Check whether the query was successful or not
if(!$result) {
echo "No rows updated";
exit();
}else {
echo "Success";
}
?>

Don't use VALUES, use SET:
"UPDATE `members` SET `employer` = '".$employ."', `flat` = '".$address."' WHERE `login`='".$login_name."'"

First of all you should not suppress error messages by using the # opperator if you are looking for issues in your code. Also you are using the wrong parentheses (' instead of `). The rest of your code looks fine. maybe you need to give us some info about the database structure otherwise

Related

SQL insert to MySQL doesn't work

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.

Query Fails whenever I want to insert

Each time i submit a form through the code below, i get "Query failed" but i can't seems to find the error.
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'order (pass, phone, fname, lname)
VALUES('test#yahoo.com','060606060606','James'' at line 1
Please someone help me.
<?php
//Start session
session_start();
//Include database connection details
require_once('../db/config.php');
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$errflag = false;
//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
//Sanitize the POST values
$pass = clean($_POST['pass']);
$phone = clean($_POST['phone']);
$fname = clean($_POST['fname']);
$lname = clean($_POST['lname']);
//Create INSERT query
$qry = "INSERT INTO order (pass, phone, fname, lname) VALUES('$pass','$phone','$fname','$lname')";
$result = #mysql_query($qry);
//Check whether the query was successful or not
if($result) {
header("location: success.php");
exit();
}else {
die("Query failed");
}
?>
I also tried to check if the user inputs are empty and it was okay but it doesn't insert.
The name 'order' is a MySQL reserved keyword.
Use backtick to enclose table name,
$qry = "INSERT INTO `order` (pass, phone, fname, lname) VALUES('$pass','$phone','$fname','$lname')";
^ enlcose table name with backtick
Backtick
And use "mysqli"
$qry = "INSERT INTO `order` (pass, phone, fname, lname) VALUES('$pass','$phone','$fname','$lname')";
$result = mysqli_query($conn,$qry);

PHP MySQL login setup error

This is all really new to me and I only know the very basics. I'm creating a frontend login for a webpage (obviously security isn't a huge deal or I wouldn't be doing it). I keep getting in issue with my "where" clause, stating that the "user" does not exist. Database is setup like this:
dbname=connectivity
table=users
users has id, user, and pass.
Anyone want to give me some pointers? Thanks in advance.
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'connectivity');
define('DB_USER','root');
define('DB_PASSWORD','');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Ya done goofed: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Ya done goofed: " . mysql_error());
function SignIn()
{
session_start();
if(!empty($_POST['user']))
{
$query = mysql_query("SELECT * FROM users where user = `$_POST[user]` AND pass = '$_POST[pass]'") or die(mysql_error());
$row = mysql_fetch_array($query) or die(mysql_error());
if(!empty($row['user']) AND !empty($row['pass']))
{
$_SESSION['user'] = $row['pass'];
echo "SUCCESSFULLY LOGIN TO USER PROFILE PAGE...";
}
else
{
echo "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY...";
}
}
}
if(isset($_POST['submit']))
{
SignIn();
}
?>
Please stop using mysql_*. use mysqli_* or PDO. Have a look to the code:-
<?php
// Force PHP to show errors
error_reporting(E_ALL); // Get all type of errors if any occur in code
ini_set('display_errors',1); // Display those errors
session_start(); // start session
define('DB_HOST', 'localhost');
define('DB_NAME', 'connectivity');
define('DB_USER','root');
define('DB_PASSWORD','');
$con = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME) or die("connection not established"); Or use $con = mysqli_connect('localhost','root','','connectivity') or die("connection not established");
if(isset($_POST['submit'])){
SignIn();
}
function SignIn(){
if(!empty($_POST['user'])) {
$username = mysqli_real_escape_string($con , $_POST['user']); // prevent form SQL injection
$password = mysqli_real_escape_string($con , $_POST['pass']); // prevent form SQL injection
$query = mysqli_query($con,"SELECT * FROM users where user = '".$username."' AND pass = '".$password."'") or die(mysqli_error($con));
if(mysqli_num_rows($query) > 0){ // check count of resultset
$_SESSION['user'] = $_POST['pass'];
echo "SUCCESSFULLY LOGIN TO USER PROFILE PAGE...";
}else{
echo "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY...";
}
}
}
?>
There are some issues here:
SELECT * FROM users where user = `$_POST[user]` AND pass = '$_POST[pass]'
The quote styles are all over the place. Try this:
SELECT * FROM `users` WHERE `user` = '$_POST[user]' AND `pass` = '$_POST[pass]'
Also, you should pre-process for SQL injection if you're not already.
This is the correct formatted SQL.
$query = mysql_query("SELECT * FROM `users` WHERE `user` = `'".$_POST["user"]."'` AND pass = '".$_POST["pass"]."'") or die(mysql_error());
One thing to note is that you MUST escape and validate all global variables. For more information I strongly recommend you to read this SO post: How can I prevent SQL injection in PHP?
There are multiple things wrong with your code check it down below:
<?php
session_start(); // This needs to be on top of every page
define('DB_HOST', 'localhost');
define('DB_NAME', 'connectivity');
define('DB_USER','root');
define('DB_PASSWORD','');
// Use mysqli_* as mysql_* is depracted and will be removed
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) or die("connection not established");
// Add a bit of security
$user = mysqli_real_escape_string($con, $_POST['user']);
$pass = mysqli_real_escape_string($con, $_POST['pass']);
function SignIn($user, $pass) {
// Add backticks ` around column and table names to prevent mysql reserved word error
$query = mysqli_query($con, "SELECT * FROM `users` WHERE `user` = '$user' AND `pass` = '$pass'");
// No need to fetch the data you already have
// Check if the query returns atleast 1 row (result)
if( mysqli_num_rows($query) >= 1 ) {
$_SESSION['user'] = $pass;
echo "SUCCESSFULLY LOGIN TO USER PROFILE PAGE...";
} else {
echo "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY...";
}
}
if(isset($_POST['submit']) && !empty($user) && !empty($pass) ) {
SignIn($user, $pass);
} else {
echo "SORRY... THERE ARE EMPTY FIELDS... PLEASE RETRY...";
}
?>
Just changed your code like follows:
SELECT * FROM users where user ='$_POST[user]'AND pass = '$_POST[pass]'
That line need to rewrite like follows:
SELECT * FROM users WHERE user = '".$_POST[user]."' AND pass = '".$_POST[pass]."'
I believe that should work in every server without any kind of trouble.
You are missing quotations
Corrected code:
$query = mysql_query("SELECT * FROM `users` WHERE `user` = `'".$_POST["user"]."'` AND pass = '".$_POST["pass"]."'") or die(mysql_error())

PHP message "Error: No database selected", concernig this script

I have this script, but i don't know what could be wrong here when I hit "post" button on the main page. Where the error can come from?
The page script:
<?php
session_start();
include("dbconnection.php");
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
$messages = clean($_POST['message']);
$user =clean($_POST['name']);
$pic =clean($_POST['name1']);
$poster =clean($_POST['poster']);
$sql="INSERT INTO message (messages, user, picture, date_created, poster)
VALUES
('$messages','$user','$pic','".strtotime(date("Y-m-d H:i:s"))."','$poster')";
mysql_query("UPDATE messages SET picture = '$pic' WHERE FirstName='$user'");
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
header("location: lol.php");
exit();
$name=$_POST['name'];
$pic=$_POST['name1'];
mysql_query("UPDATE messages SET picture = '$pic' WHERE FirstName='$name'");
?>
This is the dbconnect file:
$con = mysql_connect("hostname","username","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("asl", $con);
?>
Ensure you have selected your db using mysql_select_db
mysql_connect('hostname','username','password') or die("not able to connect");
mysql_select_db('myDatabase');
And mysql_ extensions are deprecated.. Dont use it
this errors seems to be caused by either selecting wrong database or not selecting it.
check dbconnection.php and for this line in it
mysql_select_db("your_database_name",$your_connection);
See whether this line is present and pointing to database or not and make sure this databse exists
Update It seems that your file is not being included try require() so that it produces fatal error and you can see file s being including or not
require("dbconnection.php"); // will produce fatal errors
First of all mysql_connect is outdated and unsecure, better use PDO instead
<?php
session_start();
include("dbconnection.php");
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
$messages = clean($_POST['message']);
$user =clean($_POST['name']);
$pic =clean($_POST['name1']);
$poster =clean($_POST['poster']);
$sql = $db->prepare("INSERT INTO message (messages, user, picture, date_created, poster) VALUES (:messages, :user, :picture, :date_created, :poster)");
$sql->bindParam(':messages', $messages);
$sql->bindParam(':user', $user);
$sql->bindParam(':picture', $pic);
$sql->bindParam(':date_created', strtotime(date("Y-m-d H:i:s")));
$sql->bindParam(':poster', $poster);
$stmt = $db->prepare("UPDATE messages SET picture = :picture WHERE FirstName = :user");
$stmt->bindParam(':picture', $pic);
$stmt->bindParam(':user', $user);
$stmt->execute();
if (!$sql->execute())
{
die('Error: ' . mysql_error());
}
$name=$_POST['name'];
$pic=$_POST['name1'];
$stmt_2 = $db->prepare("UPDATE messages SET picture = :picture WHERE FirstName = :name");
$stmt_2->bindParam(':picture', $pic);
$stmt_2->bindParam(':name', $name);
$stmt_2->execute();
header("location: lol.php");
?>
This is the dbconnect file:
<?php
//Connect to sql db
try {
$user_db = "username";
$pass_db = "password";
$db = new PDO('mysql:host=localhost;dbname=asl', $user_db, $pass_db);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>

How to save checkbox value to MySQL database?

I have following html:
<label for="live">Live</label>
<input type="checkbox" name="live" id="live" />
How to save text value of selected = '1'/ or text value of unchecked = '0' to database using SQL INSERT?
Any suggestion much appreciated.
PHP handling the html form (at the moment 'live' is an input):
<?php
//Start session
session_start();
//Include database connection details
require_once('../inc/config.php');
//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
if($link) {
echo "DB SUCESS <br />";
}
//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
if($db){ echo "TABLE SUCCESS<br />"; }
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
//Sanitize the POST values
$live = clean($_POST['live']);
$content = clean($_POST['content']);
//Create INSERT query
$qry = "INSERT INTO news(live, content) VALUES('$live','$content') ";
$result = #mysql_query($qry);
//Check whether the query was successful or not
if($result) {
//header("location: ../form/register-success.php");
echo "Succes";
exit();
}else {
die("Query failed");
}
?>
<input type="checkbox" name="live" value="1" />Live<br />
^Note the Value "1". If someone checks the box, it will be a 1, if they don't it will be NULL. (NOT 0!)
Do an isset on the next page, if it's set, you're good to go, if it's not, just set it to zero.
if (!isset($live)) $live = 0;
Only checked HTML checkboxes send values in the response. Use isset.

Categories