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 .
Related
While giving the correct login ID and Password which is there in the databse "tutorial" in table "users", it is giving me an error on the login.php which is being redirected.
Error is:
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 ''users' WHERE 'user' = 'XYZ'' at line 1
where XYZ is the username given from the user.
<?php
$inputuser = $_POST["user"];
$inputpass = $_POST["pass"];
$user = "root";
$password = "";
$database = "tutorial";
$connect = mysql_connect("localhost", $user, $password);
#mysql_select_db($database) or die("Database not found");
$query = "SELECT * FROM 'users' WHERE 'user' = '$inputuser'";
$querypass = "SELECT * FROM 'users' WHERE 'password' = '$inputpass'";
$result = mysql_query($query) or die(mysql_error());
$resultpass = mysql_query($querypass) or die( mysql_error());
$row = mysql_fetch_array($result);
$rowpass = mysql_fetch_array($resultpass);
$serveruser = $row["user"];
$serverpass = $row["password"];
if ($serveruser && $serverpass){
if(!$result){
die("Username Name or Password is invalid");
}
echo "<br><center>Database Output</b> </center><br><br> ";
mysql_close();
echo $inputpass;
echo $serverpass;
if($inputpass == $serverpass){
header('Location: home.php');
} else {
echo "Sorry, bad Login";
}
}
?>
Abhik Chakraborty is correct.
If you want to enclose field/column or table names you have to use backticks (so ` instead of '). The backtick is the diagonal quote on the button next to the "1", above "Tab".
To enclose field values you should use quotes the way you did.
Your corrected query: SELECT * FROM `users` WHERE `user` = '$inputuser';
HOWEVER, you should never, ever insert input gotten from a user directly into a query. If they type in something like a';DROP TABLE your_table_name; they can cause your database to start deleting tables, requesting records, etc.
Use correct escaping of user input: see this StackOverflow article on how to safely escape user input.
Instead of single quotes you should use back ticks (`)
i really dont know why this code isnt working.. database connection works, the timestamp is written to the database.
But i cant figure out why i get a blank page with this code here (i should see the timestamp as echo).
Anyone an idea about this ?
Thank you!
<?php
$user = "daycounter";
$password = "1234";
$database = "daycounter";
$host = "localhost";
$date = time();
// Create connection
$conn = new mysqli($host, $user, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Error: " . $conn->connect_error);
}
//Insert timestamp in database
$sql = "INSERT INTO datum (datum)
VALUES ('".$date."')";
//check if that worked
if ($conn->query($sql) === TRUE) {
echo "That worked!";
}
//get timestamp from db and display it as echo
$select = "SELECT 'datum' FROM 'daycounter'";
$result = mysql_query($select);
while($row = mysql_fetch_object($result))
{
echo "$row->datum";
}
?>
You're using a mysqli DB connection, but calling mysql to do your select. You cannot mix/match the database libraries like that. If you'd had even minimal error checking, you'd have been told that there's no connection to the db:
$result = mysql_query($select) or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^
Plus, your select query has syntax errors. 'daycounter' is a string literal - you cannot select FROM a string. 'datum' would be syntactically correct, you can select a string literal from a table, but most like you want:
SELECT datum FROM daycounter
or
SELECT `datum` FROM `daycounter`
Neither of those words are a reserved word, so there's NO need to quote them, but if you're one of those people who insist on quoting ALL identifiers, then they must be quoted with backticks, not single-quotes.
$select = "SELECT 'datum' FROM 'daycounter'";
$result = mysqli_query($conn, $select);
while($row = mysqli_fetch_object($result)) {
echo "$row->datum";
}
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.
<?php
include ("account.php") ;
( $dbh = mysql_connect ( $hostname, $username, $password ) )
or die ( "Unable to connect to MySQL database" );
print "Connected to MySQL<br>";
mysql_select_db($project);
$number = NULL ;
$username = $_POST["username"];
$priority = $_POST["priority"];
$category = $_POST["category"];
$incident_description = $_POST["incident_description"];
$sql = "insert into incident values ( NULL, '$username','$priority','$category','$incident_description',curdate(),curtime() )" ;
mysql_query ( $sql ) or print ( mysql_error ( ) );
$credentials = "select * from Credentials where ("username" = '$username' ,"password" = '$password' , "email_address" = 'email_address')" ;
print $credentials;
$result = mysql_query ($credentials) or print (mysql_error ( ) );
$howManyRows = mysql_num_rows ( $result);
//if $howManyRows is positive continue process to update database with sql,if not,die.
?>
There is an html code for a form on another file hence the $_POST, but I don't think it s necessary to show it here since I need the right syntaxes on this php file.
With the part from the $credentials I need help with how to compare the values in the html form (username,password,email_address) with values in the table "Credentials" from the database?I need to do this in order to authorize the values to carry on the process.
The syntax I got there isn't right at the moment because it doesn't execute it properly. I just don't know how to compare the two.
This whole thing works up until the mysql_query ( $sql ) or print ( mysql_error ( ) ) line.
Suggestions would be nice.I apologize for the long question!
PS: columns for the Credentials table are username,password,email_address as well!
the problem is here
$credentials = "select * from Credentials where ("username" = '$username' ,"password" = '$password' , "email_address" = 'email_address')" ;
change to
$credentials = "select * from Credentials where `username` = '$username' and `password` = '$password' and `email_address` = 'email_address'" ;
The problem is in query, when you want to check multiple values use AND in WHERE clause.
I dont know but shouldn't u use the following...
$sql = "INSERT INTO incident (fieldname, fieldname) VALUES ('".mysql_real_escape($_POST['fieldname'])."', '".mysql_real_escape($_POST['fieldname'])."')";
To insert anything into mysql?
You can use your credential query as below
$credentials = "select * from Credentials where username = '$username' AND password = '$password' AND email_address = 'email_address'" ;
BUT for better performance & to prevent your code for mysql injection you have to do following things
1) Use Mysqli instead of mysql functions. here is good lib for mysqli as wrapper
https://github.com/nWidart/PHP-MySQLi-Database-Class
2) Always keep your database connection string to separate file and at safe place. then, include your connection file into your require project file.
3) Always validate value of your variables & use mysql_real_escape before using directly into query.
Try
$password = mysql_real_escape($_POST['password']); //to avoid SQL injunction
$username = mysql_real_escape($_POST['username']);
$credentials = "select * from Credentials where username = '$username' AND password = '$password' AND email_address = 'email_address'" ;
I believe I have a simple syntax problem in my SQL statement. If I run this code, I get an error in the database query.
$user = $_GET['linevar'];
echo $user; // testing - url variable echos correctly
$sql = "SELECT * FROM `userAccounts` WHERE `name` = $user";
$result = mysql_query($sql) or die("Error in db query");
If I replace $user in the $sql string with 'actualName' or a known record in my table, the code works fine. Am I using the $ variable incorrectly in the SQL string?
You need to surround the value that you're getting from $user with quotes, since it's probably not a number:
$sql = "SELECT * FROM `userAccounts` WHERE `name` = '$user'";
Just as a note, you should also read up on SQL injection, since this code is susceptible to it. A fix would be to pass it through mysql_real_escape_string():
$user = mysql_real_escape_string( $_GET['linevar']);
You can also replace your or die(); logic with something a bit more informative to get an error message when something bad happens, like:
or die("Error in db query" . mysql_error());
You need escape the get input, then quote it.
// this is important to prevent sql injection.
$user = mysql_real_escape_string($_GET['linevar']);
$sql = "SELECT * FROM `userAccounts` WHERE `name` = '$user'";
This should work:
$sql = "SELECT * FROM `userAccounts` WHERE `name` = '" . $user . "'";