Why doesn't my variable work in my SELECT statement [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
session_start();
$username = $_SESSION['username'];
$db = new PDO("mysql:host=".DBHOST.";charset=utf8mb4;dbname=".DBNAME,
DBUSER, DBPASS);
function keygrabber($username) { //You need to pass a variable into this
function
global $db; //Gain access to the $db variable, which is out of scope due to
being inside of a function
$stmt = $db->prepare("SELECT * FROM keys WHERE username='$username'");
//Prepare the query
$stmt->execute(); //Execute the query
$results = $stmt->fetchAll(PDO::FETCH_ASSOC); //Fetch the query results
var_dump($results); //Dump the results
}
keygrabber($username);
So If I change username='$username'; to username='myactualusername';, it works, i.e. it shows no errors or anything.
I'm basically trying to get all data out of keys that matches the user's username. I'll change this to userID In the future but now variables are not working so I am unable to progress.
Thanks for the help

try like this
$stmt = $db->prepare("SELECT * FROM keys WHERE username='$username'");
Hope it will make sense..

You should not use php var in SQL (you are at risk for sqlinjection) you should use prepared statementes and param binding
be sure that your $username contain a valid value firts and then
$stmt = $db->prepare("SELECT * FROM keys WHERE username=:username");
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->execute();

try this
prepare("SELECT * FROM keys WHERE username=?");
$stmt->execute([$username]);
$rows = $stmt->fetchAll();

Related

Login page in PDO [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm trying to convert my site into PDO and I have some problems with my login page.
This is my code but no matter what username or password I entered, I got the same thing: "Name or password is incorrect!". I checked the username and the password, everything it's correct.
What's wrong?
<?php
if($_POST['name']=="" || $_POST['password']=="")`enter code here`
{
print 'Fields cannot be empty !<br>
Inapoi';
exit;
}
include("connnect.php");
$stmt = $db->prepare('SELECT * FROM admin WHERE admin_name = ? AND admin_password = ?');
$stmt->bindParam(1, $_POST['name']);
$stmt->bindParam(2, md5($_POST['password']));
$stmt->execute();
if(($stmt->fetchColumn())!=1)
{
print 'Name or password is incorrect!<br>
Back';
exit;
}
session_start();
$_SESSION['name_admin']=$_POST['name'];
$_SESSION['password']=md5($_POST['name']);
$_SESSION['key_admin']=session_id();
header("location: admin.php");
?>
fetchColumn
PDOStatement::fetchColumn — Returns a single column from the next row
of a result set
Instead of $stmt->fetchColumn() you have to use $stmt->rowCount()
PDOStatement::rowCount — Returns the number of rows affected by the
last SQL statement
if($stmt->rowCount()>0)
{
print 'Name or password is incorrect!<br>
Back';
exit;
}
Read http://php.net/manual/en/pdostatement.rowcount.php
Updated
PDOStatement::rowCount() does not return the number of rows affected
by a SELECT statement. Instead, use PDO::query() to issue a SELECT
COUNT(*) statement with the same predicates as your intended SELECT
statement, then use PDOStatement::fetchColumn() to retrieve the number
of rows that will be returned
$stmt = $db->prepare("SELECT * FROM admin WHERE admin_name = ? AND admin_password = ?");
$stmt->bindParam(1, $_POST['name']);
$stmt->bindParam(2, md5($_POST['password']));
$stmt->execute();
$result=$stmt->fetch();
$row=count($result);
/* Check the number of rows that match the SELECT statement */
if ($row== 0) {
print 'Name or password is incorrect!<br>
Back';
exit;
}
1) Before include("connnect.php"); add var_dump($_POST['name']); var_dump($_POST['password']); exit;
2) Then if you get name and password add after $stmt->execute(); add var_dump($stmt); exit;
3) If have nothing in output, so the problem is in your PDO configuration

