Adding a secondary WHERE statement to PDO/MySql statement - php

I have a PDO/MySQL database connection. My database holds content for various landing pages. To view these landing pages I enter *localhost/landing_page_wireframe.php* and append with ?lps=X (where X represents the Thread_Segment) to display the particular page in the browser. I am now getting to second iterations of these pages and need to add a secondary classifier to follow "Thread_Segment" to distinguish which version I am trying to pull up. Here is a snippet of my current working query.
<?php
$result = "SELECT * FROM landing_page WHERE Thread_Segment = :lps";
$stmt = $connection->prepare($result);
$stmt->bindParam(':lps', $_GET['lps']);
$stmt->execute();
$thread = "";
$threadSegment = "";
$version = "";
$categoryAssociation = "";
while($row = $stmt->fetch()) {
$thread = $row["Thread"];
$threadSegment = $row["Thread_Segment"];
$version = $row["Version"];
$categoryAssociation = $row["Category_Association"];
}
?>
So I need to now change this to add in the secondary classifier to distinguish between versions. I would imagine my query would change to something like this:
$result = "SELECT * FROM landing_page WHERE Thread_Segment = :lps AND Version = :vrsn";
if this is correct so far, then where I am beginning to get lost is in the following PHP code.
$stmt = $connection->prepare($result);
$stmt->bindParam(':lps', $_GET['lps']);
$stmt->execute();
I imagine I need to include some secondary iteration of this in my php to talk to the secondary classifier, but not totally sure how to go about this, and then I would imagine my url appendage would go from ?lps=X to something like this ?lps=X&vrsn=Y (Y representing the version).
I should state that I am somewhat new to PHP/MySql so the answer here may be simple, or may not even be possible. Perhaps I am not even going about this the correct way. Thought you all might be able to shed some insight, or direction for me to curve my research on the matter to. Thanks and apologies for any improper terminology, as I am definitely new to these technologies.

The URL change is as you describe. Just add another bindParam call to use that parameter:
$stmt = $connection->prepare($result);
$stmt->bindParam(':lps', $_GET['lps']);
$stmt->bindParam(':vrsn', $_GET['vrsn']);
$stmt->execute();

Adding another bindParam() should work here.
$stmt = $connection->prepare($result);
$stmt->bindParam(':lps', $_GET['lps']);
$stmt->bindParam(':vrsn', $_GET['vrsn']);
$stmt->execute();
You can access it via ?lps=X&vrsn=Y but just as a warning, the query will fail if those $_GET params are not requested. I recommend defaulting it to something prior to sending it through the query:
$stmt = $connection->prepare($result);
$lps = isset($_GET['lps']) ? $_GET['lps'] : 'default lps value';
$vrsn = isset($_GET['vrsn ']) ? $_GET['vrsn '] : 'default vrsn value';
$stmt->bindParam(':lps', $lps);
$stmt->bindParam(':vrsn', $vrsn);
$stmt->execute();

Related

android volly , get data from database row count [duplicate]

