pdo select row by number - php

Trying to change over to PDO, and I am missing something simple?
OLD WAY
$query="SELECT * FROM database"
$result=mysql_query($query);
$data=mysql_result($result, 2, "value");
This gets me a value from row 3, using PDO the only way I can figure is:
$result->setFetchMode(PDO::FETCH_ASSOC)
$row = $result->fetch();
$row = $result->fetch();
$row = $result->fetch();
$thisone = $row['value'];
This way seems silly and indirect, is there a better way to select a row by it's number? I need the whole database queried for other variables, so changing the database SELECT statement won't work.

You can use fetchAll to get an array containing all rows. Then it's just a matter of grabbing the row you're looking for:
$rows = $result->fetchAll();
$third = $rows[2];
$value = $third['value'];

Related

I want to return an integer from a sql query not "Resource id #7"?

Just for now I am trying to output the value of the highest j_id row.
$result = mysql_query("SELECT max(`j_id` +1) FROM `journey`");
I'm also adding that 1 to j_id purposely.
It works fine within the phpmyadmin panel. But when I try to use it within any php script I get back resource id. I know that mysql_query() does not return an array, I've tried mysql_fetch_array($result) but that doesn't work.
Any help would be great?
$result = mysql_query("SELECT max(j_id +1) FROM journey");
$row = mysql_fetch_row($result);
$max_id_plus_one = $row[0];
$result is not the value you want - it contains it.
Note that the mysql extension is deprecated - you should move to mysqli or DBO.
Try this:
$result = mysql_query("SELECT max(j_id +1) as max_id FROM journey");
$row = mysql_fetch_assoc($result);
$max_id_plus_one = $row['max_id'];
you may try this
$result = mysql_query("SELECT max(j_id +1) as mid FROM journey");
$row = mysql_fetch_row($result);
$max_id_plus_one = $row['mid'];
See the Numeric Arrays AND Associative Arrays portion.
I think,Your Confusion will be clear...
mysql_fetch_array = Associative Arrays
mysql_fetch_row = Numeric Arrays
If you use mysql_fetch_array then see the column name from phpmyadmin, and get the data from array using that column name.
If you use mysql_fetch_row then get the data from $row[0].

How to print results in php using AVG and CHAR_LENGTH in MySQL Query

How do I show the results for $wordavg in php. I have done the query in SQL on database after taking out variables so I believe the query is correct but don't know how to show the results of the search in php.
$usertable = 'words';
$yourfield = 'wordname';
$query = "SELECT AVG(CHAR_LENGTH( wordname)) AS $wordavg FROM $usertable WHERE $yourfield LIKE '"."$current_letter"."%' ";
$result = mysql_query($query);
First, you should be using mysqli instead. Back to your question, usually you can iterate over a result with a loop as follows:
while ($row = mysql_fetch_assoc($result)) {
echo $row['field'];
}
More info and examples in the PHP mysql_query doc.
Since you only have one row of data to return, you don't need the loop part. You can simply use
$row = mysql_fetch_assoc($result);
$wordavg = $row['wordavg'];
You shouldn't have the $ in wordavg in your query. It should be just ...AS wordavg FROM...

Is there a more efficient way to express this query

I have a query for my mysql database but I just want to know if there is more of a simpler way of achieving something, here is my code:
$sql="SELECT value
FROM drivers
WHERE drivers_id = '$driver1' OR drivers_id = '$driver2' OR drivers_id = '$driver3'";
$result = mysql_query($sql);
$i = 1;
while ($row = mysql_fetch_assoc($result)) {
${'value'.$i} = $row['value'];
$i++;
}
This is how I want my code as it is shorter, but the problem I am having is that I need to know that where the $driver1 variable is found in the database the data retrieved for that is placed inside the value1 variable, and the retrieved information for $driver2 is placed inside $value2. However it grabs the data from the database in the order that it comes across the matches. I don't want to have to write 3 different queries for this because I am sure it can be done in one.
$sql="SELECT drivers_id, value FROM drivers WHERE drivers_id IN ('$driver1','$driver2','$driver3')";
$result=mysql_query($sql);
while($row = mysql_fetch_assoc($result)) {
${'value_for_'.$row['drivers_id']}=$row['value'];
}
Boom.
Though personally, instead of on-the-fly variables, I'd use an array w/ the id's as keys:
...
$resultArray = array();
while($row = mysql_fetch_assoc($result)) {
$resultArray[$row['drivers_id']]=$row['value'];
}
If you want to change the order of the results, you can add an order by clause to the query:
$sql = "SELECT drivers_id, value FROM drivers WHERE drivers_id IN ('$driver1','$driver2','$driver3') ORDER BY drivers_id";
...

