I am having problem updating an existing row in my database. What I need to do is add a record to a field named "Time_Out". This field is on the same row as with the "Time_In", "username", and "date_added". The Time_In is working perfectly fine. This is the code I've used:
date_default_timezone_set('Asia/Taipei');
$date_added = date ("Y-m-d");
$time_added = date ("h:i:s:a:");
$user = $_SESSION['xxxx']['xxxxx'];
$con = mysqli_connect("localhost", "xxxx", "xxxx", "test");
$save = mysqli_query($con, "INSERT INTO time_logs (username, date_added, Time_In) VALUES('$user', '$date_added', '$time_added')");
if(!$con) {
die('Could not connect to the database' . mysql_error());
mysql_close($con);
}
else
header("Location: etc.php");
For the Time_Out, I have removed the "INSERT INTO ..." line and changed it into:
$save = mysqli_query($con, "UPDATE time_logs SET Time_Out = $time_added WHERE username = $user");
but the record in the Time_Out field in my database is still showing 0:00.
By the way, my date_added is set to Date and the Time_In and Time_Out is set to Time.
I would really appreciate it if someone could show me how to do this using PHP. Thank you in advance.
You're missing single quotes around your non-numeric data. Try:
$save = mysqli_query($con, "UPDATE time_logs SET Time_Out = '$time_added' WHERE username = '$user'");
Your code has a few issues. First in this chunk you are using mysqli_* and mysql_* extensions mixed together when they should all be mysqli_*:
date_default_timezone_set('Asia/Taipei');
$date_added = date ("Y-m-d");
$time_added = date ("h:i:s:a:");
$user = $_SESSION['xxxx']['xxxxx'];
$con = mysqli_connect("localhost", "xxxx", "xxxx", "test");
$save = mysqli_query($con, "INSERT INTO time_logs (username, date_added, Time_In) VALUES('$user', '$date_added', '$time_added');");
if (!$con) {
die('Could not connect to the database' . mysqli_error($con));
mysqli_close($con);
}
else
header("Location: etc.php");
Specifically it was in your if (!$con) { check. Look at the cleaned up example now. But also, your update does not have single quotes around string values:
$save = mysqli_query($con, "UPDATE time_logs SET Time_Out = $time_added WHERE username = $user");
So it should be like this:
$save = mysqli_query($con, "UPDATE time_logs SET Time_Out = '$time_added' WHERE username = '$user'");
But to make your life easier, you might want to reformat your queries like this:
$query = "UPDATE time_logs SET Time_Out = '" . $time_added . "' WHERE username = '" . $user . "';";
$save = mysqli_query($con, $query);
Note how I set the query in a separate string & then added concatenation to the string itself for the variables. This makes it easier to spot issues like this in text editors in my humble option. I also ended each of your queries with a semicolon (;) since that again makes it clearer to me that is the true end of the query statement.
Related
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`
So I have form1 that contains information from multiple tables in a database. I've got listboxes and textboxes within this form that have that information. So all I'm trying to do is insert whatever information the user submits back into the database and have it outputted on form2. I've got my INSERT INTOs on my output page. I know you can't use one INSERT INTO query, so I was wondering how to use multiple INSERTS and submit that information back into the database.
The variables created below come from the previous page and all of the values are there.
if (isset($_POST['n_submit'])){
$oid = $_POST['oid'];
$odate = $_POST['odate'];
$ostatus = $_POST['ostatus'];
$cfname = $_POST['cfname'];
$cname = $_POST['clname'];
$efname = $_POST['efname'];
$elname = $_POST['elname'];
echo "New record created successfully";
$db = mysqli_connect('127.0.0.1:3307', 'mysql_user', 'mysql_password') or die ("I cannot connect to the database because: ".mysqli_connect_error());
$query = "select status_id from ostatus where status_type = '$ostatus'";
$result = mysqli_query($db, $query) or die("Error in SQL statement:" .mysqli_error());
$row = mysqli_fetch_array($result);
$statusid = $row[0];
$query1 = "insert into cust ('c_fname', 'c_lname') values ('$cfname', $clname)";
$result1 = mysqli_query($db, $query1) or die("Error in SQL statement:" .mysqli_error());
$query2 = "insert into employed ('e_fname', e_lname) values ('$efname', '$elname')";
$result2 = mysqli_query($db, $query1) or die("Error in SQL statement:" .mysqli_error());
$query3 ="INSERT INTO sorder (o_id, o_date, s_id) VALUES ('{$oid}', '{$odate}', '{$statusid}')";
$result3 = mysqli_query($db, $query3);
}
First of all your query is vulnerable to SQL injection. I am not going to fix that.
Second, you should Google how to handle forms properly. And you should consider starting SQL transaction if you really care about the data to go into all the tables for sure.
Third, you should be able to use multiple inserts like you are doing in your code. but you need to correct your syntax errors.
Try this code (I also removed the select code are based on your question it is not needed)
if (isset($_POST['n_submit'])){
$oid = $_POST['oid'];
$odate = $_POST['odate'];
$ostatus = $_POST['ostatus'];
$cfname = $_POST['cfname'];
$cname = $_POST['clname'];
$efname = $_POST['efname'];
$elname = $_POST['elname'];
$db = mysqli_connect('127.0.0.1:3307', 'mysql_user', 'mysql_password') or die ("I cannot connect to the database because: ".mysqli_connect_error());
$query1 = "insert into cust (c_fname, c_lname) values ('".$cfname."', '".$clname."')";
$result1 = mysqli_query($db, $query1) or die("Error in SQL statement:" .mysqli_error());
$query2 = "insert into employed (e_fname, e_lname) values ('".$efname."', '".$elname."')";
$result2 = mysqli_query($db, $query2) or die("Error in SQL statement:" .mysqli_error());
$query3 ="INSERT INTO sorder (o_id, o_date, s_id) VALUES ('".$oid."', '".$odate."', '".$statusid."')";
$result3 = mysqli_query($db, $query3);
if($result1 && $result2 && $result3)
echo 'New record created successfully';
else
echo 'something did not work';
}
I have a registration script where the user id is saved as a session variable after registration and the user is redirected to their homepage. For some reason the user id is not being stored in the session variable. This exact same script worked on a different project, I simply took the project and changed the database connection settings and now it's not working.
Here is the registration script:
mysqli_connect($db_host, $db_user, $db_pass) OR DIE (mysqli_error());
// select the db
mysqli_select_db ($link, $db_name) OR DIE ("Unable to select db".mysqli_error($db_name));
// our sql query
$sql = "INSERT INTO seekers (first_name, last_name, username, email, password, salt) VALUES ('$firstName', '$lastName', '$username', '$email', '$hashedPW', '$salt');";
//save the updated information to the database
$result = mysqli_query($link, $sql) or die("Error in Query: " . mysqli_error($link));
if (!mysqli_error($link)) {
$row = mysqli_fetch_assoc($result);
$_SESSION['user_id'] = mysqli_insert_id($link);
$_SESSION['loggedin'] = TRUE;
header("Location: ../index.php");
}
And here is the session checking and db query on the protected page:
session_start();
if(isset($_SESSION['loggedin']) && $_SESSION['user_id'] != 'user_id') {
include_once('includes/user.header.php');
//set user_id
$user_id = $_SESSION['user_id'];
//include the logged in user header
include_once('includes/user.header.php');
//select user information according to their logged in user_id
$sql = $link->query('SELECT * FROM seekers WHERE id = "'.$user_id.'"');
$row = mysqli_fetch_assoc($sql);
//create piece name together
$firstName = $link->real_escape_string($row['first_name']);
$lastName = $link->real_escape_string($row['last_name']);
$fullName = $firstName. " " .$lastName;
//get username
$username = $link->real_escape_string($row['username']);
When I am redirected to the index.php page, everything looks fine, except none of the user information is being queried from the DB.
Can anyone see what is wrong here? I know it's got to be something little and I'm just over looking it.
Please any help would be greatly appreciated.
EDIT: All information is being stored in the database successfully as well.
You are trying to use user_id without a select query ... indeed you must get the last insert id
changed line ;
$_SESSION["user_id"]=mysql_insert_id();
and
if (!mysqli_error($link))
should be
if (!mysqli_error($result))
and
$sql = $link->query('SELECT * FROM seekers WHERE id = "'.$user_id.'"');
to
$sql = $link->query('SELECT * FROM seekers WHERE user_id = "'.$user_id.'"');
I'm kinda new to PHP and only using it for the backend of my Android App.
I've got three strings that I'm sending to the PHP from my Android App. I want to query a table called 'users' and find the userid of the username that was sent from my Android App and then inset the data into a seperate table called 'msg'.
I've tried for my life and I cannot get it to work, plus I haven't even finished.
thanks and helping me would be pretty amazing, as I'm new to PHP and can't finish off the rest of the code.
PHP:
<?php
$username = $_POST['username'];
$msg = $_POST['msg'];
$frienduser = $_POST ['frienduser'];
/*mysql data below */
$dbc = mysql_connect('localhost', 'removemypasswords', 'again');
if(!dbc) {
die("Something went wrong! Try again...");
}
/* select database */
$db_select = mysql_select_db("andagain, $dbc");
if (!db_select){
die("Can't connect :" .mysql_error);
}
$query = mysql_query("SELECT FROM users WHERE usernames ='$usernames'");
$query1 = mysql_query(INSERT INTO `gtanews1_zips54`.`msg` (
`id` ,
`friendid` ,
`msg`
)
VALUES (
'$query', '$frienduser', 'msg'
);
echo ($msg);
?>
how about putting quotes around $query1 like
$query1 = mysql_query("INSERT INTO gtanews1_zips54.msg (`id` ,`friendid` ,`msg`)
VALUES ('$query', '$frienduser', 'msg')");
Should be
$query = mysql_query("SELECT * FROM users WHERE usernames ='$username'");
$result = mysql_fetch_array($query);
$query1 = mysql_query("INSERT INTO gtanews1_zips54.msg (id,friendid,msg) VALUES ('" . $result['yourField'] . "', '$frienduser','$msg')");
your mysql select db code is wrong. you need to have the quotes before the comma
mysql_select_db("andagain", $dbc);
also place quotes at the end of your query
$query = mysql_query("SELECT FROM users WHERE usernames ='$usernames'"); $query1 = mysql_query(INSERT INTO `gtanews1_zips54`.`msg` ( `id` , `friendid` , `msg` ) VALUES ( '$query', '$frienduser', 'msg' )");
There's a lot going wrong here:
<?php
$username = $_POST['username'];
$msg = $_POST['msg'];
$frienduser = $_POST ['frienduser'];
/*mysql data below */
$dbc = mysql_connect('localhost', 'removemypasswords', 'again');
if(!$dbc) { //- You forgot the dollar $ sign on $dbc
die("Something went wrong! Try again...");
}
/* select database */
$db_select = mysql_select_db("andagain", $dbc); //- You had the entire thing quoted, quotes are just around "andagain"
if (!db_select){
die("Can't connect :" .mysql_error()); //- You forgot the parentheses after mysql_error
}
$query = mysql_query("SELECT FROM users WHERE usernames ='$usernames'");
//- You need to actually get the results out of the query object
$row = mysql_fetch_assoc($query);
if (!$row) {
die('User not found');
}
$user_id = $row['id']; //- Or whatever the column is called
$query1 = mysql_query("INSERT INTO `gtanews1_zips54`.`msg` (
`id` ,
`friendid` ,
`msg`
)
VALUES (
'$user_id', '$frienduser', 'msg'
"); //- You forgot to put quotes around this query
echo ($msg);
?>
And that's just to start, there may be other problems depending on your database schema / data transfer format.
Also, you're wide open to SQL injection.
your code have many errors .
$db_select = mysql_select_db (andagain, $dbc);
$query = mysql_query('SELECT FROM users WHERE usernames ="$usernames"');
since Stackoverflow is not a community for fixing codes bugs ..so i am leaving this job for you .
below are some points which can help you to fix all errors ?
Variable-substitution cann't be dont with single quotes (') . double quotes allow variable substitution .
to escape quotes inside quotes , we use \
parameter cannot be encapsulated with double quotes .
I have almost no experience with PHP and right now I'm stuck at the total beginning, which is really frustrating. I have a code, which seems to work. From my app I can input values and put them in my PHP database. Thing is that he only inputs the very last value from my PHP code. So the app aside: If I only use the PHP code to input something in my database he always only takes the last value. Here is my code:
<?php
$DB_HostName = "localhost";
$DB_Name = "xxx";
$DB_User = "xxx";
$DB_Pass = "xxx";
$DB_Table = "contacts";
if (isset ($_GET["name"]))
$name = $_GET["name"];
else
$name = "Blade";
if (isset ($_GET["lastname"]))
$lastname = $_GET["lastname"];
else
$lastname = "Xcoder";
if (isset ($_GET["number"]))
$number = $_GET["number"];
else
$number = "111";
$con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die(mysql_error());
mysql_select_db($DB_Name,$con) or die(mysql_error());
$sql = "insert into $DB_Table (Firtname) values('$name');";
$sql = "insert into $DB_Table (Lastname) values('$lastname');";
$sql = "insert into $DB_Table (Number) values('$number');";
$res = mysql_query($sql,$con) or die(mysql_error());
mysql_close($con);
if ($res) {
echo "success";
}else{
echo "faild";
}// end else
?>
To clarify: If I only have the firstname value, he inputs it in the right place (firstname). If I have a firstname and lastname value, he only inputs the lastname value, but not the firstname value (still at the right place lastname). And the same for number. If I have a firstname, lastname and a number, he only puts the number in the right place but not the other values. In addition I can only do it once. If I want to enter another contact he always says (Duplicate entry 'myentry' for key 'PRIMARY').
You overwrite your query, 2 ways to solve. Either 3 different variables, or 1 variable with 3 queries in it. I would prefer the 2nd option
$sql = "insert into $DB_Table (Firtname) values('$name');";
$sql .= "insert into $DB_Table (Lastname) values('$lastname');";
$sql .= "insert into $DB_Table (Number) values('$number');";
$res = mysql_query($sql,$con) or die(mysql_error());
Or if it can be 1 row in the table, as it is the same table anyways:
$sql = "insert into $DB_Table (Firtname,Lastname,Number) values('$name','$lastname','$number');";
$res = mysql_query($sql,$con) or die(mysql_error());
Because you are overwriting $sql on the next 2 lines, so the final sql line is what is inserted.
Your sql is wrong if you want them all in the same row.
$sql = "insert into $DB_Table (Firtname,lastname,number) values('$name','$lastname','$number');";
You are overwriting your $sql statements. You have to execute them. By doing:
$sql = "Insert INTO..."
you merely set a a variable. You need to ru each query using mysql_query().
I'm also guessing that you want to do this:
$sql = "INSERT INTO $DB_TABLE (Firstname, Lastname, Number) VALUES ('$name', '$lastname', '$number')
Finally, it is crucial that you sanitise your inputs:
$name = mysql_real_escape_string($_GET["name"]);
Thanks to this you avoid an SQL Injection attack.
You are overwriting $sql string each time.
Perhaps you meant to use the .= to append all three queries together. What is the structure for database tables?
$sql = "insert into $DB_Table (Firtname) values('$name');";
$sql .= "insert into $DB_Table (Lastname) values('$lastname');";
$sql .= "insert into $DB_Table (Number) values('$number');";
That is because you use the same variable name ($sql) for all 3 queries. Use $sql1, $sql2 and $sql3 instead. Also, call mysql_query for each one (but only if you've set it).
Like this:
$sql1 = "insert into $DB_Table (Firtname) values('$name');";
$sql2 = "insert into $DB_Table (Lastname) values('$lastname');";
$sql3 = "insert into $DB_Table (Number) values('$number');";
if (isset ($sql1))
{
$res1 = mysql_query($sql1,$con) or die(mysql_error());
}
if (isset ($sql2))
{
$res2 = mysql_query($sql2,$con) or die(mysql_error());
}
if (isset ($sql3))
{
$res3 = mysql_query($sql3,$con) or die(mysql_error());
}