passing parameter to select statement from url - php

I have a database with a table which has two columns, lets say aa_id and bb_id - each of the the columns is a foreign key relating to another table and both columns are making a composite key for this particular table. there are several rows containing either the same aa_id and different bb_id or the same bb_id and different aa_id.
using pdo I want to extract the rows of the same - let's say - aa_id and I want to do this passing the parameter value in url. so the result of the select statement should be several rows and they should be saved as - for example - an array.
I have tried to do this with following code:
$sql = sprintf("select aa_id, bb_id from a_table where aa_id=:aa_id");
$res = $db->query($sql);
$rows = $res->fetch(PDO::FETCH_ASSOC);
foreach($rows as $key=>$value)
{
echo $key . " - " . $value . "</br>";
}
And it give no result.
I does work if I state the value of aa_id in the query like this
$sql = sprintf("select aa_id, bb_id from a_table where aa_id=191919");
, but it extracts no data if I put the value in url.
I am not really sure what to search for in the web because I don't know what's the notation called (if it is). If somebody could tell me what may be wrong with the code or give me directions to what I should look for in the web among tutorials or documentation I will be grateful. Perhaps somebody could recommend a good source of knowledge about mysql, php and pdo... Thanks in advance.

Well yeah, :indicator doesn't just automatically load in $_GET['indicator'], you need to manually bind it.
Assuming the URL ends with, ?aa_id=191919, your code might look something like this:
$sql = "select aa_id, bb_id from a_table where aa_id=:aa_id";
$res = $db->prepare($sql);
$res->bindValue(':aa_id', $_GET['aa_id'], PDO::PARAM_INT);
$res->execute();
$rows = $res->fetch(PDO::FETCH_ASSOC);
while($row=$res->fetch(PDO::FETCH_ASSOC))
{
print_r($row);
}

Related

PHP/MYSQL:Carry out UPDATE within SELECT query

There are many questions on SO about this but I cannot find one that quite meets my situation.
I want to use the values in some fields/columns of a table to set the value of a third field/column
In other words something like:
table races
athleteid|difficulty|score|adjustedscore
$sqlSelect = "SELECT athleteid,difficulty,score FROM races";
$res = mysql_query($sqlSelect) or die(mysql_error());
while ($row = mysql_fetch_array($res)){
$adjustedscore=difficulty*score;
$sqlupdate = "UPDATE race, set adjustedscore = '$adjustedscore' WHERE athletes = 'athletes'";
$resupdate = mysql_query($sqlupdate);
}
My understanding, however, is that MYSQL does not support update queries nested in select ones.
Note, I have simplified this slightly. I am actually calculating the score based on a lot of other variables as well--and may join some tables to get other inputs--but this is the basic principal.
Thanks for any suggestions
You can run:
UPDATE `races`
SET `adjustedscore` = `difficulty` * `score`
WHERE `athleteid` IN (1, 2, 3, ...)
First of all, as previous commentators said, you should use PDO instead of mysql_* queries.
Read about PDO here.
When you'll get data from DB with your SELECT query, you'll get array. I recommend you to use fetchAll() from PDO documentation.
So, your goal is to save this data in some variable. Like you did with $row.
After that you'll need to loop over each array and get your data:
foreach($row as $r) {
//We do this to access each of ours athlete data
$adjustedscore= $row[$r]["difficulty"]* $row[$r]["score"];
//Next row is not clear for me...
$query = "UPDATE race SET adjustedscore = '$adjustedscore' WHERE athletes = 'athletes'";
And to update we use PDO update prepared statement
$stmt = $dbh->prepare($query);
$stmt->execute();
}

Select rows searching with an id in a column that contains multiple ids separated by a comma

