Updating data in mysql php - php

I'm trying to update data in my database with this function
<?php
require "conn.php";
$name = $_POST["name"];
$surname = $_POST["surname"];
$age = $_POST["age"];
$username = $_POST["username"];
$password = $_POST["password"];
$mysql_qry = "UPDATE user_data (name, surname, age, username, password) values ('$name','$surname','$age','$username','$password')";
if($conn->query($mysql_qry) === TRUE) {
echo "Success!";
}
else {
echo "Something is wrong :( Error: " . $mysql_qry . "<br>" . $caonn->error;
}
$conn->close();
but it always goes to Error. Can you help me with this? I was trying to put data from keyboard but it's not working either.
I've changed this line
$mysql_qry = "UPDATE user_data SET name = '$name'";
and now it's working but its changing all the names in database and I want to change only one record...

Add WHERE id=THAT_ID and you will be fine. THAT_ID or 'THAT_ID' depending on whether the "id" field in the database is a number or text, respectively (without apostrophes if it's a number, and with apostrophes if it is a text field). Off course, change THAT_ID to whatever id you want.

Related

MYSQL insert into multiple tables doesn't work

I have three files reg_form.php, dbconnection.php and insert.php.
When submitting the form the data is not inserted into the database. I can't figure out why. Initially I didn't know how to use insert into multiple tables but took the advice of many posts from here. Unfortunately I have still failed to make it work and it is driving me insane. Here is the sql code so far for the insert.
<?php
include ("dbconnection.php");
if(file_exists("dbconnection.php")) {
echo"Connected to database successfully";
} else if(!file_exists("dbconnection.php")){
echo "Connection failed";
}
$forename = "forename";
$surname = "surname";
$address_line1 = "address_line1";
$address_line2 = "address_line2";
$address_line3 = "address_line3";
$city = "city";
$postcode = "postcode";
$phone = "phone";
$email = "email";
$username = "username";
$password = "password";
$cpassword = "cpassword ";
$query = "INSERT INTO users (username,
password)VALUES('$username','$password');";
$query2 = "INSERT INTO users_details (forename, surname,address_line1,
address_line2, address_line3, city, postcode, phone, email)
VALUES('$forename','$surname','$address_line1','$address_line2',
'$address_line3','$city','$postcode','$phone','$email')";
query ($dbconnection,$sql);
?>
Ok problem is solved. I made a stored procedure because I am doing an INSERT INTO multiple tables and then called it like this.
$sql ="CALL add_user('".$username."', '".$password."', 'user',
'".$forename."','".$surname."', '".$address_line1."' ,
'".$address_line2."', '".$address_line3."', '".$city."', '".$postcode."',
'".$phone."', '".$email."','".is_bool($email_contact)."',
'".is_bool($phone_contact)."')";
$query = $con->prepare($sql);
$query->execute();

how to store session value in another table?

