Get all data after linking to other page using $_GET - php

I'am very glad to haveall of u programmers. I need your help for my code. Below is my code:
-survey.php
<td><center></b><font size="2">Not Complete</center></td></tr>';
While this is the page after I clink link where it GET the user_id.
-page.php
$staffid = (int)$_GET['user_id'];
In page.php, I only get user_id data only. My question is how do I want to get all data from $_GET['user_id'], such as their email, address, etc.
Any help would be much appreciated. Thank you.

In the page you want all the data, page.php, you need to run something like this (In this case a PDO prepared statement, you can do that with mysqli, too):
try {
$connection = new PDO('mysql:host=' . HOST . ';dbname=' . DB , USER_DB, PASS_DB); // replace with your credentials!
$state = $connection->prepare("SELECT * FROM usertable WHERE user_id = :id");
$state->execute(array('id' => $_GET['user_id']));
if ($state->rowCount() > 0) {
list ($username,$email /* catch all the fields you need ,*/ )=$state->fetch(PDO::FETCH_NUM);
}
else {
echo "Nothing found"; }
$state->closeCursor();
unset($state, $connection);
} catch (PDOException $e) {
die('Error!: ' . $e->getMessage() . '<br/>');
}
SIDENOTE:
There seems to be an error in your first line you posted here:
<td><center></b><font size="2">Not Complete</center></td></tr>';
^where does this come from?

passing the id alone cannot get all the fields you want. Instead create a query where you insert the staff id to get the fields you want
$staffid = (int)$_GET['user_id'];
SELECT * FROM users WHERE id= '".$staffid."'
And Run the query.

Related

Putting MySQL data from database into a variable

I'm making a luck based website and I want to make sure they have enough spins on their account before they spin.
I did see http://www.w3schools.com/php/php_mysql_select.asp but its not really what I'm looking for.
I have these rows with the names: id username email password spins.
I can deduct amounts from spins but I can't put the exact amount of their spins on a PHP variable to put in a $SESSION for a different page.
Here's how much I have so far.
$numSpin = "SELECT * FROM $tbl_name WHERE spins";
Then put it in a $SESSION
$_SESSION['spinNum'] = $numSpin;
How would I go on to doing this? This does not work as is.
It seems as if you are extremely new to coding so I'll try to help you out.
Here is the code you can use and I'll explain below.
<?php
session_start();
$host = 'localhost'; $db = 'db-name'; $user = 'db-user'; $pw = 'db-pwd';
$conn = new PDO('mysql:host='.$host.';dbname='.$db.';charset=utf8', $user, $pw);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$tbl_name = 'table-name-here';
$un = $username;
$sql = "SELECT * FROM $tbl_name WHERE username=:un";
$query = $conn->prepare($sql);
$query->bindValue(':un', $un, PDO::PARAM_STR);
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC);
$totalRows = $query->rowCount();
} catch (PDOException $e) {
die("Could not get the data: " . $e->getMessage());
}
$_SESSION['spinNum'] = $row['name-of-your-field-with-spin-numbers'];
?>
Then...
if($_SESSION['spinNum'] >= 1) {
// allow them to do something
} else {
echo "I'm sorry. It looks like you don't have any spins left. Please try again later.";
}
This code is written using pdo_mysql. You might want to read up on it here.
Line 2 starts your session
Lines 3-5 creates a connection to your database. Make sure to replace "db-name", "db-user" & "db-pwd" with your information.
On line 8 replace "table-name-here" with your database table name
On line 9 you can set "10" to whatever minimum number you want to make sure the account holder has.
On line 19 change "name-of-your-field-with-spin-numbers" to the actual name of the field in your database table that stores the account users available spins.
Now you can use $_SESSION['spinNum'] on your other pages.
Don't forget to use session_start(); at the top of any page where you want to use session variables.

Make dynamic sql to get data from session array