I have a column in mysql db that contain multiple ids separated by a comma like so... 100,112,324 . The column is defined as varchar.
I want to find those rows whose ids column contains the id 112 or some other id that I specify. Similar questions I have found suggest splitting up the values in the column using lengthy code. Maybe I'm wrong but I would think there is a cleaner approach. Here is what I'm attempting to do, any help is appreciated...
<?php
include "../connect.php";
$usrid = "%112%";
$stm = $conn->prepare("SELECT * FROM subjects WHERE ids LIKE ?");
$stm->execute($usrid);
while($row = $stm->fetch(PDO::FETCH_ASSOC)) {
echo $row['consultant']."<br>";
}
?>
I get a blank page as is.
Look at this PDO prepared statement:
Try putting the "to be binded variable" in an array:
$stm->execute(array($usrid));
use single quotes for LIKE query, because you have data type as varchar.
Try this:
$stm = $conn->prepare("SELECT * FROM subjects WHERE ids LIKE '?'");
$stm->execute($usrid);

MYSQL Statement with Array Variable

So I have the following mysql statement saving to an array:
$sql = "SELECT did FROM did WHERE id = '$did_id'";
$result = mysqli_query($link, $sql, MYSQLI_STORE_RESULT);
while($row = $result->fetch_row()){
$did[] = $row;
}
That part works great. But now I need to take the values in the $did array and perform another lookup using the values in it. The way it works is we have users assigned to certain did's. So I find the did's that the user is assigned to (the $did array) and only show them results from another table based on those did values. I have no idea how this part works, but this is what my next statement needs to do:
SELECT * FROM log WHERE did_id = "the values in $did array"
Hope someone can help. I really appreciate it. I haven't really been able to find anything on it.
You can use php's join with mysql's IN to make comma separated strings you can also use implode , join() is an alias of implode();
SELECT * FROM log WHERE did_id IN( ".join(',',$did).")
One thing to mention here that your $did should contains ids in manner like
array("1","2","3"....)
So in your loop fetch first index that holds did column value
$did[] = $row[0];
Note: i assume did , did_id type is int or bigint

Avoiding a query inside a loop in my situation