Turning a HTML form input into an PDO variable [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I want the user to specifiy a number, this number will be used in my SQL statement when connecting to the database. If the user inputs five I want the five first rows in the table to be displayed.
If i write "SELECT * FROM TABLE WHERE ID <= 5" it works, but my variable is being fetched from a form. When I use $variable = $_POST['variable'] and print it out using "SELECT * FROM TABLE WHERE ID <= $variable" no results are being returned. Why is that?
you need to bind that variable if you use PDO.
try {
$conn = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("SELECT * FROM TABLE WHERE ID <= :id");
// bind params
$stmt->bindParam(":id", $_POST['variable']);
$stmt->execute();
// fetch with
// $stmt->fetchAll(PDO::FETCH_ASSOC);
echo "OK";
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
According to http://www.w3schools.com/php/php_mysql_prepared_statements.asp
Looked through the code once again, just a simple typo:
Works with:
$sql = 'SELECT * FROM sql WHERE id <= ' . $items;
Before this I had
$sql = 'SELECT * FROM sql WHERE id <= $items';

php decode special entities in mysql [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am very new to PDO and I am trying to decode all the rows in my table "test" which contains special entities for instance "('L& eacute;on: The Professional')" instead of "Léon:The Professional".
So, here is what I tried:
<?php
require_once('connection.php');
$stmt = $conn->prepare("SELECT * from test");
$stmt->execute();
while ($results = $stmt->fetch()){
$b = html_entity_decode($stmt);
echo $b;
}
but I have no output printed..
Could someone kindly help me fix it?
prepare() returns a statement object ($stmt in your case)
fetch() returns associative array where the index would be the column name
$sql = "SELECT column1, column2, column3 from test";
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = array()
while ($row = $stmt->fetch()){
$resutlt[] = array('column1' => html_entity_decode($row['column1']),
'column2' => html_entity_decode($row['column2']),
'column3' => html_entity_decode($row['column3'])
);
}
var_dump($result);
return $result;
EDIT: to replace the values
//prepare select
$sql = "SELECT id, column1, column2, column3 from test";
$stmt = $conn->prepare($sql);
$stmt->execute();
//prepare update
$update_sql = "UPDATE test SET column1=?,column2=?,column3=? WHERE id = ?;";
$update_stmt = $conn->prepare($update_sql);
while ($row = $stmt->fetch()){
//update
$update_stmt->execute(array(html_entity_decode($row['column1']),
html_entity_decode($row['column2']),
html_entity_decode($row['column3']),
$row['id']
);
}
You did not define $query, thus it has no execute() function. If you wish to execute your prepared statement, you should call $stmt->execute().

how to make mysqli prepared statement and fetch result? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I can't understand how to create a prepared statement, and all tutorials I have seen was fetching only column.
My normal sql query
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM files WHERE id=$id ") or die(mysql_error());
$row = mysql_fetch_array($result);
$name = $row['name'];
$date = $row['date'];
Please show me how to create a prepared statement and how to fetch more than one column and insert the date into variables.
First of all it's not a good idea to use SELECT * in production. Instead specify needed columns explicitly. Take a look at https://stackoverflow.com/a/65532/1920232.
Now your code might look like
$id = $_GET['id'];
$db = new mysqli('localhost', 'user', 'password', 'dbname');
$sql = 'SELECT name, date FROM files WHERE id = ?'; //specify columns explicitly
if ($stmt = $db->prepare($sql)) { //create a prepared statement
$stmt->bind_param('i', $id); //bind parameters
$stmt->execute(); //execute query
$stmt->bind_result($name, $date); //bind result variables
$stmt->fetch(); //fetch values
}
$db->close();
echo $id, ' ', $name, ' ', $date;
Note: All error handling intentionally skipped for brevity.

how can i put a php variable into mysql command [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
$id1 = $_POST['number']; //here i am getting a php variable called number
$result = mysqli_query($con, "SELECT id,main FROM first WHERE ?how can i put that number right here?");
I am getting a variable from another page using ajax and i should put it into mysql command.How can i do that?
Here's an example of using prepared statements:
/* Create a new mysqli object with database connection parameters */
$mysqli = new mysql('localhost', 'username', 'password', 'db');
if(mysqli_connect_errno()) {
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
/* Create a prepared statement */
if($stmt = $mysqli -> prepare("SELECT priv FROM testUsers WHERE username=?
AND password=?")) {
/* Bind parameters
s - string, b - blob, i - int, etc */
$stmt -> bind_param("ss", $user, $pass);
/* Execute it */
$stmt -> execute();
/* Bind results */
$stmt -> bind_result($result);
/* Fetch the value */
$stmt -> fetch();
echo $user . "'s level of priviledges is " . $result;
/* Close statement */
$stmt -> close();
}
/* Close connection */
$mysqli -> close();
Source
I strongly suggest researching prepared statements early on.
option 1.Good to go for Prepared statements
option 2."SELECT id,main FROM first WHERE id=$id"
When a string is specified in double quotes, variables are parsed within it.
$result = mysqli_query($con, "SELECT id,main FROM first WHERE your_db_field = $id1");
OR
$result = mysqli_query($con, "SELECT id,main FROM first WHERE your_db_field = " . $id1 . ");
Should work just fine.
However you should consider using Stored Procedures to avoid any security vulnerabilities...
//Get ur name from Post Request
$number=$_POST['number'];
$query="SLEECT * FROM TABLE_NAME WHERE colunm_name='$number"; (or)
$query="SLEECT * FROM TABLE_NAME WHERE colunm_name='".$number."'";
$result=mysql_query($con,$query)
//Using Prepared Statement
$stmt = $dbh->prepare("SELECT * FROM TABLE_NAME where COLUMN_NAME= ?");
if ($stmt->execute(array($_GET['number']))) {
while ($row = $stmt->fetch()) {<br />
print_r($row);<br />
}
}

Categories