How to expand my PHP code to add more database fields? - php

I found a code php for updating database, but it's just for two field that's id and item. How about if I have 7 fields, that's id_admin, name, email, address, phonenumber, username, and password, and the table name is admin. This the code that I found.
<?php
error_reporting(0);
include("db_config.php");
// array for JSON response
$response = array();
if( isset($_POST['id'] ) && isset($_POST['item']) ) {
$id=$_POST['id'];
$item=$_POST['item'];
$result = mysql_query("update myorder set item='$item' where id='$id' ") or die(mysql_error());
$row_count = mysql_affected_rows();
if($row_count>0){
$response["success"] = 1;
$response["message"] = "Updated Sucessfully.";
}
else{
$response["success"] = 0;
$response["message"] = "Failed To Update.";
}
// echoing JSON response
echo json_encode($response); } ?>

Change these lines :
if( isset($_POST['id'] ) && isset($_POST['item']) ) {
$id=$_POST['id'];
$item=$_POST['item'];
$result = mysql_query("update myorder set item='$item' where id='$id' ") or die(mysql_error());
with these :
if( isset($_POST['submit'] ) ) {
$id=htmlspecialchars($_POST['id']);
$item=htmlspecialchars($_POST['item']);
$name=htmlspecialchars($_POST['name']);
$email=htmlspecialchars($_POST['email']);
//and so on...
$result = mysql_query("update myorder set item=$item, name=$name, email= $email ... where id=$id ") or die(mysql_error());

Warning mysql_query, mysql_fetch_array,mysql_connect etc.. extensions were deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0.
Instead, the MySQLi or PDO_MySQL extension should be used.
<?php
error_reporting(0);
//db connection
global $conn;
$servername = "localhost"; //host name
$username = "username"; //username
$password = "password"; //password
$mysql_database = "dbname"; //database name
//mysqli prepared statement
$conn = mysqli_connect($servername, $username, $password) or die("Connection failed: " . mysqli_connect_error());
mysqli_select_db($conn,$mysql_database) or die("Opps some thing went wrong");
// array for JSON response
$response = array();
if( isset($_POST['id'] ) && isset($_POST['item']) ) {
$id=$_POST['id'];
$item=$_POST['item'];
$stmt = $conn->prepare("update myorder set item=?,name=?,id_admin=?,email=?,address=?,phonenumber=? where id=? ");
$stmt->bind_param('ssissii',$item,$name,$id_admin,$email,$address,$phonenumber,$id);
The argument may be one of four types:
i - integer
d - double
s - string
b - BLOB
//change it by respectively
$stmt->execute();
$row_count= $stmt->affected_rows;
if($row_count>0)
{
$response["success"] = 1;
$response["message"] = "Updated Sucessfully.";
}
else{
$response["success"] = 0;
$response["message"] = "Failed To Update.";
}
// echoing JSON response
echo json_encode($response);
$stmt->close();
$conn->close();
}
?>

Always use parameterized queries when user value needs to be inserted in query.
Example:
$statement = $conn->prepare("update admin set name=?, email=?, address=?, phonenumber=?, username=?, password=? WHERE id_admin=?");
$statement->bind_param('ssssssi', $name, $email, $address, $phonenumber, $username, $password, $id_admin);
$statement->execute();

Related

PHP: How to Insert records in Oracle db using parameters?

I am trying to insert records into an Oracle database using PHP, but for some reason, the INSERT code is not working.
--DB Table
CREATE TABLE USER (
ID NUMBER(20) GENERATED ALWAYS AS IDENTITY(START WITH 1 INCREMENT BY 1),
ROLE NUMBER(10),
NAME VARCHAR2(50),
PASSWORD VARCHAR2(50),
);
The connection string works:
#PHP: New Oracle Database Connection (db.php):
<?php
$user = "test";
$password = "test123";
$host = "localhost/XE";
$connection = oci_connect($user, $password, $host)
or die(oci_error());
if(!$connection){
echo "Failed: Verify the connection string in db.php";
}else{
//echo "CONNECTED";
}
oci_close ($connection);
?>
This is the insert in PHP that does not work, Could you help me to identify the error?
#PHP+Oracle: INSERT new user (userControllerOracle.php)
<?php
#DB Connection:
include("db.php");
#DB Oracle INSERT:
if (isset($_POST['registro'])) {
$name = $_POST['name'];
$password = $_POST['password'];
$cnn = oci_connect($user, $password, $host);
$query = "INSERT INTO USER (1, name, password) VALUES (1,'$name', '$password')";
}
?>
Previously, I used MySQL and it worked, but I don't know how to achieve the same result in Oracle
#PHP: MySQL Database Connection (db.php):
<?php
$con = mysqli_connect("localhost","test","test123","test");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
function debug_to_console($data) {
$output = $data;
if (is_array($output))
$output = implode(',', $output);
echo "<script>console.log('Debug Objects: " . $output . "' );</script>";
}
?>
#PHP+MySQL: INSERT new user (userControllerMySQL.php)
<?php
#DB Connection:
include("php/db.php");
#DB MySQL INSERT:
if (isset($_POST['registro'])) {
if (strlen($_POST['name']) >= 1 && strlen($_POST['password']) >= 1) {
$name = trim($_POST['name']);
$password = trim($_POST['password']);
$query = "INSERT INTO USER(1, name, password) VALUES (1,'$name', MD5('$password')";
$result = mysqli_query($con,$query);
if ($result) {
?>
<h5 style="text-align: center; background-color:#28a745; color:white">User added!</h5>
<?php
} else {
?>
<h5 style="text-align: center; background-color:#dc3545; color:white">error!</h5>
<?php
}
} else {
?>
<h5 style="text-align: center; background-color:#ffc107; color:#343a40">add all fields!</h5>
<?php
}
}
?>
Use oci_bind_by_name() to bind parameters in the SQL, rather than substituting variables directly into the SQL string.
$name = $_POST['name'];
$password = $_POST['password'];
$cnn = oci_connect($user, $password, $host);
$query = "INSERT INTO USER (1, name, password) VALUES (1,:name, :password)";
$stmt = oci_parse($conn, $query);
oci_bind_by_name($stmt, ':name', $name);
oci_bind_by_name($stmt, ':password', $password);
oci_execute($stmt);
Fixed, I was missing:
$parse = oci_parse($connection, $sql);
oci_execute($parse);

Data is not inserting on the database Game resgistration

So im making a web game app my problem is my register.php is not inserting users in the database please need help by the way im just a beginner in PHP Thanks
Here is the Code:
<?php
require_once('mysql_conn.php');
$Username = mysql_real_escape_string($_POST['Username']);
$Password = md5(mysql_real_escape_string($_POST['Password']));
$Email = mysql_real_escape_string($_POST['Email']);
$query_check ="SELECT user_name FROM account_info WHERE user_name = '$Username'";
$retval_check = mysql_query( $query_check, $conn );
if( $Username == "" || $Password == "" || $Email == "" ){
echo"Please fill the field";
} else{
if(mysql_num_rows($retval_check)){
echo"Username Already Taken";
} else {
$query = "INSERT INTO account_info(user_name,user_passemail) VALUES ('$Username','$Password','$Email');";
$retval = mysql_query( $query, $conn );
echo "<script>";
echo "alert('Thank you for registering Enjoy the game !')";
echo "</script>";
echo "<script>";
echo 'location.href = "menu.html";';
echo "</script>";
}
}
mysql_close($conn);
?>
Change:
$query = "INSERT INTO account_info(user_name,user_passemail) VALUES ('$Username','$Password','$Email');";
To:
$query = "INSERT INTO account_info(user_name,user_pass,email) VALUES ('$Username','$Password','$Email');";
You forgot to add a comma ","
Warning mysql_query, mysql_fetch_array,mysql_connect etc.. extensions were deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0.
Instead, the MySQLi or PDO_MySQL extension should be used.
YOu miss the coma between user_pass and email in column name
$query = "INSERT INTO account_info(user_name,user_pass,email) VALUES ('$Username','$Password','$Email');";
try mysqli
//db connection
global $conn;
$servername = "localhost"; //host name
$username = "username"; //username
$password = "password"; //password
$mysql_database = "dbname"; //database name
//mysqli prepared statement
$conn = mysqli_connect($servername, $username, $password) or die("Connection failed: " . mysqli_connect_error());
mysqli_select_db($conn,$mysql_database) or die("Opps some thing went wrong");
//require_once('mysql_conn.php');
$Username = mysqli_real_escape_string($_POST['Username']);
$Password = md5(mysqli_real_escape_string($_POST['Password']));
$Email = mysqli_real_escape_string($_POST['Email']);
//$query_check ="SELECT user_name FROM account_info WHERE user_name = '$Username'";
// $retval_check = mysqli_query( $query_check, $conn );
if(!empty($Username))
{
$stmt = $conn->prepare("SELECT user_name FROM account_info WHERE user_name =? ");
$stmt->bind_param('s',$Username);
The argument may be one of four types:
i - integer
d - double
s - string
b - BLOB
//change it by respectively
$stmt->execute();
$get_result =$stmt->get_result();
$row_count= $get_result->num_rows;
//$row_count= $stmt->affected_rows;
$stmt->close();
//$conn->close();
}
if( $Username == "" || $Password == "" || $Email == "" ){
echo"Please fill the field";
} else{
if($row_count>0){
echo"Username Already Taken";
} else {
//$query = "INSERT INTO account_info(user_name,user_pass,email) VALUES ('$Username','$Password','$Email');";
^^^^^
//$retval = mysql_query( $query, $conn );
$stmt1 = $conn->prepare("INSERT INTO account_info(user_name,user_pass,email) VALUES (?,?,?)");
$stmt->bind_param('sss',$Username,$Password,$Email);
The argument may be one of four types:
i - integer
d - double
s - string
b - BLOB
//change it by respectively
$stmt1->execute();
//$get_result1 =$stmt1->get_result();
//$row_count1= $get_result1->num_rows;
$row_count1= $stmt1->affected_rows;
$stmt1->close();
$conn->close();
if($row_count1>0)
{
echo "<script>";
echo "alert('Thank you for registering Enjoy the game !')";
echo "</script>";
}
else
{
echo "<script>";
echo "alert('registeration failed')";
echo "</script>";
}
echo "<script>";
echo 'location.href = "menu.html";';
echo "</script>";
}
}
wrong
$query = "INSERT INTO account_info(user_name,user_passemail) VALUES ('$Username','$Password','$Email');";
correct
$query = "INSERT INTO account_info(user_name,user_pass,email) VALUES ('$Username','$Password','$Email')";

Having trouble creating a safe way for users to update their data

I am making a way for users to edit their data. My first way I did it worked, but then I remembered that it is very insecure and that I should never insert data directly into the database; at least that's what I was told. I try to make it more secure by doing the VALUES (?,?,?,?,?) thing so that the data is not directly going in, which seemed to work fine in my registration page (which I can include if you want).
To start, here is my original update data page that worked fine but it does not use the (?,?,?,?,?) method:
if(isset($_POST['submit'])) {
$userid=$_SESSION['userid'];
$skype=$_POST['skype'];
$email=$_POST['email'];
$region=$_POST['region'];
$crank=$_POST['league1'];
$drank=$_POST['league2'];
if(empty($skype) || empty($email) || empty($crank) || empty($drank) || empty($region))
{
echo "Cannot leave any field blank";
}
else
{
$host= "localhost";
$dbname = "boost";
$user = "root";
$pwd = "";
$port=3306;
try
{
$mysqli= new mysqli($host, $user, $pwd, $dbname,$port);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}
$query = "UPDATE usertable SET SkypeID = '$skype', Email = '$email', Region = '$region', CRank = '$crank', DRank = '$drank' WHERE UserID = '$userid'";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("sssss",$skype,$email,$region,$crank,$drank);
$stmt->execute();
$iLastInsertId=$mysqli->insert_id;
header('Location: http://localhost/Boost/account.php');
$stmt->close();
$mysqli->close();
} catch (mysqli_sql_exception $e) {
throw $e;
}
}
}
Here is what I tried to do to make it more secure but this doesn't seem to work. Specifically the $query = "UPDATE usertable SET usertable(SkypeID,Email,Region,CRank,DRank) VALUES (?,?,?,?,?) WHERE UserID = '$userid'"; seems to be the issue, though the syntax looks fine to me
if(isset($_POST['submit'])) {
$userid=$_SESSION['userid'];
$skype=$_POST['skype'];
$email=$_POST['email'];
$region=$_POST['region'];
$crank=$_POST['league1'];
$drank=$_POST['league2'];
if(empty($skype) || empty($email) || empty($crank) || empty($drank) || empty($region))
{
echo "Cannot leave any field blank";
}
else
{
$host= "localhost";
$dbname = "boost";
$user = "root";
$pwd = "";
$port=3306;
try
{
$mysqli= new mysqli($host, $user, $pwd, $dbname,$port);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}
$query = "UPDATE usertable SET usertable(SkypeID,Email,Region,CRank,DRank) VALUES (?,?,?,?,?) WHERE UserID = '$userid'";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("sssss",$skype,$email,$region,$crank,$drank);
$stmt->execute();
$iLastInsertId=$mysqli->insert_id;
header('Location: http://localhost/Boost/account.php');
$stmt->close();
$mysqli->close();
} catch (mysqli_sql_exception $e) {
throw $e;
}
}
}
So I am not sure what the problem is. In my experience with PHP, the syntax should be fine but I must be missing something.
It's quite simple actually, you went from
$query = "UPDATE usertable SET SkypeID = '$skype', Email = '$email', Region = '$region', CRank = '$crank', DRank = '$drank' WHERE UserID = '$userid'";
TO
$query = "UPDATE usertable SET usertable(SkypeID,Email,Region,CRank,DRank) VALUES (?,?,?,?,?) WHERE UserID = '$userid'";
It appears you confused an INSERT statement vs. an UPDATE statement when rewriting so to fix you simply use your old statement with the new style...
$query = "UPDATE usertable SET SkypeID = ?, Email = ?, Region = ?, CRank = ?, DRank = ? WHERE UserID = $userid";