I am using PDO. I want to make a sql statement which gives the user_id of that user which name is in session array. When I get the data from session array in variable and write it in sql it gives nothing but when I write "jhon" it gives user_id that I required. But I want to dynamic sql prepare statement. I see some solution from net but I can't figure it out.
session_start();
if(isset($_SESSION["username"])){
$name=$_SESSION["username"];
function add_posts(){
if($posts_text != ""){
try {
$conn=parent::connect();
$sql1=$conn->prepare("select user_id from user_login
where username=:username ");
$arr=array ('username'=>$name );//when i write "jhon" it gives id 14,
// when i write $name it gives nothing
$sql1->execute($arr);
$fetch = $sql1->fetch();
echo $fetch['user_id'];
}
catch (PDOException $e){
die ("connection failed" .$e->getMessage() );
}
}
}
You need you pass $name argument in your function
function add_posts($name) {

PHP PDO mySQL query returns column name instead of value [duplicate]

This question already has an answer here:
Can I use a PDO prepared statement to bind an identifier (a table or field name) or a syntax keyword?
(1 answer)
Closed 7 years ago.
I'm setting up a web application that has multiple user roles that determine what view a specific user gets when visiting specific sections (or whether those sections are even available to them). I have a table ("users") that includes a columns for "username" and "role". I have a second table ("roles") that has columns for "role" as well as a column for each section, each having multiple possible values that drive the user experience for each role. The column I'm concerned with here is call "useradminview", but I have the same issue with all other columns.
I have no problem obtaining a given user's role when they login. But when I attempt to get the useradmin view associated with that role, my query returns the column name rather than the expected value.
I've found several posts on stackoverflow and other sites that are for the same symptom, but the queries are setup differently from what I have. Any help is greatly appreciated!
//function to get role for user - this returns the expected value
function getUserRole($username) {
include($_SERVER["DOCUMENT_ROOT"] . "/sharedinc/db.php");
try {
$sql = "SELECT role FROM users WHERE username = :username";
$s = $pdoUsers->prepare($sql);
$s->bindValue(":username", $username);
$s->execute();
} catch (PDOException $e) {
$error = "Error obtaining user role";
include($_SERVER["DOCUMENT_ROOT"] . "/sharedinc/dboutput.php");
exit();
}
$role = $s->fetch();
return $role[0];
}
//function to check page view for that role - this returns the column name
function getPageView($role, $page) {
include($_SERVER["DOCUMENT_ROOT"] . "/sharedinc/db.php");
try {
$sql = "SELECT :page FROM roles WHERE role = :role";
$s = $pdoUsers->prepare($sql);
$s->bindValue(":role", $role);
$s->bindValue(":page", $page);
$s->execute();
} catch (PDOException $e) {
$error = "Error obtaining pageview for role";
include($_SERVER["DOCUMENT_ROOT"] . "/sharedinc/dboutput.php");
exit();
}
$pageview = $s->fetch();
return $pageview[0];
}
//end-goal query needs to be able to store the values as session variables
$_SESSION["username"] = $_POST["username"];
$_SESSION["role"] = getUserRole($_SESSION["username"]);
$_SESSION["useradminview"] = getPageView($_SESSION["role"], "useradminview");
you cant put row-name via bind. change it to:
try {
$sql = "SELECT $page FROM roles WHERE role = :role";
$s = $pdoUsers->prepare($sql);
$s->bindValue(":role", $role);
$s->execute();
} catch (PDOException $e) {

PHP and MySQL using the PDO class

I am trying to update a database, here is my code
if (isset($_GET['placeorder']))
{
include 'includes/db.php';
try
{
$newBalance = $_POST['balance'] + $_POST['oldbalance'];
$sql = 'UPDATE customer SET
balance = :balance
WHERE id = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':balance', $newBalance);
$s->execute();
}
catch (PDOException $e)
{
$error = 'Could not add the new balance for the customer' . $e->getMessage();
include 'result.php';
exit();
}
header('Location: .');
exit();
What I am trying to do is update the balance for a customer that is coming from a form that was submitted. I am able to get the value in the code all the way up to where I get to $s->execute(); if I try to echo the value, which is $newBalance, it will not show after that line is executed, the page goes blank. Something is happening in the execute statement. $s->execute() that it does not allow my code to proceed. Any idea? Am I using the PDO class the wrong way. It is not getting to the "catch" statement. Any help would be great. The end result is that the page returns to where it started with the updated balance.
You are only binding a value to the balance, not the id, you need a line like:
$s->bindValue(':id', $id);
It would be a good idea to make sure that $_POST['balance'] and $_POST['oldbalance'] are set as well before using them in your query:
$balance = isset($_POST['balance'])? $_POST['balance'] : 0;
$oldbalance = isset($_POST['oldbalance'])? $_POST['oldbalance'] : 0;
$newbalance = $balance + $oldbalance;
If you aren't getting an error, you likely don't have error reporting on, you can enable it by adding error_reporting(E_ALL); to the top of your page.
var_dump() both variables $_POST['balance'] & $_POST['oldbalance']. I am sure they are coming as string. Type casting is one of the solution. Try typecasting in this case to perform addition on int/float.
$newBalance = (int)$_POST['balance'] + (int)$_POST['oldbalance'];

Duplicate check before adding into database

I have a code which kinda works, but not really i can't figure out why, what im trying to do is check inside the database if the URL is already there, if it is let the user know, if its not the go ahead and add it.
The code also makes sure that the field is not empty. However it seems like it checks to see if the url is already there, but if its not adding to the database anymore. Also the duplicate check seems like sometimes it works sometimes it doesn't so its kinda buggy. Any pointers would be great. Thank you.
if(isset($_GET['site_url']) ){
$url= $_GET['site_url'];
$dupe = mysql_query("SELECT * FROM $tbl_name WHERE URL='$url'");
$num_rows = mysql_num_rows($dupe);
if ($num_rows) {
echo 'Error! Already on our database!';
}
else {
$insertSite_sql = "INSERT INTO $tbl_name (URL) VALUES('$url')";
echo $url;
echo ' added to the database!';
}
}
else {
echo 'Error! Please fill all fileds!';
}
Instead of checking on the PHP side, you should make the field in MySQL UNIQUE. This way there is uniqueness checking on the database level (which will probably be much more efficient).
ALTER TABLE tbl ADD UNIQUE(URL);
Take note here that when a duplicate is INSERTed MySQL will complain. You should listen for errors returned by MySQL. With your current functions you should check if mysql_query() returns false and examine mysql_error(). However, you should really be using PDO. That way you can do:
try {
$db = new PDO('mysql:host=localhost;db=dbname', $user, $pass);
$stmt = $db->query('INSERT INTO tbl (URL) VALUES (:url)');
$stmt->execute(array(':url' => $url));
} catch (PDOException $e) {
if($e->getCode() == 1169) { //This is the code for a duplicate
// Handle duplicate
echo 'Error! Already in our database!';
}
}
Also, it is very important that you have a PRIMARY KEY in your table. You should really add one. There are a lot of reasons for it. You could do that with:
ALTER TABLE tbl ADD Id INT;
ALTER TABLE tbl ADD PRIMARY KEY(Id);
You should take PhpMyCoder's advice on the UNIQUE field type.
Also, you're not printing any errors.
Make sure you have or die (mysql_error()); at the end of your mysql_* function(s) to print errors.
You also shouldn't even be using mysql_* functions. Take a look at PDO or MySQLi instead.
You're also not executing the insert query...
Try this code:
if(isset($_GET['site_url']) ){
$url= $_GET['site_url'];
$dupe = mysql_query("SELECT * FROM $tbl_name WHERE URL='$url'") or die (mysql_error());
$num_rows = mysql_num_rows($dupe);
if ($num_rows > 0) {
echo 'Error! Already on our database!';
}
else {
$insertSite_sql = "INSERT INTO $tbl_name (URL) VALUES('$url')";
mysql_query($insertSite_sql) or die (mysql_error());
echo $url;
echo ' added to the database!';
}
}
else {
echo 'Error! Please fill all fileds!';
}
As PhpMyCoder said, you should add a unique index to the table.
To add to his answer, here is how you can do what you want to do with only one query.
After you add the unique index, if you try to "INSERT INTO" and it result in a duplicate, MySQL will produce an error.
You can use mysql_errno() to find out if there was a duplicate entry and tell the user.
e.g.
$sql = "INSERT INTO $tbl_name (URL) VALUES('$url')";
$result = mysql_query($sql);
if($result === false) {
if(mysql_errno() == $duplicate_key_error) {
echo 'Error! Already in our database!';
} else {
echo 'An error has occurred. MySQL said: ' . mysql_error();
}
}
mysql_error() will return the mysql error in plain english.
mysql_errno() returns just the numeric error code. So set $duplicate_key_error to whatever the code is (I don't know it off the top of my head) and you are all set.
Also note that you don't want to print any specific system errors to users in production. You don't want hackers to get all kinds of information about your server. You would only be printing MySQL errors in testing or in non-public programs.
ALSO! Important, the mysql functions are deprecated. If you go to any of their pages ( e.g. http://php.net/manual/en/function.mysql-errno.php) you will see recommendations for better alternatives. You would probably want to use PDO.
Anyone who wants to edit my answer to change mysql to PDO or add the PDO version, go ahead.

Categories