I am trying to fetch user
function getItemName($dbh, $userId) {
$itemId = getItemId($dbh, $userId); // the getItemId() function works
echo "item id is: " . $itemId ; // because I can see the correct result if I echo it
$sql = "SELECT name FROM items WHERE id = :item_id";
$stm = $dbh->prepare($sql);
$stm->bindParam(':item_id', $itemId, PDO::PARAM_INT);
$stm->execute();
$result = $stm->fetch();
return $result['name'];
}
And I get Trying to access array offset on value of type bool on the return $result['name']; line.
The field name exists on the items table so that's not the issue.
Also, when I try to further test it, I change the $sql statement to SELECT * FROM items and then when I do echo $stm->rowCount() it finds the correct number of rows (With the original SQL statement row count is 0)
Can't find out what's causing this
I have 3 suggestions:
Make sure to convert $itemId to integer using intval();
Just before returning the function result validate that the query returned results.
$result = $stm->fetch();
if(!$result){
return null;
}
return $result['name'];
Finally, the more obvious, make sure the itemId you are looking for exists in the DB.
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);
}
So, I want to get a column to a variable.
I tried 2 methodes
mysql_query
and
mysql_fetch_array
At mysql_query I get Resource id #5.
And
At mysql_fetch_array I get array.Does some one knows how to fix this?
$res=mysql_query("SELECT * FROM users WHERE userId=".$_SESSION['user']);
$userRow=mysql_fetch_array($res);
Suppose you have column with name as 'firstname'. Then you can go with this
$res=mysql_query("SELECT * FROM users WHERE userId=".$_SESSION['user']);
$userRow=mysql_fetch_array($res);
$firstname = $userRow[0]['firstname'];
echo $firstname;
If you get multiple rows in result, you can get all rows by loop.
My understanding is that you want to call the column name from a table where the value of that column is equal to a variable? If so...
The easiest way I can think of to resolve this would be to so a search through all the tables for the value you look for based on columns and return the value. This function should help accomplish this task:
function columnToVariable($conn, $table, $variable){//SET PARAMETERS (CONNECTION STRING, TABLE NAME, VARIABLE SEARCH)
$sql = "SHOW COLUMNS FROM ".mysqli_real_escape_string($conn, $table).";"; // SQL STATEMENT
$result = $conn->query($sql); // RESULTS OF ALL ROWS
$field = array(); // ARRAY WITH COLUMNS
if($result->num_rows > 0){ // CHECK IF RESULTS FOUND
while($row = $result->fetch_assoc()){ // SET RESULTS TO ARRAY
array_push($field, $row['Field']); // APPEND ARRAY WITH FIELD NAME
}
}
foreach($field as $return){ // ITERATE THROUGH FIELD NAMES
$sql = "SELECT * FROM ".mysqli_real_escape_string($conn, $table)." WHERE ".mysqli_real_escape_string($conn, $return)." = '".mysqli_real_escape_string($conn, $variable)."';"; // SQL STRING
$result = $conn->query($sql); // QUERY RESULTS
if($result->num_rows > 0){ // IF FOUND, RETURN VALUE
return $return; // RETURN VALUE
}
}
}
I have a table in my database that has these fields:
-id
-video_title
-video_article
-video_category
Now, I'd like to query it by video_category and I have tried this code so far:
public function related_videos($current_video_category)
{
$sql = "SELECT * FROM English WHERE video_category = :current_video_category";
$stmt = $this->pdo->prepare($sql);
$result = $stmt->execute(array(":current_video_category" => $current_video_category));
$data = $stmt->fetch(PDO::FETCH_ASSOC);
return $data;
}
The problem is it returns the first occurrence only and I'm not sure how to return all the occurrences of $current_video_category at once.
Any help would be really appreciated.
You only fetch one row:
$data = $stmt->fetch(PDO::FETCH_ASSOC);
If you want to fetch all available rows from the statement, use fetchAll:
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
This returns an array where each element is a row from the query.
You need to put that fetch assoc in while loop to get all data
While($data = $stmt->fetch(PDO::FETCH_ASSOC)){
//process data here
}
I'm trying to print out the value of a query but what appears on the screen is the query itself!
mysql_select_db($database_databasestudents, $databasestudents);
$result = mysql_query("Select name from country where id = '$s';",$databasestudents);
$r = mysql_fetch_array($result) ;
echo $r;
where $s is an integer
This is what I get on the screen:
SELECT name FROM country WHERE id='3'
3 is the value of $s
You need to run the query first
http://www.php.net/manual/en/mysqli.query.php
and then loop though the results
http://www.php.net/manual/en/mysqli-result.fetch-array.php
You need to run the query in order to get the result. Maybe this will get you started:
$pdo = new PDO('mysql:host=YOURHOST;port=YOURPORT;dbname=YOURDB', 'YOURUSER', 'YOURPASSWORD');
$sql = 'SELECT name FROM `country` WHERE id=?';
$stmt = $pdo->prepare($sql);
$stmt->execute(array($s));
while ($result = $stmt->fetchObject())
{
echo $result->name;
}
$r is an array, not a string. You need print_r($r); or var_dump($r);, not echo
You have created a string containing your query.
You must instantiate a database connection and then execute your query.
i want to check the rows if there are any events that are binded to a host with host_id parameter, everything is well if there is not any events binded to a host, its printing out none, but if host is binded to one of the events, its not listing the events, but if i remove the codes that i pointed below with commenting problem starts here and problem ends here, it lists the events. I'm using the fetchAll function above too for another thing, there is not any such that error above there, but with the below part, it's not listing the events, how can i fix that?
Thanks
try
{
$eq = "SELECT * FROM `events` WHERE `host_id` = :id AND `confirmed` = '1' ";
$eq_check = $db->prepare($eq);
$eq_check->bindParam(':id', $id, PDO::PARAM_INT);
$eq_check->execute();
//problem starts here
$count3 = $eq_check->fetchAll();
$rowCount = count($count3);
if ($rowCount == 0)
{
echo "None";
}
//problem ends here
while($fetch = $eq_check->fetch (PDO::FETCH_ASSOC) )
{
$_loader = true;
$event_id = $fetch['event_id'];
$event_name = $fetch['event_name'];
$link = "https://www.mywebsite.com/e/$event_id";
echo "<a target=\"_blank\" href=\"$link\"><li>$event_name</li></a>";
}
}
catch(PDOException $e)
{
$log->logError($e." - ".basename(__FILE__));
}
Thank you
You can't fetch twice without executing twice as well. If you want to not just re-use your $count3 item, you can trigger closeCursor() followed by execute() again to fetch the set again.
To reuse your $count3 variable, change your while loop into: foreach($count3 as $fetch) {
The reason that it is not listing the events when you have your code is that the result set is already fetched using your fetchAll statement (The fetchAll doesn't leave anything to be fetched later with the fetch).
In this case, you might be better off running a select count(*) to get the number of rows, and then actually running your full query to loop through the results:
An example of this in PDO is here:
<?php
$sql = "SELECT COUNT(*) FROM fruit WHERE calories > 100";
if ($res = $conn->query($sql)) {
/* Check the number of rows that match the SELECT statement */
if ($res->fetchColumn() > 0) {
/* Issue the real SELECT statement and work with the results */
$sql = "SELECT name FROM fruit WHERE calories > 100";
foreach ($conn->query($sql) as $row) {
print "Name: " . $row['NAME'] . "\n";
}
}
/* No rows matched -- do something else */
else {
print "No rows matched the query.";
}
}
$res = null;
$conn = null;
?>
Note that you cannot directly use rowCount to get a count of rows selected - it is meant to show the number of rows deleted and the like instead.