PHP assign where in the link - php

I have coded a php script that will generate a pdf file from some results. My select statement needs to be filtered with a where condition. Basically, I want to test my php script to see if it works well or not. How can I assign the where condition in the link itself?
this is my php code :
$query = "
SELECT
user_id
FROM TahdirUsers
WHERE
username = ':username'
";
$query_params = array(
':username' => $_POST['username']
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex)
{
$response["success"] = 0;
$response["message"] = "Database Error1. Please Try Again!";
die(json_encode($response));
}
$row = $stmt->fetch();
if ($row)
{
if ($_POST['password'] === $row['password'])
{
$response["success"] = 1;
$response["message"] = "Login successful!";
die(json_encode($response));
}
else
{
$response["success"] = 0;
$response["message"] = "Invalid password!";
$pdf = new PDF(PDF_PAGE_ORIENTATION,PDF_UNIT,PDF_PAGE_FORMAT,true, 'UTF-8', true);
$pdf->SetFont('aefurat', '', 12, '', true);
// The first Parameter is localhost again unless you are retrieving data from a different server.
// The second parameter is your MySQL User ID.
// The third parameter is your password for MySQL. In many cases these would be the same as your OS ID and Password.
// The fourth parameter is the Database you'd like to run the report on.
$pdf->connect('xxxxxxxxx','xxxxxxx','xxxxxxxxx','xxxxxxxx');
// This is the title of the Report generated.
$attr=array('titleFontSize'=>24,'titleText'=>'THIS IS MY PDF FILE');
// This is your query. It should be a 'SELECT' query.
// Reports are run over 'SELECT' querires generally.
$pdf->mysql_report($query,false,$attr);
$pdf->Output('htmlout.pdf', 'I');
die(json_encode($response));
}
}
else
{
$response["success"] = 0;
$response["message"] = "this username in not in our database!";
die(json_encode($response));
}
To clarify my question. If my website link is www.testtesttest.com, how do I implement the where condition from the select statement in the URL

If my comment above is wrong, and your question is literally "how do I pass data from a URL to a PHP script", the answer is that you use the $_GET superglobal variable to access query strings in the standard format .../path/to/script.php?var1=value1&var2=value2...
So the URL http://amjad-test.site40.net/arabictest.php?username=imsop will execute 'arabictest.php' and populate the variable $_GET['username'] with the value 'imsop'. You then use that variable wherever you like in your code.

Related

Change password in Android

I am having problem when trying to change the password in my application. It keep showing current password is invalid. It might be problem from my PHP coding. But I can't find the problem. This is my code for PHP.
<?php
require ("config1.php");
if (!empty($_POST)) {
$lecID = $_GET['lecID'];
$query = "UPDATE lecturer SET lecPass= :lec_Pass WHERE lecID = '$lecID' ";
$query_params = array(':lec_Pass'=> $_POST['lecPass']);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error1. Please try again";
die(json_encode($response));
}
$validate_info = false;
// Fetching rows from query
$row = $stmt->fetch();
if ($row) {
if ($_POST['lecPass'] === $row['lecPass']) {
$changePass_ok = true;
}
}
if ($changePass_ok) {
// UserLogin
$response['success'] = 1;
$response['message'] = "Password changed successfully";
die(json_encode($response));
}
else {
$response["success"] = 0;
$response["message"] = "Failure";
die(json_encode($response));
}
}
?>
Appreciate if someone can guide me. Thanks.
$row = $stmt->fetch();
if ($row){
if($_POST['lecPass'] === $row['lecPass']){
$changePass_ok=true;
}
}
This isn't going to work. Doing a fetch() on an UPDATE statement is never going to return anything, because UPDATE statements don't return rows. There is nothing to compare.
You have two options:
1) Simply check that the UPDATE statement succeeded. This should really be sufficient evidence that the password was successfully updated, without having to select the row out again.
2) The lengthier way, more similar to what you're trying now is that, following the UPDATE, you run a separate SELECT statement to fetch the same row again from the database and compare the value returned against the $_POST value.
N.B. As others have pointed out in the comments, storing your passwords in plain text and transmitting them over unencrypted HTTP is incredibly insecure and asking for trouble. You should switch to HTTPS and also store the passwords in your database using a one-way hash, so that anyone with access to the DB cannot immediately steal the passwords. Then when the user logs in, you hash the password value they supply using the same algorithm, and compare that with the value in the DB in order to validate the login.