Im not trying to use a loop. I just one one value from one column from one row. I got what I want with the following code but there has to be an easier way using PDO.
try {
$conn = new PDO('mysql:host=localhost;dbname=advlou_test', 'advlou_wh', 'advlou_wh');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$userid = 1;
$username = $conn->query("SELECT name FROM `login_users` WHERE username='$userid'");
$username2 = $username->fetch();
$username3 = $username2['name'];
echo $username3;
This just looks like too many lines to get one value from the database. :\
You can use fetchColumn():
$q= $conn->prepare("SELECT name FROM `login_users` WHERE username=?");
$q->execute([$userid]);
$username = $q->fetchColumn();
You could create a function for this and call that function each time you need a single value. For security reasons, avoid concatenating strings to form an SQL query. Instead, use prepared statements for the values and hardcode everything else in the SQL string. In order to get a certain column, just explicitly list it in your query. a fetchColumn() method also comes in handy for fetching a single value from the query
function getSingleValue($conn, $sql, $parameters)
{
$q = $conn->prepare($sql);
$q->execute($parameters);
return $q->fetchColumn();
}
Then you can simply do:
$name = getSingleValue($conn, "SELECT name FROM login_users WHERE id=?", [$userid]);
and it will get you the desired value.
So you need to create that function just once, but can reuse it for different queries.
This answer has been community edited addressing security concerns
Just like it's far too much work to have to get into your car, drive to the store, fight your way through the crowds, grab that jug of milk you need, then fight your way back home, just so you can have a milkshake.
All of those stages are necessary, and each subsequent step depends on the previous ones having been performed.
If you do this repeatedly, then by all means wrap a function around it so you can reuse it and reduce it down to a single getMyValue() call - but in the background all that code still must be present.

Php search Splitting criteria type

I have a php search form with two fields. One for $code another for '$name'.The user uses one or the other, not both.
The submit sends via $_POST.
In the receiving php file I have:
SELECT * FROM list WHERE code = '$code' OR name = '$name' ORDER BY code"
Everything works fine, however I would like that $code is an exact search while $name is wild.
When I try:
SELECT * FROM list WHERE code = '$code' OR name = '%$name%' ORDER BY code
Only $code works while $name gives nothing. I have tried multiple ways. Changing = to LIKE, putting in parentheses etc. But only one way or the other works.
Is there a way I can do this? Or do I have to take another approach?
Thanks
If you only want to accept one or the other, then only add the one you want to test.
Also, when making wild card searches in MySQL, you use LIKE instead of =. We also don't want to add that condition if the value is empty since it would become LIKE '%%', which would match everything.
You should also use parameterized prepared statements instead of injection data directly into your queries.
I've used PDO in my example since it's the easiest database API to use and you didn't mention which you're using. The same can be done with mysqli with some tweaks.
I'm using $pdo as if it contains the PDO instance (database connection) in the below code:
// This will contain the where condition to use
$condition = '';
// This is where we add the values we're matching against
// (this is specifically so we can use prepared statements)
$params = [];
if (!empty($_POST['code'])) {
// We have a value, let's match with code then
$condition = "code = ?";
$params[] = $_POST['code'];
} else if (!empty($_POST['name'])){
// We have a value, let's match with name then
$condition = "name LIKE ?";
// We need to add the wild cards to the value
$params[] = '%' . $_POST['name'] . '%';
}
// Variable to store the results in, if we get any
$results = [];
if ($condition != '') {
// We have a condition, let's prepare the query
$stmt = $pdo->prepare("SELECT * FROM list WHERE " . $condition);
// Let's execute the prepared statement and send in the value:
$stmt->execute($params);
// Get the results as associative arrays
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
The variable $results will now contain the values based on the conditions, or an empty array if no values were passed.
Notice
I haven't tested this exact code IRL, but the logic should be sound.

How to replace multiple placeholders in a PHP SQL query

Sorry if the title is strangely worded. This is my first time asking anything here, and I'm pretty new to PHP so I'm having a tough time figuring this out.
Basically, I am trying to write a PHP script that will allow me to change the rules for a certain game instance from our website, so I don't have to go into the database and run a SQL query every time.
This is what I have so far:
public function update_rules()
{
$rules = $this->input->post('rules');
$domains = $this->input->post('domains_multiselect');
$qarr = array();
$sql = "
UPDATE domains
SET rules = ?
WHERE domain_id = ?
";
$qarr[] = $rules;
$qarr[] = $domain_id;
$query = $this->db->query($sql,$qarr);
redirect ("admin/insert_rules");
}
I am unsure how to to a substr_replace() to change the "?" placeholders in the query to be able to input both the manually typed rules and the domain_id, which I think will be generated when the domain name is selected.
I could be completely off-base here, but if anyone could point me in some kind of direction, that'd be great. thank you.
you can use either named placeholder or position dependent placeholders...
//Position dependent:
$stmt = $this->db->prepare("UPDATE domains SET rules = ? WHERE domain_id = ?");
$stmt->bindParam(1, $rules);
$stmt->bindParam(2, $domain_id);
$stmt->execute();
//Named Placeholder:
$stmt = $this->db->prepare("UPDATE domains SET rules = :rules WHERE domain_id = :domain");
$stmt->bindParam(':rules', $rules);
$stmt->bindParam(':domain', $domain_id);
$stmt->execute();

Pulling settings from MySQL using Object-Orientated PHP

Ok, so I am slowly migrating from Procedural to OOP, and I'm finding it all pretty straight forward apart from one thing.
I used to use this method for pulling my settings data from a simple two-column settings table comprising of a row for each setting, defined with 'setting' and 'value' fields:
$query = mysql_query("SELECT * FROM `settings`");
while ($current_setting = mysql_fetch_array($query)) {
$setting[$current_setting['setting']] = $current_setting['value'];
}
As you can see, I manipulated it so that I could simply use $setting['any_setting_name'] to display the corresponding 'value' within that setting's row. I'm not sure if this is a silly way of doing things but no matter, I'm moving on anyway..
However, since moving to object orientated PHP, I don't really know how to do something similar..
$query = $mysqli->query("SELECT * FROM `settings`");
while ($current_setting = $query->fetch_object()) {
echo $current_setting->setting; // echo's each setting name
echo $current_setting->value; // echo's each setting value
}
As you can see, I'm perfectly able to retrieve the data, but what I want is to be able to use it later on in the form of: $setting->setting_name; which will echo the VALUE from the row where setting is equal to 'setting_name'..
So basically if I have a row in my settings table where setting is 'site_url' and value is 'http://example.com/', I want $setting->site_url; to contain 'http://example.com/'.. Or something to the same effect..
Can anyone help me out here? I'm at a brick-wall right now.. Probably something really stupid I'm overlooking..
Since you are working with a resource it has a pointer. Once you get to the end you can't use it anymore. I think you can reset it but why not mix the new with the old?
I don't think you're going to have too much overhead, any that matters anyway, to do something like this:
$settings = array();
$query = $mysqli->query("SELECT * FROM `settings`");
while ($current_setting = $query->fetch_object()) {
$settings[$current_setting->setting] = $current_setting->value;
}
Now you can use $settings as much as you want.
UPDATE
Haven't tested this or used it but are you looking to do something like this? Consider the following pseudo code and may not actually work.
$settings = new stdClass();
$query = $mysqli->query("SELECT * FROM `settings`");
while ($current_setting = $query->fetch_object()) {
$settings->{$current_setting->setting} = $current_setting->value;
}

Append 2 Mysql rows

I have a two step registration, one with vital data, like email username and password, and a second optional one with personal info, like bio, eye color, etc.. i have 2 exec files for these, the first ofc writes the data in the first part of the database, leaving like 30 columns of personal data blank. The second one does another row, but with the vital data empty now.. I would like to append, or join these two rows, so all the info is in one row..
Here is the 2nd one
$qry = "UPDATE `performers` SET `Bemutatkozas` = '$bemuatkozas', `Feldob` = '$feldob', `Lehangol` = '$lehangol', `Szorzet` = '$szorzet', `Jatekszerek` = '$jatek', `Kukkolas` = '$kukkolas', `Flort` ='$flort', `Szeretek` = '$szeretek', `Utalok` = '$utalok', `Fantaziak` = '$fantaziak', `Titkosvagyak` = '$titkos_vagyak, `Suly` = '$suly', `Magassag` = '$magassag', `Szemszin` = '$szemszin', `Hajszin` = '$hajszin', `Hajhossz` = '$hajhossz', `Mellboseg` ='$mellboseg', `Orarend` = '$orarend', `Beallitottsag` = '$szexualis_beallitottsag', `Pozicio` = '$pozicio', `Dohanyzas` = '$cigi', `Testekszer` = '$pc', `Tetovalas` ='$tetko', `Szilikon` ='$szilikon', `Fetish1` = '$pisiszex', `Fetish2` = '$kakiszex', `Fetish3` = '$domina', `Testekszerhely` = '$pchely', `Tetovalashely` = '$tetkohely', `Csillagjegy` = '$csillagjegy', `Parral` = '$par', `Virag` = '$virag' WHERE `Username` ='" . $_POST['username']. "'";
$result = #mysql_query($qry);
//Check whether the query was successful or not
if($result) {
header("location: perf_register_success.php");
exit();
I'm not sure if $_POST works here. I have the form, then the exec of that form, which works, then this form, and this is the exec of that.. Anyway I always get "query failed" message, which is in the else statement of the 'if' i'm using. What am i doing wrong?
Thanks!
The correct syntax for UPDATE is as follows:
UPDATE table SET columnA=valueA, columnB=valueB WHERE condition=value
(documentation here)
Thus, your query should look like the following:
$qry = "UPDATE performers SET Bemutatkozas = $bemuatkozas, Feldob = $feldob, Lehangol = $lehangol [...] WHERE Username ='" . $_POST['username']. "'
You'll have to replace [...] with all your values (that's gonna take some time) but hopefully you get the pattern.
Other than that there are a number of things you should improve/change in your code but I'll just point you to jeroen answer in this question since he pretty much covers it all.
You want UPDATE instead of INSERT for your second query.
Apart from that you really need to fix that sql injection error, preferably by switching to PDO or mysqli in combination with prepared statements. The mysql_* functions are deprecated.
And whatever solution you take, you need to add proper error handling, suppressing errors is wrong, especially when you try to fix a problem but even in a production site, errors need to be logged, not ignored.

Categories