I have quite a complicated situation here. I can't find a better way to solve this without putting a SELECT query inside a loop that rolls over 70000 times when I enter that page (don't worry, I use array_chunk to split the array into pages). I guess this would be a resource killer if I use a query here. Because of this, here I am, asking a question.
I have this big array I need to loop on:
$images = scandir($imgit_root_path . '/' . IMAGES_PATH);
$indexhtm = array_search('index.htm', $images);
unset($images[0], $images[1], $images[$indexhtm]);
Now I have an array with all file names of the files (images) in my IMAGES_PATH. Now the problem comes here:
Some of these images are registered on the database, because registered users have their images listed on my database. Now I need to retrieve the user_id based on the image name that the array above gives me.
Inside a loop I simply did this:
foreach ($images as $image_name)
{
$query = $db->prepare('SELECT user_id FROM imgit_images WHERE image_name = :name');
$query->bindValue(':name', $image_name, PDO::PARAM_STR);
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC);
$user_id = $row['user_id'];
echo $user_id;
}
This works just fine, but the efficiency equals to 0. Using that user_id I plan on getting other stuff from the imgit_users table, such as username, which would require another query inside that loop.
This is too much and I need a simpler way to deal with this.
Is there a way to get those user_ids before going inside the loop and use them IN the loop?
This is the table structure from imgit_images:
While this is the schema for imgit_users:
Something like this would work (I'm not sure if it's possible to prepare the WHERE IN query since the # of values is unknown... Else, make sure you sanatize $images):
$image_names = "'".implode("', '", $images)."'";
$query = $db->prepare("SELECT img.user_id, image_name, username
FROM imgit_images img
INNER JOIN imgit_users u ON u.user_id = img.user_id
WHERE image_name IN(".$image_names.")");
$query->execute();
while($row = $query->fetch(PDO::FETCH_ASSOC))
{
echo $row['user_id']."'s image is ".$row['image_name'];
}
You might need to tweak it a little (haven't tested it), but you seem to be able to, so I'm not worried!
Not sure if it is going to help, but I see a couple of optimizations that may be possible:
Prepare the query outside the loop, and rebound/execute/get result within the loop. If query preparation is expensive, you may be saving quite a bit of time.
You can pass an array as in Passing an array to a query using a WHERE clause and obtain the image and user id, that way you may be able to fragment your query into a smaller number of queries.
Can you not just use an INNER JOIN in your query, this way each iteration of the loop will return details of the corresponding user with it. Change your query to something like (i'm making assumptions as to the structure of your tables here):
SELECT imgit_users.user_id
,imgit_users.username
,imgit_users.other_column_and_so_on
FROM imgit_images
INNER JOIN imgit_users ON imgit_users.user_id = imgit_images.user_id
WHERE imgit_images.image_name = :name
This obviously doesn't avoid the need for a loop (you could probably use string concatenation to build up the IN part of your where clause, but you'd probably use a join here anyway) but it would return the user's information on each iteration and prevent the need for further iterations to get the user's info.
PDO makes writing your query securely a cinch.
$placeholders = implode(',', array_fill(0, count($images), '?'));
$sql = "SELECT u.username
FROM imgit_images i
INNER JOIN imgit_users u ON i.user_id = u.id
WHERE i.image_name IN ({$placeholders})";
$stmt = $db->prepare($sql);
$stmt->execute($images);
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
// use $row['username']
}
Create a string of comma separated ?s and write them into IN's parentheses. Then pass the array of images to execute(). Easily done, and now all of your desired data is available in a single resultset from a single query. (Add additional columns to your query's SELECT clause as needed.)

How to query all fields in a row

I know this is very simple, but I haven't used PHP/MySQL in a while and I have been reading other threads/php website and can't seem to get it.
How can I query a single row from a MySQL Table and print out all of the fields that have data in them? I need to exclude the NULL fields, and only add those that have data to an html list.
To clarify, I would like to display the field data without specifying the field names, just for the reason that I have a lot of fields and will not know which ones will be NULL or not.
What you've outlined requires 4 basic steps:
Connect to the database.
Query for a specific row.
Remove the null values from the result.
Create the html.
Step 1 is quite environment specific, so that we can safely skip here.
Step 2 - SQL
SELECT * from <tablename> WHERE <condition isolating single row>
Step 3 - PHP (assuming that $query represents the executed db query)
//convert the result to an array
$result_array = mysql_fetch_array($query);
//remove null values from the result array
$result_array = array_filter($result_array, 'strlen');
Step 4 - PHP
foreach ($result_array as $key => $value)
{
echo $value \n;
}
Just SELECT * FROM table_name WHERE.... will do the trick.
To grab data from specific fields, it would be SELECT field_1,field_2,field_3....
you have to make a string which represent mysql query. Then there is function in php named mysql_query(). Call this function with above string as parameter. It will return you all results. Here are some examples
You need to do it like this...
First connect to your sql... Reference
Now make a query and assign it to a variable...
$query = mysqli_query($connect, "SELECT column_name1, column_name2 FROM tablename");
If you want to retrieve a single row use LIMIT 1
$query = mysqli_query($connect, "SELECT column_name1, column_name2 FROM tablename LIMIT 1");
If you want to fetch all the columns just use * instead of column names and if you want to leave some rows where specific column data is blank you can do it like this
$query = mysqli_query($connect, "SELECT * FROM tablename WHERE column_name4 !=''");
Now fetch the array out of it and loop through the array like this..
while($show_rows = mysqli_fetch_array($query)) {
echo $show_rows['column_name1'];
echo $show_rows['column_name2'];
}
If you don't want to include the column names in the while loop, you could do this:
while($show_rows = mysqli_fetch_array($query)) {
foreach( $show_rows as $key => $val )
{
echo $show_rows[$key];
}
}

Categories