php login screen error

<?php
/*
* Following code will update a product information
* A product is identified by product id (pid)
*/
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['email']) && isset($_POST['pass'])) {
$eml = $_POST['email'];
$pass = $_POST['pass'];
$e = "$eml";
// include db connect class
// connecting to db
$db = new PDO('mysql:host=localhost;dbname=quotes;charset=utf8', 'Sidd');
// mysql update row with matched pid
$result = $db->query("SELECT * FROM user WHERE email='$e'");
// check if row inserted or not
if ($result) {
$response["success"] = 1;
$response["message"] = "Login Successful";
// while($row = $result->fetch(PDO::FETCH_ASSOC)) {
// $response["uid"] = $row["uid"];
// echoing JSON response
echo json_encode($response);
}
else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
Error
Android app always return Success=1 and login successful whether the entered Email id is right or wrong! As such whether email id exist in database or not. what am i missing? :/ .................... :(
And Also inform whether the commented code will work?!!
Please help
replace
$result = $db->query("SELECT * FROM user WHERE email='$e'");
if ($result) {....}
with
$result = $db->query("SELECT * FROM user WHERE email='$e'");
$row_count = $result->rowCount(); //number of rows with same email
if($row_count >0) {...}
PDO query method returns object. Object is always compared to true. ALWAYS.
query method can return false but only in case there is an error. But having no values that corresponds to given email is not an error.

php mysql how to use mysql_insert_id() to be able to insert into 2 table at the same time?

I am using php with mysql database to do some insert.
I have 2 tables.
user
status
where the second table has as foreign key user_id to relate between these 2 tables
my problem is that when i insert into status table the user_id field do change and take 0 no matter what is the user_id.
so how to fix this problem ???
this is the code of login.php
<?php
//array for JSON response
$response = array();
// check for required fields
if(empty($_POST['user']) || empty($_POST['password'])){
$response["success"] = 0;
$response["message"] = "enter Both Fields";
// echoing JSON response
die (json_encode($response));
}
else if (isset($_POST['user']) && isset($_POST['password']) ) {
$user = $_POST['user'];
$password = $_POST['password'];
// include db connect class
require_once '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$sql = mysql_query("Select user, password from users where user='$user'")or die(mysql_error());
$count_query = mysql_num_rows($sql);
if($count_query >0){
$response["success"] = 1;
$response["message"] = "correct Informations";
// echoing JSON response
echo json_encode($response);
}
else{
$response["success"] = 0;
$response["message"] = "Wrong User Or Pass";
// echoing JSON response
echo json_encode($response);
}
}
else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
status.php
<?php
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/
// array for JSON response
$response = array();
if(empty($_POST['status'])){
$response["success"] = 0;
$response["message"] = "You must Write something";
// echoing JSON response
die (json_encode($response));
}
// check for required fields
else if (isset($_POST['status'])) {
$status = $_POST['status'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO status(status, user_id) VALUES('$status' , '$last_insert_id')") or die(mysql_error);
$last_insert_id = mysql_insert_id();
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Your Status has been saved.";
// echoing JSON response
die (json_encode($response));
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
die (json_encode($response));
}
}
?>
i am using php with android so their is no html form
You can't. mysql_insert_id() only applies to the LAST insert performed. If you're doing two inserts, and call insert_id() after the second one, the first ID is lost.
There is no way around this.
You must have something like:
INSERT INTO foo ....
$fooid = mysql_insert_id();
INSERT INTO bar .... foo_id=$fooid
$barid = mysql_insert_id();
Given that your code actually seems to be split into multiple pages, it's even worse. mysql_insert_id() only applies to the CURRENT connection to the database. Once your first script exits, the connection is closed and the insert_id is lost.
The next script will get a NEW connection, and have its own completely separate insert_id system going.
For chaining multiple pages together like this, you'll have to retrieve/pass the insert ID around yourself, e.g.
page1:
INSERT ...
$_SESSION['page1_id'] = mysql_insert_id();
page2:
$last_id = $_SESSION['page1_id'];
INSERT ..... id=$last_id

Checking table in mysql for a name

I'm trying to implement a way to keep names, entered in an android app and sent to a server, from being used again. I figured the easiest way to do this is create another table and every time a product is added the name is added to the name table. I'm very new to php so this may seem like a very simple question but how would I go about checking the table to see if name is already on it.
here is what I go so far(most of it was already there just the commented out is my thought process)
<?php
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['name']) && isset($_POST['longitude']) && isset($_POST['latitude']) && isset($_POST['pavement']) && isset($_POST['traffic']) && isset($_POST['environment'])) {
//if(Name is not already in list of names){
$name = $_POST['name'];
$longitude = $_POST['longitude'];
$latitude = $_POST['latitude'];
$pavement = $_POST['pavement'];
$traffic = $_POST['traffic'];
$environment = $_POST['environment'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO spots(name, longitude, latitude, pavement, traffic, environment) VALUES('$name', '$longitude', '$latitude', '$pavement', '$traffic', '$environment')");
//add new name to table
//$result2 = mysql_query("INSERT INTO names(name) VALUES('$name')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Spot successfully created.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
/*
} else {
// name already taken
$response["success"] = 0;
$response["message"] = "Name has already been taken.";
// echoing JSON response
echo json_encode($response);
}
*/
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
Sorry for the simple question but thank you in advance,
Tyler
You could do a SELECT query like this:
$query = mysql_query("SELECT * FROM spots WHERE name='$name'");
$count = mysql_num_rows($query);
if($count == 0){
// name not in database
}
else{
// name is in database
}
However, this is using mysql_ functions which are deprecated. Please use mysqli_ functions instead.
Make name primary key in names table or apply unique constrain and check for duplicate key error after insertion in names table
Or you can first query table to see if name is already there or not
$result3 = mysql_query("SELECT * FROM names WHERE name='$name'");
if(mysql_num_rows($result3) <= 0 )
{
// name is not in names table
// now insert in names table
}

PHP script to check If user already exists in MySQL database

I'm creating simple game for Facebook. All users who used app are written to database. I need always check If user already exists Is in database, how to do that correctly?
So I have variable $name = $user_profile['name']; It successfully returns user's name
And this is my part of code to check If user already exists in database.
$user_profile = $facebook->api('/me');
$name = $user_profile['name'];
$mysqli = new mysqli("host","asd","pw","asdf");
echo "1";
$sql = "SELECT COUNT(*) AS num FROM myTable WHERE userName = ?";
echo "2";
if ($stmt = $mysqli->prepare($sql)) {
echo "3";
$stmt->bind_param('s', $name);
echo "4";
$stmt->execute();
echo "5";
$results = $stmt->get_result();
echo "6";
$data = mysqli_fetch_assoc($results);
echo "7";
}
if($data['num'] != 0)
{
echo "bad";
print "user already exists\n";
} else {
echo "good";
$apiResponse = $facebook->api('/me/feed', 'POST', $post_data);
print "No user in database\n";
}
}
This code not working, It should post data on user's wall If user not exists in database. I spent many time to find reason why, but unsuccessfully. After debugging It don't show any errors. To find which line is incorrect after every line I used echo "number" so now I know which line is incorrect. It prints 1 2 3 4 5 and stucks. (everything what are below the code not loading.) So that means this line $results = $stmt->get_result(); is incorrect. But I misunderstood what's wrong with this line?
If I comment this line all code loading (then print 1 2 3 4 5 6 7 No user in database! and It post data on user's wall.) but in this case program always do the same, not checking database.
Also I've tried to change COUNT(*) to COUNT(userName), but the same.
So could you help me, please?
I've read this: Best way to check for existing user in mySQL database? but It not helped me.
P.s. In this case i need to use FB username.
Can you try this, $stmt->fetch() instead of mysqli_fetch_assoc($results)
$mysqli = new mysqli("host","asd","pw","asdf");
echo "1";
/* Create the prepared statement */
$stmt = $mysqli->prepare("SELECT COUNT(*) AS num FROM myTable WHERE userName = ?") or die("Prepared Statement Error: %s\n". $mysqli->error);
/* Execute the prepared Statement */
$stmt->execute();
/* Bind results to variables */
$stmt->bind_result($name);
$data = $stmt->fetch();
if($data['num'] > 0)
{
echo "bad";
print "user already exists\n";
} else {
echo "good";
$apiResponse = $facebook->api('/me/feed', 'POST', $post_data);
print "No user in database\n";
}
/* Close the statement */
$stmt->close();
Ref: http://forum.codecall.net/topic/44392-php-5-mysqli-prepared-statements/

Categories