Can I have some advice on where I'm going wrong with this Query?
$entry_id = '1';
$accident_road = $form_data[58]["id"]; //print_r returns "116"
$accident_road_array = $wpdb->get_results(
"SELECT id FROM wp_rg_lead_detail
WHERE field_number = '$accident_road'
AND 'lead_id' = '$entry_id' ",
ARRAY_A);
print_r returns 'Array()'
I assume lead_id is a field in DB so you don't need quotes for it:
AND lead_id = '$entry_id'
You're also going wrong by putting variables directly into the query, you make your app vulnerable to SQL injections. consider using prepared statements.
you set values in variable
$accident_road
while down there in query you used
'$accident_road_exp'
cross check this one man
Related
This question already has answers here:
How to insert values in a PHP array to a MySQL table?
(2 answers)
Closed 5 years ago.
I'm using PHP session variable to track character ID's between two tables, characters and character_data_store.
The session ID definitely has the correct ID as I have had to print its value before it goes into the mySQL query.
For testing I selected a user I knew had a rapsheet and used
$usersql = "SELECT *
FROM character_data_store
WHERE character_data_store.`key` = 'RapSheet'
AND character_data_store.character_id = '216'";
Obviously I can't use this for all users as I need to confirm the right one has been selected so thats where the session variable comes in.
I've tried using:
$correctPlayer = $_SESSION['selpid'];
echo $correctPlayer; #confirm it's the right id and then remove
$usersql = "SELECT *
FROM character_data_store
WHERE character_data_store.'key' = 'RapSheet'
AND character_data_store.character_id = '$correctPlayer'";
I did some searching on SO and I found that int's need to have double quotes around them not single quotes, I tried that and had no luck but someone else suggested putting the session ID in exactly which I tried next:
$usersql = "SELECT *
FROM character_data_store
WHERE character_data_store.'key' = 'RapSheet'
AND character_data_store.character_id = {$_SESSION['selpid']}";
Each time I do this I get mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given which SO tells me is because this operation results to false, I assume because it's not accepting the playerID from selpid or $correctPlayer?
It definitely works with the testing user where the playerID is inserted directly into the query. But I can't think of a way to do that since I need to match the playerID from table "characters" where the search is done against their first and last name and then pull the rapsheet data against the same playerID in table "character_data_store".
How do I use a variable in the WHERE condition of a MySQL query using a php variable?
You have obvious error in your code. You are missing quotes in {$_SESSION['selpid']} and you are using quotes in column name. Your query should be
$usersql = "SELECT * FROM character_data_store WHERE character_data_store.`key` = 'RapSheet' AND character_data_store.character_id = '{$_SESSION['selpid']}'";
You should not use quotes in column name, instead use backquotes(`) if you really need. I recommend prepared statements.
There are multiple ways to do this. A naive way to do this would be-
$usersql = "SELECT * FROM character_data_store WHERE character_data_store.'key' = 'RapSheet' AND character_data_store.character_id = ".$correctPlayer;
But to avoid sql injections I would recommend you use bindparam function to bind paramaters in a statement.
$sql="SELECT * FROM character_data_store WHERE character_data_store.'key' = 'RapSheet' AND character_data_store.character_id = ?";
if($stmt = $dbh->prepare($sql)){
$stmt->bindParam(1, $correctPlayer, PDO::PARAM_STR);
$ql = $stmt->execute() or die("ERROR: " . implode(":", $dbh->errorInfo()));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$result['data'] = $row;
This is my code:
$sql = $_POST['sql'];
....
$result = $mysqli->query($sql);
This does not return any results. So i echoed the $sql variable and this is the result:
SELECT o.entity_id, o.increment_id FROM sales_flat_order o JOIN sales_flat_order_payment p ON o.entity_id = p.parent_id JOIN sales_flat_order_address a ON o.entity_id = a.parent_id WHERE a.country_id = \'DE\' ORDER BY o.entity_id DESC LIMIT 10;
Now, when I assign this to the $sql variable directly, it works. What could be the problem?
Thanks
Well, first you could test $result and output the last error with $mysqli->error when it's false, that would give you details on what's wrong.
Secondly, you should NOT execute a query that's coming from POST or GET parameter, that's how you allow anyone to do anything on your database with sql injection. That's a big security breach.
Thirdly, the issue is probably on POST encoding (note the quotes \'DE\') so if you urldecode and/or stripslashes your $sql it would probably work
I have a search form where users can enter a few pieces of information to search for records in the database. Due to the fact that some of the fields can be left blank, I am dynamically creating the WHERE clause of the query as well as dynamically binding the PDO parameters. Everything works great if the user only fills out 1 field in the search form but if more than 1 field is used then an empty array is returned. Here is my code.
if(count($_POST)>0)
{
//Remove any key that has no value
$data = array_filter($_POST);
//Define array to hold the pieces of the where clause
$where = array();
//loop each of the variable to build the query
foreach($data as $key=>$value)
{
$key = mysql_real_escape_string($key);
//Push values to array
array_push($where, "$key=:$key");
}
//Create the select query
$query = "SELECT application_ID,
student_last_name,
student_first_name,
s.school_name,
DATE_FORMAT(submission_datetime, '%m/%d/%Y %h:%i:%s %p') AS submission_datetime,
aps.name
FROM application a
LEFT JOIN application_status aps ON(aps.status_ID = a.application_status_ID)
LEFT JOIN schools s ON(s.school_ID = a.school_choice)";
//As long as criteria was selected in the search form then add the where clause to the query with user's search criteria
if(!empty($where))
{
$query .= "WHERE ".implode(" AND ", $where);
}
//Add ORDER BY clause to the query
$query .= " ORDER BY application_ID";
$stmt = $conn->prepare($query);
//loop each of the variables to bind parameters
foreach($data as $key=>$value)
{
$value = mysql_real_escape_string($value);
$stmt->bindparam(':'.$key, $value);
}
$stmt->execute();
$result = $stmt->fetchall(PDO::FETCH_ASSOC);
}
When I echo the query everything looks fine and even returns results when run from PHPMyAdmin. Here is the query.
SELECT application_ID,
student_last_name,
student_first_name,
s.school_name,
DATE_FORMAT(submission_datetime, '%m/%d/%Y %h:%i:%s %p') AS submission_datetime,
aps.name
FROM application a
LEFT JOIN application_status aps ON(aps.status_ID = a.application_status_ID)
LEFT JOIN schools s ON(s.school_ID = a.school_choice)
WHERE school_choice=:school_choice AND status_ID=:status_ID
ORDER BY application_ID ASC
When I print_r I get an empty array.
Thanks for any help you can provide.
When you iterate through an array to bind values to the PDO statement you should use bindValue instead of bindParam.
When you say $stmt->bindparam(':'.$key, $value), the query will use the value of the variable $value as it is at the time of the query execution. Value of $value will be the last element of the array.
http://php.net/manual/en/pdostatement.bindvalue.php
I hope this helps.
You are not supposed to use mysql_real_escape_string() with prepared statements. And in fact, this function will not work if you don't have a mysql_connect() initialized, which you don't.
That must be why it all is failing, your calls to mysql_real_escape_string() are returning FALSE for everything.
Also, what makes you think array keys coming from $_POST are safe to be used in your SQL query? You are taking a serious risk of SQL injection here, don't ever do that.
I have a variable, $ids
It is a , separated string so it can be $ids = "1" or $ids = "1, 3, 7, 8"
What i want to do is update the database based on these values so i have :
$query = "UPDATE Fields SET Value = '1' WHERE Id IN '$ids'";
And also:
$query = "UPDATE Fields SET Value = '1' WHERE Id '$ids'";
What is the best way to update the database, should i split the string in to an array, and then do a for each loop? or is there a better way?
Save the fact that it's wide open to SQL Injection, this line works for one or many id's:
$query = "UPDATE Fields SET Value = '1' WHERE Id IN ($ids)";
Now, to keep yourself from SQL Injection attacks, which is obviously up to you, you'd want to explode that array and send multiple update statements like this:
$query = "UPDATE Fields SET Value = '1' WHERE Id = :Id";
There's nothing inherently wrong with using an IN clause here. Any WHERE clause works for an UPDATE statement. You'll just want to treat the numbers as a list of values instead of a string. Something like this:
$query = "UPDATE Fields SET Value = '1' WHERE Id IN ($ids)";
The really important part is how you get the $ids value into the query in the first place. You don't show that in the question, but you'll want to make sure you're not opening yourself to a SQL injection vulnerability. Make sure you're properly sanitizing inputs and using prepared statements. How prepared statements handle lists of values vs. individual values is up to the data access technology being used.
Use this query:
$query = "UPDATE Fields SET Value = '1' WHERE Id IN ($ids)";
Where $ids should be formatted als 1,2,3,4. Don't forget to check them before execution (SQL Injection).
I'm trying to count all of the rows from an item list where the id matches a user input. I am switching all of my code from mysql to PDO as I have learned it is much better.
The code below is what I found to work in my situation.
$id = '0';
$sql="SELECT count(*) FROM item_list WHERE item_id = $id";
$data=$connMembers->query($sql)->fetchcolumn();
echo $data;
However, It is not safe for a live site due to sql injections.
I want to know how can I change it to work whare it sanatizes the user input.
I would prefer using a prepare and execute functions so the variables are kept seperately.
So is there something I can do?
This is where you start binding parameters. I prefer to do it using ? and one array for inputs.
Assuming $connMembers is your PDO object:
$sql="SELECT COUNT(*) FROM item_list WHERE item_id = ?";
$input=array($id); //Input for execute should always be an array
$statement=$connMembers->prepare($sql);
$statement->execute($input);
$data=$statement->fetchObject();
var_dump($data);
To add more variables to your sql, just add another ? to the query and add the variable to your input.
$sql="SELECT COUNT(*) FROM item_list WHERE item_id = ? AND item_name=?";
$input=array($id, $name); //Input for execute should always be an array
$statement=$connMembers->prepare($sql);
$statement->execute($input);
$data=$statement->fetchObject();
var_dump($data);
OR you can use bindParam:
$sql="SELECT COUNT(*) FROM item_list WHERE item_id = :itemID";
$statement=$connMembers->prepare($sql);
$statement->bindParam(':itemID', $id);
/*Here I am binding parameters instead of passing
an array parameter to the execute() */
$statement->execute();
$data=$statement->fetchObject();
var_dump($data);