Get int value from single row in sqlite using php - php

I have an sqlite table called projects with columns path and count. I'm trying to retrieve the count value from the row that matches the unique path value. The path value was passed to this page as an $id variable.
My code is below. The $id variable was passed to the page correctly as I can echo the correct value. My issue is:
Trying to use a php variable in a query
Querying a single value as an integer
My current code is below.
<?php
$id = $_GET['id'];
$proj = $pdo->query("SELECT count FROM projects WHERE path =$id");
$count = $proj->fetch(PDO::FETCH_ASSOC);
?>
<?php for ($x = 1; $x <= $count; $x++): ?>

I have managed to get it working using a prepared statement.
<?php
$result = $pdo->prepare("SELECT * FROM projects WHERE path = ? LIMIT 1");
$result->execute(array($id));
$row = $result->fetchAll();
$value = $row[0];
?>
<?php for ($x = 1; $x <= $value['count']; $x++): ?>

Related

How to store a row into an array in PHP and echo out a certain value of the array?

I'm trying to query data from a row in a table, store the data into an array, and then echo out a certain value from the array. Here's the PHP:
$receiveuserdata = mysqli_query($connection, "SELECT * FROM s_users LIMIT 0,1");
$userdata = array();
$index = 0;
while ($row = mysqli_fetch_assoc($receiveuserdata)) {
$userdata[$index] = $row;
$index++;
};
I've tried using other posts related to this issue for help, but most are outdated. Here's my attempt to echo a value from the array:
<h3>Username: <?php echo $userdata[0]; ?></h3>
Am I using $receiveuserdata incorrectly?
To retrieve Single row
You are used to LIMIT 0,1 - so it will retrieve only one row
<?php
$receiveuserdata = mysqli_query($connection, "SELECT * FROM s_users LIMIT 0,1");
if (mysqli_num_rows($receiveuserdata) > 0)
{
$row = mysqli_fetch_assoc($receiveuserdata);
$username = $row['username'];
echo '<h3>Username: '.$username.'</h3>';
}
?>
To retrive multiple rows
<?php
$receiveuserdata = mysqli_query($connection, "SELECT * FROM s_users");
if (mysqli_num_rows($receiveuserdata) > 0)
{
while ($row = mysqli_fetch_assoc($receiveuserdata)) {
$username = $row['username'];
echo '<h3>Username: '.$username.'</h3>';
}
}
?>
$row contains the entire MySQL table row. Which means that $userdata[0] also contains a row (as an associative array). Using echo does not work with arrays. Instead you can use var_dump if you want to see what the row is or access the value you need directly: $userdata[0]['username'] (if you have a column name username)

how to grab the max from mysql columns and assign to php variable

It is giving me errors when I run this code, I want to grab the max of my columns then eventually add 1 to it. I want to be able to use new max after these operations are completed. I think my sytnax is wrong on the x = line
$sql2 = "SELECT max(order_number) from t_item_list
where template_item_id = '$id'"
$x = mysqli_fetch_array($sql2)
$newmax = $x +1;
You are forgetting to execute the query. Here's your fixed code:
$sql2 = "SELECT max(order_number) from t_item_list where template_item_id = '$id'";
// I assume here that you already have a database connection
$result = $connection->query($sql2);
$x = mysqli_fetch_array($result);
$newmax = $x +1;
Also, mysqli_fetch_array($result) will probably return you an array. You must retrieve the value according to it.

PDO Select Statement returns nothing (FETCH_ASSOC)

I'm trying to retrieve records from the mySQL-database but nothing gets selected. I'm using the below php function:
function printButton($conn){
$your_variable = 1;
$knappar = $conn->prepare('SELECT * FROM knappar WHERE pid < :parameter');
$knappar->bindParam(':parameter', $your_variable, PDO::PARAM_INT);
$knappar->execute();
//Loops boxes
$count = 1;
while ($row = $knappar->fetch(PDO::FETCH_ASSOC)) {
echo "<a href='#'><div class='box' id='div_item".$count."'>";
echo $row['header'];
echo $row['id'];
echo "</div></a>";
$count = $count + 1;
}
}
It works fine if I change "WHERE pid = 1" instead of the "< :parameter". What am I doing wrong?
I updated it to what it looks like now:
function printButton($conn){
$your_variable = 1;
$knappar = $conn->prepare('SELECT header FROM knappar WHERE pid < :parameter');
$knappar->bindParam(':parameter', $your_variable, PDO::PARAM_INT);
$knappar->execute();
//Loops boxes
$results = $knappar -> fetchAll(PDO::FETCH_ASSOC);
foreach ($results as $row){
echo $row['header'];
echo '<br />';
}
}
With above example, still no output. pid value is int(11) in the database and the value of all rows are 1.
$knappar -> fetch(PDO::FETCH_ASSOC) only fetches the next row of the result set. Use fetchAll to get the entire result set.
You could then iterate through the returned array with a foreach.
Granted, I'm not sure why it returns nothing rather than just the first row but give it a try.

using pagination to output array