PHP Zend - Execute to get a rowset and total number of records

I encounter some problem where i want to execute a SQL statement and get the total number of records + all the records.
$strSQL = "SELECT * FROM table WHERE ProjectID = 1 ";
$stmt = $db->query($strSQL);
$total = count($stmt->fetchAll());
while ($row = $stmt->fetch()){
..No More Record Shown here..
}
but there is no more record in the while loop after i execute fetchAll, i believe I need to get back to the first row or something, anyone know how to fix this?
You've already fetched all the records with fetchAll(). So when you call fetch(), there are no more records to read. Try storing the return value of fetchAll() in a variable and iterating through that. Something like this:
$strSQL = "SELECT * FROM table WHERE ProjectID = 1";
$stmt = $db->query($strSQL);
$allRows = $stmt->fetchAll();
$total = count($allRows);
foreach ($allRows as $row){
// process each $row
}

PHP - Select a unique mysql line without while [duplicate]

This question already has answers here:
Single result from database using mysqli
(6 answers)
Closed 6 months ago.
I want to select only unique values with php/mysql.
I can do it with many line, but I forget how to do it without while... :)
Thanks a lot.
Here is the code that I want to do without while.
$request_1m = "SELECT date1, date2 from mytable";
$result_1m = mysql_query($request_1m,$db);
while($row = mysql_fetch_array($result_1m))
{
/* Get the data from the query result */
$date1_1m = $row["date1"];
$date2_1m = $row["date2"];
}
mysql_fetch_assoc + SELECT with DISTINCT
I'm not sure I understand your question, but here's what I think you want to do :
$request_1m = "SELECT date1, date2 from mytable";
$result_1m = mysql_query($request_1m,$db);
list($date1_1m, $date2_1m) = mysql_fetch_row($result_1m);
Note that this will only get the first row from the result set (just as if you LIMIT 1)
like this?
$dbresult = mysql_query("SELECT DISTINCT field FROM table");
$result = array();
while ($row = mysql_fetch_assoc($dbresult))
{
$result[] = $row;
}
This gets you all unique values from "field" in table "table".
If you really wish to avoid the while loop, you can use the PHP PDO objects, and in particular call the PDO fetchAll() method to retrieve the complete results array in one go. PDO fetchAll() documentation
$db = new PDO('dblib:host=your_hostname;otherparams...');
$db->query("SELECT DISTINCT col FROM table");
$results = $db->fetchAll();
// All your result rows are now in $results
Heres how I do it and Json encode after. This will ensure it will encode only UNIQUE json Values (Without duplicates) as an example
$tbl_nm = "POS_P";
$prod_cat = "prod_cat";
//Select from the POS_P Table the Unique Product Categories using the DISTINCT syntax
$sql = "SELECT DISTINCT $prod_cat FROM $tbl_nm";
//Store the SQL query into the products variable below.
$products = mysql_query($sql);
if ($products){
// Create an array
$rows = array();
// Fetch and populate array
while($row = mysql_fetch_assoc($products)) {
$rows[]=$row;
}
// Convert array to json format
$json = json_encode(array('Categories'=>$rows));
echo $json;
}
//Close db connection when done
mysql_close($con);
?>
That is very easy, take out the while, like below
$row = mysqli_fetch_assoc($result);
$date1_1m = $row["date1"];

Categories