I have one login page and its database. i want to take the email from there and store it in another table of the same database. Code is give below please have a look and tell me.
Table 1
<?php
session_start();
$email = $_POST['email'];
$password = $_POST['password'];
include 'connection.php';
$sql = "SELECT * FROM users WHERE email='$email' AND password='$password'";
$res = mysql_query($sql);
$count = mysql_num_rows($res);
if($count == 0)
{
echo "Username Password Incorrect";
}
else
{
$_SESSION['email'] = $email;
header("location:home2.php")
}
?>
Table 2
<?php
$email= (HOW TO GET IT FROM SESSION?)
$company = $_POST['company'];
$project = $_POST['project'];
$duration = $_POST['duration'];
$key_learning = $_POST['key_learning'];
include 'connection.php';
$sql = "INSERT INTO `internship`(`id`, `email`, `company`, `project`, `duration`, `key_learning`) VALUES ('', '$email', '$company','$project', '$duration', '$key_learning')";
$res = mysql_query($sql);
$count = mysql_num_rows($res);
if($count == 1)
{
echo "Fail";
}
else
{
$_SESSION['email'] = $email;
header("location:home3.php");
}
?>
From table 1 i want to take email if using session and want to store it in table 2. How to do it?
$email= (HOW TO GET IT FROM SESSION?)
If the 2nd code block is in the same execution context as the first, you can just use the variable $email that you created.
If you're trying to retrieve data from session as the user navigates to a new page, you do:
<?php
session_start();
$email = isset($_SESSION['email'])? $_SESSION['email'] : null;
By the way, in the 2nd code block you're trying to use mysql_num_rows to analyze the effect of an INSERT query. You can't do that. According to the manual:
[mysql_num_rows] retrieves the number of rows from a result set. This
command is only valid for statements like SELECT or SHOW that return
an actual result set. To retrieve the number of rows affected by a
INSERT, UPDATE, REPLACE or DELETE query, use mysql_affected_rows().
$res = mysql_query($sql) or die(mysql_error());
if(mysql_affected_rows()){
//success
}else{
//failure
}
You should not be using mysql_ functions anyway and you should most definitely not be inserting user provided values (username, email, password) directly in your SQL statement

PHP Code executing but not inserting data?

I've followed a year old online tutorial of Unity Client - PHP Server - Database integration. The code seems to execute fine, it reaches the 'echo"Success"' line etc perfectly.
However when I look at my database, there is nothing there. Its blank, and I have no idea why.
Note: The online tutorial used mysql... whereas I'm using the (non-depracted) mysqli... but there didn't seem to be that much of a difference, but I'm a total rookie at PHP coding, only having minimal experience at it so it is very possible I'm wrong?
<?php
/**
* Created by PhpStorm.
* User: Josh
* Date: 09/04/2016
* Time: 14:11
*/
$Username = $_REQUEST["Username"];
$Password = $_REQUEST["Password"];
$Hostname = "localhost";
$DBName = "statemilitaryrpdb";
$User = "root";
$PasswordP = "";
$link = mysqli_connect($Hostname, $User, $PasswordP, $DBName) or die ("Can't Connect to DB");
if (!$Username || !$Password) {
echo "Empty";
} else
{
$SQL = "SELECT * FROM accounts WHERE Username = '" . $Username ."'";
$Result = #mysqli_query($link, $SQL) or die ("DB ERROR");
$Total = mysqli_num_rows($Result);
if($Total == 0)
{
$insert = "INSERT INTO 'accounts' ('Username', 'Password') VALUES ('" .$Username . "', MD5('" . $Password . "'), 0)";
$SQL1 = mysqli_query($link, $insert);
$Result2 = #mysqli_query($link, $SQL) or die ("DB ERROR");
echo(mysqli_num_rows($Result2));
}
else
{
echo"Username Already Used";
}
}
mysqli_close($link);
$insert = "INSERT INTO 'accounts' ('Username', 'Password') VALUES ('" .$Username . "', MD5('" . $Password . "'), 0)";
Answer: Username and Password are the fields but you are trying to insert Username, Password and 0
Suggestion: Do more than just MD5 encryption, that is SUPER easy to decrypt.
Edit:
Also like #andrewsi said in the comments if your only going to check if its empty, than anyone could SQL inject your database and drop your tables or make changes. Make sure that you are filtering your inputs correctly.
Firstly, your query have only 2 columns, but you are inserting 3 values:
$insert = "INSERT INTO 'accounts' ('Username', 'Password') VALUES ('" .$Username . "', MD5('" . $Password . "'), 0)";
Columns
Username
Password
Values to insert
$Username
md5($Password)
0
Thus, not all the values will be inserted.
Secondly, for MySQL related names, you need to use back ticks instead of single-quote.
Thus, this:
INSERT INTO 'accounts'
Should be:
INSERT INTO `accounts`
Thirdly, your code is vulnerable to MySQL Injection, you should prevent it using mysqli_real_escape_string():
$Username = mysqli_real_escape_string($link, $_REQUEST["Username"]);
$Password = mysqli_real_escape_string($link, $_REQUEST["Password"]);
Tip: You shouldn't suppress error messages:
#mysqli_query($link, $SQL)
Remove # to enable error reporting. It's very useful in diagnosing syntax errors.
Also, you shouldn't use md5() to hash passwords, as it's not very secure. Use password_hash and password_verify instead.
In debug mode, never use # to suppress errors, ie. #mysqli_query. Also or die("DB ERROR") isn't very descriptive. Even if that resolves, what good does DB ERROR provide you? Instead, use or die( mysqli_error($link) ) to see what's really going on with the query.
You also have 3 values to be inserted, but only 2 columns represented in the query statement:
('Username', 'Password') // 2 columns
VALUES ('" .$Username . "', MD5('" . $Password . "'), 0)"; // 3 values
What column is 0 being inserted into? This value needs to be represented by a column.
And a table/column name should never be wrapped with quotes; only ticks `accounts`

