PHP, MY SQL error query [duplicate] - php

This question already has answers here:
Can PHP PDO Statements accept the table or column name as parameter?
(8 answers)
Closed 6 years ago.
I have an application that goes by that passes for my PHP a variable (nomecardapioBD and which received and recorded in the variable :nomecardapioBD) which is the table name that I want to select all rows and columns.
But to receive the variable via post can not make the appointment. Can anyone tell me what was wrong with this part of my code ?
$query = "Select * FROM :nomecardapioBD ";
$query_params = array(
':nomecardapioBD' => $_POST['nomecardapioBD']
);
//execute query
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll();

Why not this?
$query = "Select * FROM " . $_POST['nomecardapioBD'];
//execute query
try {
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll();
You should also do some sort of input sanitization though.

Table and Column names cannot be replaced by parameters in PDO. Just use it as
$table=$_POST['nomecardapioBD'];
$query = "Select * FROM $table";
//execute query
try {
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}

Related

MYSQL Check if username already exists in database [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 3 years ago.
My code was working but after I inserted a query to check if the first name in MYSQL database already exists, it does not work anymore. Here you can see my code, if you have any tip on how to make this work, I will appreciate it. Thank you very much!
I have tried to work with mysql_num_rows command, but it seems like I didn't use it correctly.
<?php
require_once __DIR__.'/connect.php';
$sName = $_POST['txtName'];
$query = mysql_query("SELECT * FROM users WHERE firstName = '$sName' ");
if (mysql_num_rows ($query) > 0){
echo 'User with this name already exists';
}else{
try {
$stmt = $db->prepare('INSERT INTO users
VALUES (null, :sName, :sLastName, :sEmail, :sCountry )');
$stmt->bindValue(':sName', $sName);
$stmt->execute();
echo 'New user was successfully inserted';
} catch (PDOEXception $ex) {
echo $ex;
}
}
You are trying to use mysql_query when you have (based on the rest of your code that is working) a PDO connection. Change your query to use your existing connection:
try {
$stmt = $db->prepare("SELECT COUNT(*) FROM users WHERE firstName = :sName");
$stmt->bindValue(':sName', $sName);
$stmt->execute();
$num_rows = $stmt->fetchColumn();
}
catch (PDOEXception $ex) {
echo $ex;
}
if ($num_rows > 0) {
echo 'User with this name already exists';
}
else {
// the rest of your code here

Having trouble checking mysql database for existing user_id in PHP

I'm having a problem with the following PHP script. Specifically, the part that creates the user_id. This is part of a larger registration.php file that works fine without the section that creates the user_id.
As you can see, it's a while loop that uses a variable, $useridexits, to control the loop. It's set to true by default, so the loop runs. A random number is generated and then checked against the database. If a result is returned, the $useridexists variable is set to true and the loop continues. If no results are returned, $useridexists is set to false, so the loops stops. The number generated is then set to $userid and is then added to the database in the following section.
Here's the code:
//This section creates a new userid for each user.
//This varible is used by the while loop and is set to true by default.
$useridexists = true;
//While loop to create userid and check the database to see if the userid
//already exists. If it does, the while loop keeps going until a unique
//user id is created.
while($useridexists){
// Function to create random user id number.
function randomNumber($length) {
$result = '';
for($i = 0; $i < $length; $i++) {
$result .= mt_rand(0, 9);
}
return $result;
}
// user id value created from randomNumber function.
$number = randomNumber(1);
//query the database to see if the user id already exists
$query = "SELECT * FROM users WHERE user_id = :number";
$query_params = array(':number' => '$number');
try {
// These two statements run the query against the database table.
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Failed to run query: " . $ex->getMessage();
die(json_encode($response));
}
$row = $stmt->fetch();
if ($row){
$useridexists = true;
}else{
$useridexists = false;
}
}
$userid = $number;
// This section adds the values to the database:
$query = "INSERT INTO users (username, password, email, firstname, lastname, user_id) VALUES ( :user, :pass, :email, :firstname, :lastname, :uid)";
//update tokens with the actual data:
$query_params = array(
':user' => $_POST['username'],
':pass' => $_POST['password'],
':email' => $_POST['email'],
':firstname' => $_POST['firstName'],
':lastname' => $_POST['lastName'],
':uid' => $userid
);
//run the query, and create the user
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Failed to run query: " . $ex->getMessage();
die(json_encode($response));
}
$response["success"] = 1;
$response["message"] = "Username Successfully Added! Please log in.";
echo json_encode($response);
$email= mysql_escape_string($_POST['email']);
$username = mysql_escape_string($_POST['username']);
If I comment out this section, everything works:
// user id value created from randomNumber function.
$number = randomNumber(1);
//query the database to see if the user id already exists
$query = "SELECT * FROM users WHERE user_id = :number";
$query_params = array(
':number' => '$number'
);
try {
// These two statements run the query against the database table.
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Failed to run query: " . $ex->getMessage();
die(json_encode($response));
}
$row = $stmt->fetch();
if ($row){
$useridexists = true;
}else{
$useridexists = false;
}
If I don't comment that section out, I don't get any errors, but nothing gets added to the database.
Everything works except the part that checks the database to see if the user_id already exists and changes the $useridexists variable to false, which should escape the while loop. When I add that, nothing gets added to the database.
BTW: I'm using a 1 digit value for testing purposes, but I'll change it to $number = randomNumber(7); once the code actually works.

Cannot display results from query with PDO

I am trying to get the results from a query which should get multiple results and display them all on the page. However it is not displaying any of the content. My guess is a mistake in my syntax for me loop. But I am unsure.
//query to find comments about this map
$query = "
SELECT
user_id,
comment
FROM map_comments
WHERE
map_id = :mapID
";
//query parameters
$query_params = array(
':mapID' => $_SESSION['mapID']
);
try
{
//execute query
$statement = $db->prepare($query);
$result = $statement->execute($query_params);
//get all results
$comments = $result->fetchAll;
if($result === FALSE)
{
die(mysql_error()); // TODO: better error handling
}
}
catch(PDOException $e)
{
die("failed to find comments");
}
foreach($comments as &$comment)
{
echo $comment;
}
You need parentheses after a function to call it.
$comments = $result->fetchAll;
should be:
$comments = $statement->fetchAll();
Also, the check for if ($result == FALSE) should be before this line. And you can't use mysql_error() if you're using PDO, you should use $statement->errorInfo(). Or you should enable PDO::ERRMODE_EXCEPTION on the connection, and the catch block will be invoked. You should then use $db->errorInfo() in the error message that it prints.

invalid parameter number exception using named parameter

I am getting "invalid parameter number:parameter undefined" exception when attempting an insert query to mysql database.
I am returning the result to my Android app as json.
if (!empty($_POST))
{
$query = "INSERT INTO attendance (tdate,slot_from,slot_to,coursecode,stud_id,remark) VALUES (:dat,:fromm,:too,:ccode,:stud,:rmk ) ";
$query_params = array(
':dat' => $_POST['datee'],
':from'=>$_POST['fromm'],
':to'=>$_POST['too'],
':ccode'=>$_POST['course'],
':stud'=>$_POST['sname'],
':rmk'=>$_POST['remark'],
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex)
{
//or just use this use this one to product JSON data:
$response["success"] = 0;
$response["message"] = $ex->getMessage();
$response["date"] = $_POST['datee'];
$response["from"] = $_POST['fromm'];
$response["to"] = $_POST['too'];
$response["ccode"] = $_POST['course'];
$response["stud"] = $_POST['sname'];
$response["remark"] = $_POST['remark'];
die(json_encode($response));
}
}
you lack a m in
':from'=>$_POST['fromm'],
should be
':fromm'=>$_POST['fromm'],
you must be careful when using named parameter, I myself am very prone to making such errors
that's why I more easily use the ? placeholder, this way in your exemple:
$query = "INSERT INTO attendance (tdate,slot_from,slot_to,coursecode,stud_id,remark) VALUES (?,?,?,?,?,?) ";
$query_params = array(
$_POST['datee'],
$_POST['fromm'],
$_POST['too'],
$_POST['course'],
$_POST['sname'],
$_POST['remark'],
);
then:
$result = $stmt->execute($query_params);
you must be sure that the params are in good order (same as in query)
In your query, you're misspelling from:
$query = "INSERT INTO attendance (tdate,slot_from,slot_to,coursecode,stud_id,remark) VALUES (:dat,:fromm,:too,:ccode,:stud,:rmk ) ";
Replace it with:
$query = "INSERT INTO attendance (tdate,slot_from,slot_to,coursecode,stud_id,remark) VALUES (:dat,:from,:too,:ccode,:stud,:rmk ) ";

Can't get array from PDO query

i'm trying to get an array from a SQL query using pdo, what i send to the method it's for example $connection->selectFrom('Person',array(1,2));
when i try to get the results it returns an empty array, here is my code:
public function selectFrom($table,$indexes){
try{
$pdo=$this->getPdo();
// HERE I GET ALL THE COLUMN NAMES FROM THE TABLE I RECEIVE
$columns = $this->getColumnNames($table);
$finals = array();
// IN THIS CICLE I GET THE COLUMNS THAT MATCH THE INDEXES I RECEIVE
for($i=0;$i<count($indexes);$i++){
$finals[$i] = $columns[$indexes[$i]];
}
// FROM HERE I GET THE QUERY STATEMENT WICH IS SELECT column1,column2 from $table
$query = $this->getSelectSQL($table, $finals);
// ALL OF THE ABOVE WORKS BUT HERE IT STOPS WORKING
$results = $pdo->query($query);
return $results;
}catch(PDOException $ex){
echo "EXCEPTION ".$ex;
}
}
Thanks to #Cymbals for your answer, the final code ended up like this:
public function selectFrom($table,$indexes){
try{
$pdo=$this->getPdo();
$columns = $this->getColumnNames($table);
$finals = array();
for($i=0;$i<count($indexes);$i++){
$finals[$i] = $columns[$indexes[$i]];
}
$query = $this->getSelectSQL($table, $finals);
$query.= " WHERE Available = 1";
$stmt = $pdo->prepare($query);
$stmt->execute();
$results = $stmt ->fetchAll();
return $results;
}catch(PDOException $ex){
echo "EXCEPTION ".$ex;
}
}
Try this after getting the query, prepare and execute it
$stmt = $pdo->prepare($query);
var_dump($stmt);// if the prepare fails or sql query is messed up it will give false
$results = $stmt->execute();
return $results;

Categories