Inserting data to mysql not working

<?
session_start();
if(($connection = mysql_connect("localhost", "root", "")) == false)
die ("Couldn't connect to database");
if(mysql_select_db("Social", $connection) == false)
die ("Couldn't select db");
if (isset($_POST['username']) && isset($_POST['pass']) && isset($_POST['login'])){
$sql = sprintf("SELECT * FROM users WHERE username LIKE '%s' AND password LIKE '%s'", $_POST['username'], $_POST['pass']);
$query = mysql_query($sql);
if (mysql_num_rows($query) == 0){
$error = "<br />Wrong Username or Password";}
else{
$_SESSION['user'] = $_POST['username'];
header("Location: home1.php");
}
}
if (isset($_POST['register'])){
$sql2 = sprintf("INSERT INTO Social.users (username, password) VALUES (%s, %s)", $_POST['newUser'], $_POST['newPass']);
$query2 = mysql_query($sql2);
if (!$query2){
print "Registration failed";
}
else{
print "Registration sucessfull";
}
}
?>
My program is not inserting any data into mySQL table. I know all the syntax is right, everything should work out fine. I double checked on the command that mySQL uses in order to enter data into the table. Why is this not working? My query2 should be successful, but idk why its not.
Please help.
Thanks
to prevent sql injections, try mysqli or pdo
here is mysqli prepared statements version. However if you are trying to create user management system, I wouldn't recommend you do it. There are so many scripts which provide more security, http://www.usercake.com is a good user management system.
session_start();
$db = new mysqli('localhost', 'root', 'password', 'database');
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
if (isset($_POST['username'] && $_POST['pass'] && $_POST['login']))
{
$user_name = ''; //define these here.
$pass = '';
$stmt = $db->prepare("select * from users where username = ? and password = ?");
echo $db->error;//this will echo the error.
$stmt->bind_param('ss', $user_name, $pass);
$stmt->execute();
$result = $stmt->get_result();//get rows
if($result->num_rows < 1) //check if result is less than 1
{
$error = "<br />Wrong Username or Password";}
else{
$_SESSION['user'] = $_POST['username'];
header("Location: home1.php");
}
}
if (isset($_POST['register'])){
$uname = $_POST['newUser'];
$pass = $_POST['newPass'];
if(empty($uname))
{
echo "Please enter your username.";
}
elseif(empty($pass))
{
echo "Please enter your password.";
}
else{
$stmt = $db->prepare("insert into Social.users (username, password) values (?,?)");
echo $db->error;//this will echo the error.
$stmt->bind_param('ss', $uname, $pass);
$stmt->execute();
echo "You have successfully registered.";
}
}
The variables in the INSERT must be the username and password
$sql2 = sprintf("INSERT INTO Social.users (username, password) VALUES (%s, %s)", $_POST['username'], $_POST['pass']);
Use prepared statements and parameterized queries. These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL.
You basically have two options to achieve this:
Using PDO:
$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');
$stmt->execute(array('name' => $name));
foreach ($stmt as $row) {
// do something with $row
}
Using mysqli:
$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name =
?'); $stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result(); while ($row = $result->fetch_assoc()) {
// do something with $row }
Font: How can I prevent SQL injection in PHP?

