I want to create an array from a database query. I want to select 10 random questions by their ID, and put them into an Array, JUST the ID, i do not want it to be like [0]=>array('1'),[1]=>array('2'), I would like to to simply be, array('1','2','3') etc.
After they are in the array i would like to be able to check if the id is in the array
If u use the PDO php extension, use the http://www.php.net/manual/en/pdostatement.fetchcolumn.php to retrieve the values of the column as one-dim array.
try {
$pdo = new PDO([dsn], [username], [password]);
$sql = "
SELECT ID
FROM [tablename]
ORDER BY RAND()
LIMIT 10
";
$statement = $pdo->prepare($sql);
if (!$statement) {
//error handling here
}
$result = $statement->execute();
if (!$result) {
//error handling here
$array = array();
while (list($id) = $statement->fetch(PDO::FETCH_NUM)) {
$array[] = $id;
}
$statement = NULL;
} catch (PDOException $e) {
//error handling here
}
This should leave an enumerated array of the ID's
Related
Ive used two queried in a function. FIrst query to find an array of data. And second query is to select rows as per checking the array data from the first query. But the overall function return only one row data.
function getCartItems($conn)
{
$cust_id=$_SESSION['cust_id'];
$stmtSelect1 = $conn->prepare("SELECT product_id FROM tbl_cart WHERE cust_id=cust_id");
$stmtSelect1->bindParam('cust_id',$cust_id);
$stmtSelect1->execute();
$product_id= $stmtSelect1->fetchAll();
foreach($product_id as $productid) {
$stmtfetch = $conn->prepare("SELECT * FROM tbl_item WHERE product_id=:products_id");
$stmtfetch->bindParam(':products_id',$productid['product_id']);
$stmtfetch->execute();
$datas = $stmtfetch->fetchAll();
print_r($datas);
exit();
}
}
First of all, your code has typos (Missing ":" before parameter, product_id/products_id).
This should work:
$cust_id=$_SESSION['cust_id'];
$stmt = $conn->prepare("SELECT tbl_item.* FROM tbl_cart, tbl_item WHERE tbl_cart.cust_id = :cust_id AND tbl_item.product_id = tbl_cart.product_id);
$stmt->bindParam('cust_id',$cust_id);
$stmt->execute();
$rows = $stmt->fetchAll();
foreach($rows as $row)
{
print_r($row);
}
I don't know why my code doesn't return true, the while loop works fine, but there's a problem.
$PDO_result = $db_PDO->prepare("SELECT * FROM nnm_anime INNER JOIN nnm_anime_info ON nnm_anime.a_id = nnm_anime_info.a_id WHERE a_name LIKE '?%' ");
$PDO_result->bindParam(1, $pismenka[$i]);
$PDO_result->execute();
Here when I var_dump() $PDO_result I get one item in array so the following while loop should work:
while($row = $PDO_result->fetch(PDO::FETCH_ASSOC))
but it doesn't.
Working MySQLi:
$result = mysqli_query($connect_to_db, "SELECT * FROM nnm_anime INNER JOIN nnm_anime_info ON nnm_anime.a_id = nnm_anime_info.a_id WHERE a_name LIKE '$pismenka[$i]%' ");
while($row = mysqli_fetch_array($result))
The most simple solution would be to change $pdo->fetch(PDO::FETCH_ASSOC) to $pdo->fetchAll(PDO::FETCH_ASSOC)
fetchAll returns ALL rows in the requested query, while fetch only gets 1 row (the first)
Example:
<?php
try {
$PDO_result = $db_PDO->prepare("SELECT * FROM nnm_anime INNER JOIN nnm_anime_info ON nnm_anime.a_id = nnm_anime_info.a_id WHERE a_name LIKE ?");
//Execute by inserting an array:
if (!$PDO_result->execute([$pismenka[$i] . "%" ])) { //Added ."%"
die('Error!');
}
//Fetch rows:
$rows = $PDO_result->fetchAll(PDO::FETCH_ASSOC);
//Go trough each row:
foreach ($rows as $row) {
//Do something
}
//Catch exceptions thrown by PDO
} catch (PDOException $ex) {
print_r($ex);
}
I am looking for how to insert multiple records from a SQL table into a session variable, or into multiple unique session variables.
$userID = $_SESSION['user']['id'];
$coursequery = "
SELECT
coursename,
location,
description
FROM courses
WHERE
teacherID = '$userID'
";
try
{
$stmt = $db->prepare($coursequery);
$result = $stmt->execute();
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$row = $stmt->fetch();
$_SESSION['courseinfo'] = $row;
The table "courses" has a few records inside, all with the teacherID being that of the current userID, defined at the start. When I print_r($_SESSION['courseinfo']); it only displays one of the records in the table.
I'm trying to create a loop that displays all the information grabbed, for each record, since you won't know for sure how many records you'll grab at any given time. Any answers are greatly appreciated!
$userID = $_SESSION['user']['id'];
$coursequery = "
SELECT
coursename,
location,
description
FROM courses
WHERE
teacherID = '$userID'
";
try
{
$stmt = $db->prepare($coursequery);
$result = $stmt->execute();
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
while ($row = $stmt->fetch()):
$row['YourColumn'];
endwhile;
Use while() loop to fetch all record as per your query
You can fetch all your records with changing the fetch -> fetchAll() doc
$rows = $stmt->fetchAll();
Sessions can also store arrays and objects (they get serialized automatically). So you can just store the whole results set there.
$_SESSION['courseinfo'] = $rows;
Side note: Consider using another storage place for all of the returned data, if its a lot, and in the session store only Ids.
I have the weirdest issue going on. COUNT() is not working from inside my PHP code, but it is working in the SQL input space in the PHPMyAdmin database. For example if I use the following query:
SELECT COUNT(*) FROM posts WHERE category = "coding"
It will return the correct results from the SQL input in the PHPmyadmin part, but from the PHP code it will always return 1. Here is the code I am using for the PHP:
function numberofposts($category, $connection) {
$query = "SELECT COUNT(*) FROM posts WHERE category = :category";
$params = array(':category' => $category);
try{
$stmt = $connection->prepare($query);
$result = $stmt->execute($params);
}
catch(PDOException $ex){
echo ("Failed to run query: " . $ex->getMessage());
}
return $result;
}
echo "Number of Posts: " . numberofposts("art", $connection);
What it is doing is in the first code at the top it will return the correct results, but in the PHP code it is always returning 1. Is there a problem with me PHP? Please just post if you do not understand what I am asking, or if you would like more information.
You are doing a select and you execute the statement, but you are not fetching the row with the results.
You probably want something like:
function numberofposts($category, $connection) {
$query = "SELECT COUNT(*) as cnt FROM posts WHERE category = :category";
^^^ for easy access
$params = array(':category' => $category);
try{
$stmt = $connection->prepare($query);
$stmt->execute($params);
$row = $stmt->fetch();
}
catch(PDOException $ex){
echo ("Failed to run query: " . $ex->getMessage());
}
return $row['cnt'];
// if you don't alias the column you can do:
// return $row[0];
}
I will pass the query into this function query("SELECT * FROM table_name");
And the function is
public function query($sql) {
$resource = mysql_query($sql, $this->link_web);
if ($resource) {
if (is_resource($resource)) {
$i = 0;
$data = array();
while ($result = mysql_fetch_assoc($resource)) {
$data[$i] = $result;
$i++;
}
mysql_free_result($resource);
$query = new stdClass();
$query->row = isset($data[0]) ? $data[0] : array();
$query->rows = $data;
$query->num_rows = $i;
unset($data);
return $query;
} else {
return true;
}
} else {
trigger_error('Error: ' . mysql_error($this->link_web) . '<br />Error No: ' . mysql_errno($this->link_web) . '<br />' . $sql);
exit();
}
}
I want to add tenent_id = '1' in SELECT query also for INSERT query. Likewise I need to do it for UPDATE.
I want to bring the query like this
SELECT * FROM table_name WHERE tenent_id = 1 and user_id = 1
INSERT INTO table_name('tenant_id, user_id') VALUE('1','1')
UPDATE table_name SET user_id = 1 WHERE tenant_id = '1'
Can anyone give me the idea about how to insert tenant_id in select, insert and update
Thanks in advance
It's better practice to use the correct mysql functions rather than just a query function.
For example, if you want to cycle through many items in a database, you can use a while loop:
$query = mysql_query("SELECT * FROM table WHERE type='2'");
while($row = mysql_fetch_array($query)){
echo $line['id'];
}
This would echo all the IDs in the database that have the type 2.
The same principle is when you have an object, using mysql functions, you can specify how you want the data to return. Above I returned it in an array. Here I am going to return a single row as an object:
$query = mysql_query("SELECT * FROM table WHERE id='1'");
$object = mysql_fetch_object($query);
echo $object->id;
echo $object->type;
echo $object->*ANY COLUMN*;
This would return as:
1.
2.
Whatever the value for that column is.
To insert your data, you don't need to do "query()". You can simple use mysql_query($sql).
It will make life much easier further down the road.
Also, its best to run one query in a function, that way you can handle the data properly.
mysql_query("INSERT...");
mysql_query("UPDATE...");
mysql_query("SELECT...");
Hope this helps.
The simple answer is: just add the condition to your query. Call query("SELECT * FROM table_name WHERE tenant_id = 1 and user_id = 1").
If you're concerned about escaping the parameters you pass to the SQL query (which you should be!), you can either do it yourself manually, e.g.
$query = sprintf("SELECT * FROM table_name WHERE tenant_id = %d", intval($tenant_id));
query($query);
Or better use prepared statement offered by mysqli extension (mysql_query is deprecated anyway):
$stmt = $mysqli->prepare("SELECT * FROM table_name WHERE tenant_id = ?");
$stmt->bind_param("i", $tenant_id);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
// ...
}
If I still haven't answered your question, you can use a library to handle your queries, such as dibi:
$result = dibi::query('SELECT * FROM [table_name] WHERE [tenant_id] = %i', $id);
$rows = $result->fetchAll(); // all rows
The last option is what I would use, you don't need to write your own query-handling functions and get query parameter binding for free. In your case, you may utilize building the query gradually, so that the WHERE condition is not part of your basic query:
$query[] = 'SELECT * FROM table_name';
if ($tenant_id){
array_push($query, 'WHERE tenant_id=%d', $tenant_id);
}
$result = dibi::query($query);