this is my code
//select all the members id
$result = mysql_query("select id from member");
//create array of ids
$id = array();
// page is the number of my pagination numbering and its from 1 to 10
$dis = $page;// for example $page = 1
// $page get its value every time a user click my pagination numbering i.e $page = $_GET[page];
// guess you understand
while($u_id = mysql_fetch_assoc($result)){
//id is my field name
$id[] = $u_id[id];
}
echo $id[$dis];
my problem is that this above code works for only 4 records out of 10records. my question is, why is it not working outputin other ids when the array index is 4,5... and howw do i amke it work
secondly the echo part is just the test of my idea but what i wanted to do is to pass the return id to a function for query. please any help
Well not sure if this is your problem but you might want to correct this if its not just a type in your post:
while($u_id = mysql_fetch_assoc($result)){
$id[] = $u_id['id']; // this should be 'id' not $id
}
I think you want to have:
while($u_id = mysql_fetch_assoc($result)){
$id[] = $u_id['id']; // changed from $id inside brackets
}
For starters, as you're using mysql_fetch_assoc(), your $u_uid variable will not contain any numeric indices. In fact, it will only ever have an 'id' key so your while loop should really look like this
$id[] = $u_uid['id'];
This will build the $id array with every id in your member table which is probably not what you want. As you mention pagination, I expect you actually want something like this
$page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
$page = max(1, $page); // ensure page is 1 or greater
$rowCount = 5; // you can set this to whatever you want
$offset = ($page - 1) * $rowCount;
$result = mysql_query(sprintf('SELECT id FROM member ORDER BY id LIMIT %d, %d',
$offset, $rowCount));

PHP getting data from mysql database for the Query string variable

Here is what I would like to do; I am passing an encoded data as a query variable to my webpage, then in my php page, I am decoding the data and checking the same in my database. The code I am using is shown below:
<?php
// Get the ID from URL.
$id = ( isset($_GET["id"]) && !empty($_GET["id"]) ? $_GET["id"] : "");
// If "id" is not empty, proceed.
if(!empty($id)) {
$id = base64_decode($id);
global $wpdb;
$res = $wpdb->query("SELECT * FROM S_redirect WHERE source = ".$id);
$tot = count($res);
echo $tot . " records found.";
for( $i=0; $i<count($res); $i++) {
echo $res[$i]->id;
}
exit;
}
else {
echo "No ID";
exit;
}
?>
I have one record in my database. The above code correctly says "1 records found". I am not sure how to get the value of the field in that row. I have 3 columns, they are id, field1 and field2. The code "echo $res[$i]->id" returns nothing.
Please help
BTW, I am trying this in my Wordpress blog.
Thank you all for your suggestions. I tried your suggestions and here are my results:
$res = $wpdb->query("SELECT * FROM S_redirect WHERE source = ".$id);
$tot = count($res);
echo $tot . " records found."."</br>";
it says 1 records found.
$res = $wpdb->get_row("SELECT * FROM S_redirect WHERE source = ".$id);
$tot = count($res);
echo $tot . " records found."."</br>";
it says 0 records found.
$res = $wpdb->get_results("SELECT * FROM S_redirect WHERE source = ".$id);
$tot = count($res);
echo $tot . " records found."."</br>";
it says 0 records found.
while ($row = mysql_fetch_array($res)) {
echo $row[0];
}
If I use mysql_fetch_array,
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/myfolder/mytheme/index.php on line 38.
line 38 is while ($row = mysql_fetch_array($res)) {.
What I am trying to accomplish:
I have a wordpress blog. All the above code goes into my index.php. I will pass a product id to my index.php via query string variable. I have created a new table called S_redirect in my wordpress database. I will retrieve the value of query string variable id and check the same in my database table. If record exists, then retrieve one of the column value (url of the product) from that table row and redirect to that product url. If the record doesn't exists then redirect to home page. hope this helps everyone to understand what I am doing.
Judging by $wpdb, it looks like this is a WordPress. Hopefully this will help:
http://codex.wordpress.org/Function_Reference/wpdb_Class
Update
Don't use count() to get the number of rows; use $wpdb->num_rows (no () because it's a property, not a function). The count() function always returns 1 for any non-null value that it doesn't recognize as a "countable" value (i.e., arrays and certain objects), so it's likely your code will always yield 1.
$tot = $wpdb->num_rows;
=====
If you run your query with get_results() instead of query(), then you can loop through the results like this:
foreach ($res as $row) {
echo $row->id;
}
Ultimately, I think your code will end up looking like this:
$res = $wpdb->get_results("SELECT * FROM S_redirect WHERE source = ".$id);
$tot = $wpdb->num_rows;
echo $tot . " records found.";
foreach ($res as $row) {
echo $row->id;
}
Disclaimer: This is untested, as I've never used WordPress. This is just how I understand it from the documentation linked above. Hopefully it at least gets you on the right track.
Use:
$tot = count(mysql_fetch_array($res));
or
$tot = mysql_num_rows($res);
The best is
while($row = mysql_fetch_assoc($res)){
echo $row['column_name'];
}

Categories