I am trying to use WordPress logged in user id which should search transaction_user_ID in the table wp_m_subscription_transaction.
The table has a column called transaction_user_ID and another called transaction_paypal_ID.
logic:if user id == transaction user id then get transaction paypal id
which should be passed to the url along with the user id email address
and the execute the url to get the a code - this is my final output
How this can be achieved?
The code which I am developing is like this which is obviously incomplete & error for the getting and using the database query
<?php $user_id = get_current_user_id();
$query = "SELECT * FROM $wpdb->;wp_m_subscription_transaction
if ($user_id ==$query) {
Get ur Code
}
else {
echo 'You are not logged in as user ';}?>
First, since you need the email address as well, get all the current user's details, not just the id, using wp_get_current_user().
Secondly, your query is wrong; you haven't closed the quotes, and have a stray semicolon. If I've read it right, you need something like:
select transaction_paypal_ID
from wp_m_subscription_transaction
where transaction_user_ID = [the user's ID]
If you're only getting a single value in a query, you can retrieve it with $wpdb->get_var()
If the query doesn't return a row, it doesn't necessarily mean the user isn't logged in. You can check if a user is logged in using is_user_logged_in().
Something like this should work. I haven't tested, and you'll have to build up the URL yourself.
<?php
if (is_user_logged_in()) {
$user = wp_get_current_user();
$paypal_id = $wpdb->get_var("select transaction_paypal_ID from wp_m_subscription_transaction where transaction_user_ID = " . (int) $user->ID);
if ($paypal_id) {
// Build up your URL here, with $paypal_id and $user->user_email
}
else {
echo 'No transaction found for the current user';
}
}
else {
echo 'You are not logged in';
}
?>
Try this query.
$query = "SELECT transaction_paypal_ID FROM wp_m_subscription_transaction where transaction_user_ID = ".$user_id;
$result = $wpdb->get_row($wpdb->prepare($query), ARRAY_A);
$transaction_paypal_ID = $result['transaction_paypal_ID'];
This code comes without warrant, because you've not provided database structure, field names, or many other factors.
However, treated as pseudo-code, this will get you going in the right direction.
$user_id = get_current_user_id();
// Global / bring in $wpdb, and the $table_prefix variables
global $wpdb, $table_prefix;
// Use $wpdb prepare to be sure the query is properly escaped
$query = $wpdb->prepare("SELECT * FROM " . $table_prefix . "m_subscription_transaction WHERE user_id = %d", $user_id);
// Turn on error reporting, so you can see if there's an issue with the query
$wpdb->show_errors();
// Execute the query
$results = $wpdb->get_results($query);
// Are there any records? If so, that means the user ID matched
if ($results) {
$row = $results[0];
// Get the data from the row
echo 'Get ur Code';
} else {
echo 'No records for this user.';
}
Related
The following code works well when the correct URL is used like...
http://example.com/user.php?id=joe
Where I need help is where do I add an if statement and how should it be written to provide either a default landing page or better, an input field so the visitor can retype the user name and submit it to have the correct page load.
<?php
$pdo = new PDO('mysql:host=localhost;dbname=users', 'root', '');
// retrieve member's data
$ps = $pdo->prepare("SELECT * FROM members WHERE id = ?");
if(isset($_GET["id"])) {
$ps->execute(array($_GET["id"]));
}
$result = $ps->fetch(PDO::FETCH_ASSOC);
extract($result);
echo $First_Name . ' - ' . $Email;
Any help?
if(!empty($_GET['id'])) {
// YOUR PREVIOUS CODE HERE
} else {
// REDIRECT CODE HERE
}
I assume you'd want to wrap all the code with the if statement so it doesn't run unless an id is present.
<?php
if( isset( $_GET['id'] ) ) {
//retrieve member data here and render normal page
}
else {
//render landing page
}
?>
It might be wise to put the code for rendering the two different pages into different functions to help with organization as well.
First off, just wanted to say I'm a novice at this type of coding, although I'm hopeful that I'll eventually make sense of it all with a little guidance.
I have a MySQL database table (promotion) that stores a bunch of redemption codes for various products (for a give away contest). The idea is, the first person to enter the redemption code wins the product, and their info should be stored in the "promotion" table.
The table's columns are: redeem_id (Auto Increment field), redeem_code, redeemer_email, redeemer_first_name, redeemer_last_name, and redeem_date_time.
Initially, the redeem_id and redeem_code fields are the only ones with any data. What I'd like to happen is when a user enters their information (name, email, etc) and submit a redemption code, their info will populate the rest of the row for that particular code. If anyone else tries to submit a code that has already been redeemed, they should receive an error message - likewise for an invalid code (i.e. a code that does not exist in the table).
The PHP code I have so far is:
<?php
function get_promotion_by_redeem_code($redeem_code)
{
$sql = "SELECT * FROM promotion WHERE redeem_code= '".mysql_real_escape_string($redeem_code)."'";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
return $row;
}
function redeem_promotion($email,$first_name,$last_name,$redeem_date_time,$redeem_code)
{
$query = 'UPDATE promotion
SET redeemer_email=".mysql_real_escape_string($email).", redeemer_first_name=".mysql_real_escape_string($first_name).", redeemer_last_name=".mysql_real_escape_string($last_name).", redeem_date_time=NOW(), WHERE redeem_code=".mysql_real_escape_string($redeem_code)."';
$insert = mysql_query($query);
return $insert;
}
$email=$_POST['e_mail'];
$first_name=$_POST['f_name'];
$last_name=$_POST['l_name'];
$redeem_code=$_POST['v_code'];
$connection = mysql_connect('localhost', 'db', 'pw');
mysql_select_db('db', $connection);
$promotion = get_promotion_by_redeem_code($redeem_code);
if ($promotion) {
if (!$promotion['redeemer_email']) {
redeem_promotion($email,$first_name,$last_name,$redeem_date_time,$redeem_code);
echo 'Congratulations, you have successfully claimed this item!';
} else {
echo 'Sorry, this item has already been redeemed.';
}
} else {
echo 'Sorry, you have entered an incorrect claim code. Please use your browser\'s back button to try again.';
}
mysql_close($connection);
?>
It works as expected when I enter an invalid claim code, or if a code's row has been previously populated.
When it doesn't work, is when someone goes to redeem the item for the first time. Essentially, it will show the "Congratulations" message, however the table doesn't get updated for the submitted information. Therefore, no matter how many times the correct code is entered, the user will receive the "Congratulations" message.
I'm fairly certain that the error is in the redeem_promotion() function, but I can't figure out where.
You have add an extra comma(,) before WHERE clause. Thats the mistake, i think.
function redeem_promotion($email,$first_name,$last_name,$redeem_date_time,$redeem_code)
{
$query = 'UPDATE promotion
SET redeemer_email=".mysql_real_escape_string($email).",
redeemer_first_name=".mysql_real_escape_string($first_name).",
redeemer_last_name=".mysql_real_escape_string($last_name).",
redeem_date_time=NOW()
WHERE redeem_code=".mysql_real_escape_string($redeem_code)."';
**OR**
$query = "UPDATE promotion
SET redeemer_email='".mysql_real_escape_string($email)."',
redeemer_first_name='".mysql_real_escape_string($first_name)."',
redeemer_last_name='".mysql_real_escape_string($last_name)."',
redeem_date_time=NOW()
WHERE redeem_code='".mysql_real_escape_string($redeem_code)."'";
$insert = mysql_query($query);
return $insert;
}
There are not really and direct answers on this, so I thought i'd give it a go.
$myid = $_POST['id'];
//Select the post from the database according to the id.
$query = mysql_query("SELECT * FROM repairs WHERE id = " .$myid . " AND name = '' AND email = '' AND address1 = '' AND postcode = '';") or die(header('Location: 404.php'));
The above code is supposed to set the variable $myid as the posted content of id, the variable is then used in an SQL WHERE clause to fetch data from a database according to the submitted id. Forgetting the potential SQL injects (I will fix them later) why exactly does this not work?
Okay here is the full code from my test of it:
<?php
//This includes the variables, adjusted within the 'config.php file' and the functions from the 'functions.php' - the config variables are adjusted prior to anything else.
require('configs/config.php');
require('configs/functions.php');
//Check to see if the form has been submited, if it has we continue with the script.
if(isset($_POST['confirmation']) and $_POST['confirmation']=='true')
{
//Slashes are removed, depending on configuration.
if(get_magic_quotes_gpc())
{
$_POST['model'] = stripslashes($_POST['model']);
$_POST['problem'] = stripslashes($_POST['problem']);
$_POST['info'] = stripslashes($_POST['info']);
}
//Create the future ID of the post - obviously this will create and give the id of the post, it is generated in numerical order.
$maxid = mysql_fetch_array(mysql_query('select max(id) as id from repairs'));
$id = intval($maxid['id'])+1;
//Here the variables are protected using PHP and the input fields are also limited, where applicable.
$model = mysql_escape_string(substr($_POST['model'],0,9));
$problem = mysql_escape_string(substr($_POST['problem'],0,255));
$info = mysql_escape_string(substr($_POST['info'],0,6000));
//The post information is submitted into the database, the admin is then forwarded to the page for the new post. Else a warning is displayed and the admin is forwarded back to the new post page.
if(mysql_query("insert into repairs (id, model, problem, info) values ('$_POST[id]', '$_POST[model]', '$_POST[version]', '$_POST[info]')"))
{
?>
<?php
$myid = $_POST['id'];
//Select the post from the database according to the id.
$query = mysql_query("SELECT * FROM repairs WHERE id=" .$myid . " AND name = '' AND email = '' AND address1 = '' AND postcode = '';") or die(header('Location: 404.php'));
//This re-directs to an error page the user preventing them from viewing the page if there are no rows with data equal to the query.
if( mysql_num_rows($query) < 1 )
{
header('Location: 404.php');
exit;
}
//Assign variable names to each column in the database.
while($row = mysql_fetch_array($query))
{
$model = $row['model'];
$problem = $row['problem'];
}
//Select the post from the database according to the id.
$query2 = mysql_query('SELECT * FROM devices WHERE version = "'.$model.'" AND issue = "'.$problem.'";') or die(header('Location: 404.php'));
//This re-directs to an error page the user preventing them from viewing the page if there are no rows with data equal to the query.
if( mysql_num_rows($query2) < 1 )
{
header('Location: 404.php');
exit;
}
//Assign variable names to each column in the database.
while($row2 = mysql_fetch_array($query2))
{
$price = $row2['price'];
$device = $row2['device'];
$image = $row2['image'];
}
?>
<?php echo $id; ?>
<?php echo $model; ?>
<?php echo $problem; ?>
<?php echo $price; ?>
<?php echo $device; ?>
<?php echo $image; ?>
<?
}
else
{
echo '<meta http-equiv="refresh" content="2; URL=iphone.php"><div id="confirms" style="text-align:center;">Oops! An error occurred while submitting the post! Try again…</div></br>';
}
}
?>
What data type is id in your table? You maybe need to surround it in single quotes.
$query = msql_query("SELECT * FROM repairs WHERE id = '$myid' AND...")
Edit: Also you do not need to use concatenation with a double-quoted string.
Check the value of $myid and the entire dynamically created SQL string to make sure it contains what you think it contains.
It's likely that your problem arises from the use of empty-string comparisons for columns that probably contain NULL values. Try name IS NULL and so on for all the empty strings.
The only reason $myid would be empty, is if it's not being sent by the browser. Make sure your form action is set to POST. You can verify there are values in $_POST with the following:
print_r($_POST);
And, echo out your query to make sure it's what you expect it to be. Try running it manually via PHPMyAdmin or MySQL Workbench.
Using $something = mysql_real_escape_string($POST['something']);
Does not only prevent SQL-injection, it also prevents syntax errors due to people entering data like:
name = O'Reilly <<-- query will bomb with an error
memo = Chairman said: "welcome"
etc.
So in order to have a valid and working application it really is indispensible.
The argument of "I'll fix it later" has a few logical flaws:
It is slower to fix stuff later, you will spend more time overall because you need to revisit old code.
You will get unneeded bug reports in testing due to the functional errors mentioned above.
I'll do it later thingies tend to never happen.
Security is not optional, it is essential.
What happens if you get fulled off the project and someone else has to take over, (s)he will not know about your outstanding issues.
If you do something, finish it, don't leave al sorts of issues outstanding.
If I were your boss and did a code review on that code, you would be fired on the spot.
I want to display the attributes of the game character, which is under the users TABLE. So, I want it to display the specific attributes of the user who has logged in, since it should be in his row. Do I need to register my users with session, because I didn't.
This is the code I used to get the sessions for the user in when login in
<?
if(isset($_POST['Login'])) {
if (ereg('[^A-Za-z0-9]', $_POST['name'])) {// before we fetch anything from the database we want to see if the user name is in the correct format.
echo "Invalid Username.";
}else{
$query = "SELECT password,id,login_ip FROM users WHERE name='".mysql_real_escape_string($_POST['Username'])."'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result); // Search the database and get the password, id, and login ip that belongs to the name in the username field.
if(empty($row['id'])){
// check if the id exist and it isn't blank.
echo "Account doesn't exist.";
}else{
if(md5($_POST['password']) != $row['password']){
// if the account does exist this is matching the password with the password typed in the password field. notice to read the md5 hash we need to use the md5 function.
echo "Your password is incorrect.";
}else{
if(empty($row['login_ip'])){ // checks to see if the login ip has an ip already
$row['login_ip'] = $_SERVER['REMOTE_ADDR'];
}else{
$ip_information = explode("-", $row['login_ip']); // if the ip is different from the ip that is on the database it will store it
if (in_array($_SERVER['REMOTE_ADDR'], $ip_information)) {
$row['login_ip'] = $row['login_ip'];
}else{
$row['login_ip'] = $row['login_ip']."-".$_SERVER['REMOTE_ADDR'];
}
}
$_SESSION['user_id'] = $row['id'];// this line of code is very important. This saves the user id in the php session so we can use it in the game to display information to the user.
$result = mysql_query("UPDATE users SET userip='".mysql_real_escape_string($_SERVER['REMOTE_ADDR'])."',login_ip='".mysql_real_escape_string($row['login_ip'])."' WHERE id='".mysql_real_escape_string($_SESSION['user_id'])."'")
or die(mysql_error());
// to test that the session saves well we are using the sessions id update the database with the ip information we have received.
header("Location: play.php"); // this header redirects me to the Sample.php i made earlier
}
}
}
}
?>
you need to find which user you are logged in as. How do you log in to your system? You have several options which you can try out:
use sessions (save the userID in the session, and add that to the query using something like where id = {$id}
Get your userid from your log-in code. So the same code that checks if a user is logged in, can return a userid.
Your current code shows how you log In, and this works? Then you should be able to use your session in the code you had up before.
Just as an example, you need to check this, and understand the other code. It feels A bit like you don't really understand the code you've posted, so it's hard to show everything, but it should be something like this.
<?php
session_start();
$id = $_SESSION['user_id'];
//you need to do some checking of this ID! sanitize here!
$result = mysql_query("SELECT * FROM users" where id = {$id}) or die(mysql_error());
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
}
I want my php query to display the user name with a link to the user profile.
<?php
$get_items = "SELECT * FROM items WHERE category='test'";
$result = mysql_query($get_items);
while($item = mysql_fetch_array($result, MYSQL_ASSOC)){
$creator = $item['created_by'];
echo "<b>Seller: </b>"."<a href='userprof.php?id=$creator'>$creator</a>";
}
?>
Clicking on this link takes it to a user profile page that I created. But I want "userprof.php?id=$creator" to know which user to display the account information. Is this the best way to do this? How can I read the url and display the correct information?
<?php
$userId = $_GET['id'];
$sql = "SELECT * FROM user WHERE id = " . intval($userId);
$result = mysql_query($sql);
...
You are sending a GET variable.
$id = $_GET['id']; // Contains whatever was in $creator;
use $_GET for getting the variable from the URL.
like in your code you want to access the user profile then get the user id from url
like
http://localhost/test/user_profile.php?uid=2
here in the url uid is 2 thet is your userid.
you can get this id by using the code
$user_id = $_GET['uid'];
use this variable in your query.
OMG!! HORRIBLE PHP ABOUNDS! IT HURTS MY EYES!!
These people, none of them did both of the correct things:
ALWAYS FILTER USER INPUT!!
NEVER TRUST PHP ESCAPE FUNCTIONS, ESP NOT intval() and addslashes()!!
EVEN mysql_real_escape_string() HAS VULNERABILITIES AND SHOULD NEVER BE USED.
You should used prepared statements for everything in 2010.
Here it is the proper way:
<?php
if (!filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT))
{
trigger_error('Invalid User ID. It must be an integer (number).', PHP_USER_ERROR);
exit;
}
$userId = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
$sql = "SELECT * FROM user WHERE id = ?";
$pdo = new PDO('mysql:host=localhost;db=mydb', $dbUsername, $dbPassWord);
$statement = $pdo->prepare($sql);
$statement->execute(array($userId));
$result = $statement->fetch(PDO::FETCH_ASSOC);
That is 100% secure. I hope people neither vote me down nor tone down my answer. Bad code is so systemic, we just have to shout from the rooftops until the new guys start learning it correctly, otherwise PHP as a professional language is seriously harmed.