Several Errors when trying to enter data into mysql

I keep getting this error when trying to use my form to submit data into mysql
"Insertion Failed:Column count doesn't match value count at row 1"
<?php
include 'dbc.php';
$rank = $_POST['rank'];
$lname = $_POST['lname'];
$fname = $_POST['fname'];
$platoon = $_POST['platoon'];
$squad = $_POST['squad'];
$justsuta =$_POST['justsuta'];
$fdate =$_POST['fdate'];
$tdate =$_POST['tdate'];
$ddate1 =$_POST['ddate1'];
$ddate2 =$_POST['ddate2'];
$ddate3 =$_POST['ddate3'];
$sdate1 =$_POST['sdate1'];
$sdate2 =$_POST['sdate2'];
$sdate3 =$_POST['sdate3'];
$sql_insert = "INSERT into `forms`
(`rank`,`lname`,`fname`,`platoon`,`squad`,`justsuta`,`fdate`,`tdate`,`ddate1`,`ddate2`,`ddate3`,`sdate1`,`sdate2`,`sdate3`)
VALUES('$rank','$lname','$fname','$platoon','$squad','$justsuta','$fdate','$tdate','$ddate1','$ddate2','$ddate3','$sdate1','$sdate2','$sdate3', NOW())";
mysql_query($sql_insert) or die("Insertion Failed:" . mysql_error());
?>
Do i have something wrong with my code? Thank you for your help in advance
Your issue is that you've supplied more data than the amount of columns you've specified.
You specify 14 columns:
(`rank`,`lname`,`fname`,`platoon`,`squad`,`justsuta`,`fdate`,`tdate`,`ddate1`,`ddate2`,`ddate3`,`sdate1`,`sdate2`,`sdate3`)
Yet you supply 15
VALUES('$rank','$lname','$fname','$platoon','$squad','$justsuta','$fdate','$tdate','$ddate1','$ddate2','$ddate3','$sdate1','$sdate2','$sdate3', NOW())";
You either have to remove the NOW() or the $sdate3 in the data you supply.

php form script

