I am trying to open one page base on id from web address.
My address is …/customer-single.php?id=5
And my code is:
try {
$connection = new PDO($dsn, $username, $password, $options);
$CustomerID = $_GET['CustomerID'];
$sql = "SELECT * FROM tblcustomer WHERE CustomerID = :CustomerID";
$statement = $connection->prepare($sql);
$statement->bindValue(':CustomerID', $CustomerID);
$statement->execute();
$user = $statement->fetch(PDO::FETCH_ASSOC);
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
So I need to see only result from CustomerID=5.
Change the following line
$CustomerID = $_GET['CustomerID'];
into
$CustomerID = $_GET['id'];
Because you need to specify the name of the parameter you have used in the url.
$CustomerID = $_GET['CustomerID'];
change this into this
$CustomerID = $_GET['id'];
in here what you have done is trying to access a php GET variable using a unidentified reference. in get request you send your parameter like this ?id=5
but when you access it, you try to access it in a wrong way . So what should actually happen is in order to access that GET variable you should reference it correctly like I have shown above
Related
I am about to lose my mind.I dont have any php experince and I am struggling about php web service.
Here is my code;
<?php
private $username2 = "";
private $password2 = "";
private $DB_CONNECTION;
private $servername = "localhost";
private $username = "root";
private $password = "";
private $dbname = "dptest";
function __construct()
{
$this->DB_CONNECTION = mysqli_connect($this->servername, $this->username,
$this->password, $this->dbname);
}
function getUserType(){
$sql = "SELECT usertype FROM `login_test` WHERE username = '". $this->username2."'AND password = '".$this->password2."'";
$result = mysqli_query($this->DB_CONNECTION,$sql);
//$value = mysqli_fetch_array($result);
while(!is_null($value = mysqli_fetch_array($result))){
return $value['usertype'];
}
}
}
This is my function code.The other is my login code;
<?php
include_once 'Authentication.php';
use user\Authentication;
$auth = new Authentication();
$auth->prepare($_POST);
$userStatus = $auth->isUserValidToLogIn();
if ($userStatus) {
// user existed
// So log him to main page
$json['success'] = 1;
$json['message'] = 'access granted';
$json['usertype'] = $auth->getUserType();
echo json_encode($json);
} else {
$json['success'] = 0;
$json['message'] = 'error!';
echo json_encode($json);
}
I am trying to get the user's type but when try to get the data form phpmyadmin local database it only gives the first column's usertype.When I try to get 2nd,3rd,4th so on.. user's usertype it doesnt return anything and blank page shows up on postman app.
Also my database looks like this;
usertype username password
admin despro 1234
client test 1234
client despro2 1234
client despro3 1234
The reason you are only getting one column back is because you only request the one column. In order to get the columns you want you need to explicitly request them in your query or use '*' in order to get all columns back. So your query should look like this in order to get all columns from the data table:
$sql = "SELECT * FROM `login_test` WHERE username = '". $this->username2."'AND password = '".$this->password2."'";
In general, I highly recommend that you stop using MySQLi extension and start using PHP Data Objects (PDO). It makes it easy to use prepared statements. Which also makes your code safer.
Then your query could look something like this (this is NOT the complete code):
// connecting to db
$pdo = new PDO($dsn, $user, $pass, $opt);
$sql = 'SELECT *
FROM login_test
WHERE userName = :username
AND pass = :password;';
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':username', $username2, PDO::PARAM_STR);
$stmt->bindParam(':password', $password2, PDO::PARAM_STR);
$res = $stmt->execute();
if ($res) {
$response["userdata"] = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$myData = array();
$myData["usertype"] = $row["usertype"];
$myData["username"] = $row["username"];
array_push($response["userdata"], $myData);
}
}
Note that the code above is for returning multiple rows of data. If you just want the one row then use something like this:
if ($res) {
$response["userdata"] = array();
$myData = array();
$myData["usertype"] = $row["usertype"];
$myData["username"] = $row["username"];
array_push($response["userdata"], $myData);
}
removing the 'while' statement.
You might want to take a look at this answer I gave, recently. It is a comprehensive example of using a webservice from an Android app.
How to insert all the SQL table data into an array in java [android studio]
Why is this not working:
function listOrderComments ($factnr){
global $connection;
//$factnr = 123; //or $factnr = "123"; (Both work)
$query = "SELECT * FROM orderstatus WHERE factuurnummer = '$factnr'";
$result = mysqli_query($connection, $query);
When I echo $factnr I get "123" back.
When I uncommented //$factnr = 123; my function is working.
Looked everywhere for a solution. check the type $factnr is (string).
Well if you're using a variable in your query you're opening yourself up to an injection attack for one.
If you're going to be using that variable I would recommend you use bind_param for your query
Read the PHP manual link below and you will be able to figure out the issue
http://php.net/manual/en/mysqli-stmt.bind-param.php
If you're passing in a variable to your function it should already be set so I don't understand why you're setting it to 123 anyway. So execute the sql statement and bind the parameter following the first example on the PHP docs page.
public function listOrderComments ($factnr)
{
global $connection;
$query = "SELECT * FROM orderstatus WHERE factuurnummer = ?";
$sql->prepare($query);
$sql->bind_param("s", $factnr);
$sql->execute();
$result = $sql->get_result();
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
foreach ($data as $row) {
print_r($row);
}
}
Then do what you want with the result
You can go with:
$query = "SELECT * FROM orderstatus WHERE factuurnummer = ". $factnr;
Concatenating your code is not good practise. Your best solution is to use PDO statements. It means that your code is easier to look at and this prevents SQL injection from occuring if malice code slipped through your validation.
Here is an example of the code you would use.
<?php
// START ESTABLISHING CONNECTION...
$dsn = 'mysql:host=host_name_here;dbname=db_name_here';
//DB username
$uname = 'username_here';
//DB password
$pass = 'password_here';
try
{
$db = new PDO($dsn, $uname, $pass);
$db->setAttribute(PDO::ERRMODE_SILENT, PDO::ATTR_EMULATE_PREPARES);
error_reporting(0);
} catch (PDOException $ex)
{
echo "Database error:" . $ex->getMessage();
}
// END ESTABLISHING CONNECTION - CONNECTION IS MADE.
$factnr = "123" // or where-ever you get your input from.
$query = "SELECT * FROM orderstatus WHERE factuurnummer = :factnr";
$statement = $db->prepare($query);
// The values you wish to put in.
$statementInputs = array("factnr" => $factnr);
$statement->execute($statementInputs);
//Returns results as an associative array.
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
$statement->closeCursor();
//Shows array of results.
print_r($result);
?>
Use it correctly over "doted" concat. Following will just work fine:
$factnr = 123;
$query = "SELECT * FROM orderstatus WHERE factuurnummer = " . $factnr;
UPDATE:
here is $factnr is passing as argument that supposed to be integer. Safe code way is DO NOT use havvy functions even going over more complicated PDO, but just verify, is this variable integer or not before any operation with it, and return some error code by function if not integer. Here is no danger of code injection into SQL query then.
function listOrderComments ($factnr){
global $connection;
if (!is_int($factnr)) return -1
//$factnr = 123; //or $factnr = "123"; (Both work)
$query = "SELECT * FROM orderstatus WHERE factuurnummer = " . $factnr;
$result = mysqli_query($connection, $query);
try {
$conn = new PDO('mysql:host=localhost;dbname=dbtable', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$data = $conn->prepare('SELECT * FROM table WHERE name = ' . $conn->quote($name).' AND id = '. $conn->quote($id));
$data->execute();
while($row = $data->fetch(PDO::FETCH_ASSOC)) {
echo "ID : ".$row['id'].'</br>';
echo "Name : ".$row['name'].'</br>';
echo "Name : ".$row['header'].'</br>';
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
The above works for one parameter (name) but when i use AND operator it shows no results. URL is as given below.
http://www.mywebsite.com/page.php?id=2&name=xyz
As mentioned in the documentation, you're strongly advised to use parametrized queries, like so:
$data = $conn->prepare('SELECT * FROM table WHERE name = :name AND id = :id');
$data->bindParam(":name", $name);
$data->bindParam(":id", $id);
If this still does not work, I would suggest running a similar query directly against your database, through either phpMyAdmin or the MySQL Workbench, to verify that the query actually returns anything.
$data = $conn->prepare("SELECT * FROM table WHERE name = '$name' AND id <> '$id' ");
The above code worked for me.
I'm using $_POST to data to my php page to update the mysql database. I'm trying to use the customer id to pick the row and update the company name and fname(firstname). When I figure this out, I'll add the rest to be updated. I've also included what I've tried via the "//" Thank you
-----dbconnect-----
$id= $_POST['id'];
$company= $_POST['company'];
$fname = $_POST['fname'];
echo $id;
echo $company;
echo $fname;
//$sql = mysqli_query($con,"UPDATE customer SET company = $company WHERE id= '.$id.'")
//$sql = "UPDATE customer SET company ='".mysql_real_escape_string($_POST['company'])."WHERE id='".mysql_real_escape_string($_POST['id'])."'";
$sql = "UPDATE customer SET company = $company WHERE id= '1'";
mysqli_select_db('customer');
$retval = mysqli_query( $sql, $con );
if(! $retval )
{
die('Could not update data: ' . mysqli_error());
}
echo "Updated data successfully\n";
mysqli_close($conn);
}
Making a few assumptions here but try this out...
// make mysqli throw exceptions on error
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// assuming your connection looks something like this
// you can pass the database name as the fourth argument instead of using select_db()
$con = new mysqli('localhost', 'user', 'pass', 'customer');
// $id = $_POST['id'], etc
// use a prepared statement with parameter placeholders.
// for more info see http://php.net/manual/mysqli.quickstart.prepared-statements.php
$stmt = $con->prepare('UPDATE customer SET company = ? WHERE id = ?');
// bind parameter variables and execute
$stmt->bind_param('si', $company, $id);
$stmt->execute();
echo 'Updated data successfully', PHP_EOL;
got the following code. All values are gotten through javascript and then sent through ajax. The var_dump($array) at the end works and display all the correct values. So they are all passed through correctly. The catch error for the try method also never pops up. The values are not being inserted into the sql table. Whats wrong?
Thanks in advance.
$name = $_GET['name'];
$category = $_GET['category'];
$subCategory = $_GET['subCategory'];
$date = $_GET['date'];
$address = $_GET['address'];
$city = $_GET['city'];
$state = $_GET['state'];
$host = $_GET['host'];
$imagePath = $_GET['imagePath'];
$info = $_GET['info'];
//turn into array
$array = array();
$array[0]=$name;
$array[1]=$category;
$array[2]=$subCategory;
$array[3]=$date;
$array[4]=$address;
$array[5]=$city;
$array[6]=$state;
$array[7]=$host;
$array[8]='j';//$imagePath;
$array[9]=$info;
try {
$con = new PDO('mysql:host=localhost;dbname=test');
$insert = $con->prepare(" INSERT INTO create
(name,category,subCategory,date,address,city,state,host,imagePath,info)
VALUES (?,?,?,?,?,?,?,?,?,?) ");
$insert->execute($array);
}
catch(PDOException $e) { //try
echo 'error';
//echo 'ERROR: ' . $e->getMessage();
}
var_dump($array);
create is a reserved word in mysql so you need to quote it in backticks:
INSERT INTO `create` ...
To have PDO throw exceptions, you need to add that after you open your connection:
$con = new PDO('mysql:host=localhost;dbname=test');
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
By the way, I assume that you are logging into your database with a username and a password as well (the second and third parameter of the PDO constructor)...