mysql_query SELECT do not give the desired result

The following code always displays
rows = 0
eventhough the table contains Ravi in the field 'to'. Does anyone know what is wrong with this code?
<?php
$response = array();
$con = mysql_connect("localhost","root","");
if(!$con) {
die('Could not connect: '.mysql_error());
}
mysql_select_db("algopm1",$con);
//if (isset($_POST['to'])) {
$to = "Ravi";
$result = mysql_query("SELECT *FROM `events` WHERE to = '$to'");
if (!empty($result)) {
if (mysql_num_rows($result)>0) {
$result = mysql_fetch_array($result);
echo $result["to"] + " " + $result["from"];
} else {
echo 'rows = 0';
}
} else {
echo 'empty for Ravi';
}
//} else {
//}
?>
to is a reserved word in MySQL, if you want to use it you must encase it in backticks:
.... WHERE `to` = ...
I have not look at your code but I recommend looking at
http://php.net/manual/en/intro.mysql.php
this before you continue to use mysql and not mysqli. It isn't that different but mysqli seems to have a wrapper over mysql and uses the "->" to instantiate new classes for a connection. If that makes any sense.
Try this:
<?php
$response = array();
$con = mysql_connect("localhost","root","");
if(!$con) {
die('Could not connect: '.mysql_error());
}
mysql_select_db("algopm1",$con);
//if (isset($_POST['to'])) {
$to = "Ravi";
$result = mysql_query("SELECT *FROM `events` WHERE `to` = '$to'");
if (!empty($result)) {
if (mysql_num_rows($result)>0) {
$row = mysql_fetch_array($result);
echo $row["to"] + " " + $row["from"];
} else {
echo 'rows = 0';
}
} else {
echo "empty for $to";
}
//} else {
//}
?>
MYSQLI version + some adjustments:
<?PHP
$host = "localhost";
$user = "root";
$password = "";
$database="algopm1";
$link = mysqli_connect($host, $user, $password, $database);
IF (!$link){
echo ("Unable to connect to database!");
}
ELSE {
$query = "SELECT *FROM `events` WHERE `to` = '$to'";
$result = mysqli_query($link, $query);
if (mysql_num_rows($result)>0) {
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)){
echo $row["to"]. "+". $row["from"];
}
}
ELSE {
echo 'rows = 0';
}
}
mysqli_close($link);
?>
I would like to credit #njk and #Wezy for their contribution with regard to the reserved word to in mysql. The WHILE loop is not necessary if the table events can only contain one "to" in this case "Ravi". I suspect that the number of events can be greater than one.
#Wezy has a point but let's do the troubleshooting:
As #JonathanRomer in his comment suggested, do:
$result = mysql_query("SELECT *FROM `events` WHERE `to` = '$to'") or die(mysql_error());
What does it say? Does it fail at all?
Or, just before mysql_query do:
die("SELECT *FROM `events` WHERE `to` = '$to'");
this will print faulty query being executed. Next, fire up mysql console or PHPMyAdmin and try executing this query manually.
Again, what does it say?
Actually, my main purpose was to encode this message and receive it on a mobile device by using JSON. This is the full code. For normal checking purpose, instead of using json_encode(*), the values can be displayed individually. This is the solution I got and it is working perfectly for receiving the data in an android app on which I am working.
<?php
$host = "localhost";
$user = "root";
$password = "";
$database="algopm1";
$response = array();
$mysqli = new mysqli($host, $user, $password, $database);
if (mysqli_connect_errno()){
$response["success"] = 0;
$response["message"] = mysqli_connect_error();
echo json_encode($response);
}
if(isset($_POST['to'])) {
$to = $_POST['to'];
$query = "SELECT *FROM `events` WHERE `to` = '$to'";
if($stmt = $mysqli->prepare($query)) {
$stmt->execute();
$stmt->store_result();
$i = 0;
if($stmt->num_rows > 0) {
$stmt->bind_result($rowto, $rowfrom, $rowevent);
$response["events"] = array();
while($stmt->fetch()) {
$events = array();
$events["to"] = $rowto;
$events["from"] = $rowfrom;
$events["event"] = $rowevent;
array_push($response["events"], $events);
}
$response["success"] = 1;
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No events found";
echo json_encode($response);
}
$stmt->close();
}
} else {
$response["success"] = 0;
$response["message"] = "Required fields are missing";
echo json_encode($response);
}
$mysqli->close();
?>

Categories