I'm very new to PHP and am having some trouble. I have a form using HTML which is action=.php method=post
The form is using text boxes and select options, I'm not sure if it makes a difference in sqldatabase. I've tried about 30 different combinations of this script and can only get a connect successfully message but nothing is posted.
<?php
$link = mysql_connect('everybodyslistcom.ipagemysql.com', 'accounts', 'accounts');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_select_db("user");
$FName = $_POST["FName"];
$LName = $_POST["Lname"];
$Phone = $_POST["Phone"];
$EmailAddress = $_POST["EmailAddress"];
$Month = $_POST["Month"];
$Day = $_POST["Day"];
$Year = $_POST["Year"];
$Username = $_POST["Username"];
$Password = $_POST["Password"];
$sql = 'INSERT INTO Members (ID, FName, LName, Phone, EmailAddress, Month, Day, Year, Username, Password) VALUES'
. '(\'\', \'$FName\', \'$LName\', \'$Phone\', \'$EmailAddress\', \'$Month\', \'$Day\', \'$Year\', \'$Username\', \'$Password\')';
mysql_close();
php?>
try to execute your query
mysql_query($sql);
EDIT: I see you are doing this:
$sql = 'SELECT bla bal $variable';
PHP will not parse the variable. The right way:
$sql = "SELECT bla bla $variable"; // valid
$sql = "SELECT bla bla {$variable}"; // also valid
$sql = 'SELECT bla bla '.$variable; // also valid
your closing php tag is not correct, it should be
?>
rather than
php?>
Also u r not executing your query using:
mysql_query('your query here');
this might cause the problem.
Your variables are not interpreted by PHP. If you want variable to be parsed in string, it should be wrapped in double-quote (")
It may fail if any of your posted data contains some quote character, so you must apply mysql_real_escape_string to all of them.
I hope that database connection credentials are not real you posted here? :D
You said that your form contains "action=.php" literally, you have to turn it into :
<form name="form_name" method="post" action="your_script.php">
You need to execute the query too:
mysql_query($sql, $link);
you should also check whether POST was really sent:
if (!empty($_POST)) {
// ... your code here
}
next thing: you don't need closing tag ?> if your *.php file consist only PHP code - end of file is also correct end of PHP block of code - it's "good-to-have" habit, because in some cases it helps you to avoid error: "Cannot add/modify header information - headers already sent by..."
next problem - wrong way of inserting variables into string:
$sql = 'INSERT INTO Members (ID, FName, LName, Phone, EmailAddress, Month, Day, Year, Username, Password) VALUES'
. '(\'\', \'$FName\', \'$LName\', \'$Phone\', \'$EmailAddress\', \'$Month\', \'$Day\', \'$Year\', \'$Username\', \'$Password\')';
correct way:
$sql = "INSERT INTO Members (ID, FName, LName, Phone, EmailAddress, Month, Day, Year, Username, Password) VALUES (null, '$FName', '$LName', '$Phone', '$EmailAddress', '$Month', '$Day', '$Year', '$Username', '$Password')";
more info here
next - as Deniss said, instead of:
$FName = $_POST["FName"];
should be:
$FName = mysql_real_escape_string($_POST["FName"]);
actually you should fist check weather magic quotes gpc are on or off:
if (get_magic_quotes_gpc()) {
if (!empty($_POST)) {
array_walk_recursive($_POST, 'stripslashes_value');
}
}
function stripslashes_value(&$value) {
$value = stripslashes($value);
}
without this you could have problem with double \\ inserted into db (it depends on your server configuration)
and last but not least: as Robert said you miss one more important thing:
mysql_query($sql);
I think your error because your have not call mysql_query function
can try my code edit
<?php
$link = mysql_connect('everybodyslistcom.ipagemysql.com', 'accounts', 'accounts');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_select_db("user",$link);
$FName = $_POST["FName"];
$LName = $_POST["Lname"];
$Phone = $_POST["Phone"];
$EmailAddress = $_POST["EmailAddress"];
$Month = $_POST["Month"];
$Day = $_POST["Day"];
$Year = $_POST["Year"];
$Username = $_POST["Username"];
$Password = $_POST["Password"];
$sql = "INSERT INTO Members SET FName='{$FName}', LName='{$LName}', Phone='{$Phone}', EmailAddress='{$EmailAddress}', Month='{$Month}', Day='{$Day}', Year='{$Year}', Username='{$Username}', Password='{$Password}'";
// Call Function mysql_query insert new record in mysql table
mysql_query($sql,$link);
mysql_close($link);
?>
Comment for me if your have problem :) or notes of apache services
good day

Categories