I have two php files. They each have a different query in them. Both of them work. Then I have one file where I include both files inside of it. The queries work on their individual pages, but in the page where they are both included only the first query works. They look something like this (The first one uses * because I pull out every row)
include 'connect.php';
$query = "SELECT * FROM table ORDER by jid DESC";
$ex = $mysqli->query($query) or die(mysqli_error());
$row_cnt = mysqli_num_rows($ex);
if ($row_cnt > 0) {
/* fetch associative array */
while ($row = $ex->fetch_assoc()) {
echo $row["one"] . $row["two"] . $row["three"] . $row["four"];
}
$result->free();
}
$mysqli->close($mysqli);
The second one is like this
include 'connect.php';
$q = "SELECT one, three FROM table ORDER by jid DESC";
$d = $mysqli->query($q) or die(mysqli_error());
$row_cnt = mysqli_num_rows($d);
if ($row_cnt > 0) {
/* fetch associative array */
while ($row = $d->fetch_assoc()) {
echo $row["one"] . $row["three"];
}
$result->free();
}
$mysqli->close($mysqli);
Then the file that includes them is just two includes like include ' ';
How do I get both queries to work on the one page?
add value in array, like this:
include 'connect.php';
$q = "SELECT one, three FROM jokes ORDER by jid DESC";
$d = $mysqli->query($q) or die(mysqli_error());
$row_cnt = mysqli_num_rows($d);
$values = array();
if ($row_cnt > 0) {
/* fetch associative array */
while ($row = $d->fetch_assoc()) {
$values[0][] = $row["one"];
$values[1][] = $row["two"];
$values[2][] = $row["three"];
$values[3][] = $row["four"];
}
$result->free();
}
$mysqli->close($mysqli);
... after, use foreach for print the value
I have not tested
How do I get both queries to work on the one page?
Just run them one after another like everyone does.
If something goes wrong - debug your code, like everyone does. Read all the error messages and act accordingly.
Related
/* To sort the id and limit the post by 40 */
$sql = "SELECT * FROM requests";
$result = $conn->query($sql);
$sqlall= "SELECT * FROM requests ";
$resultall = $conn->query($sqlall);
$i = 0;
if ($result->num_rows > 0) {
// Output data of each row
$idarray= array();
while($row = $result->fetch_assoc()) {
echo "<br>";
// Create an array to store the
// id of the blogs
array_push($idarray,$row['id']);
}
}
else {
echo "0 results";
}
?>
<?php
for($x = 1; $x < 40; $x++) {
// This is the loop to display all the stored blog posts
if(isset($x)) {
$query = mysqli_query(
$conn,"SELECT * FROM `requests`");
$res = mysqli_fetch_array($query);
$email1 = $res['email1'];
$msg1= $res['msg1'];
$subject1 = $res['subject1'];
$name1 = $res['name1'];
$id = $res['id'];
the output is 40 cards reading data from the first row in my database. can anyone help?
I'm using xampp.
This code is to show the loop, but if anyone wants the full code is here
You are storing all the IDs in the array $idarray, but then you don't really use them properly. You loop over them, but you just run SELECT * FROM requests` 40 more times, and always extract the same first row. You never use the ID to change the query.
But it really makes no sense to run lots of separate queries anyway. If you just want the first 40 rows then use MySQL's LIMIT keyword. It usually works best when combined with ORDER BY as well. Something like this:
$sql = "SELECT * FROM requests ORDER BY id LIMIT 40";
$result = $conn->query($sql);
while ($res = $result->fetch_assoc()) {
$email1 = $res['email1'];
$msg1 = $res['msg1'];
$subject1 = $res['subject1'];
$name1 = $res['name1'];
$id = $res['id'];
//example output, just for demo:
echo $email1." ".$msg1." ".$subject1." ".$name1." ".$id;
}
Documentation: https://dev.mysql.com/doc/refman/8.0/en/limit-optimization.html
I'm not sure if this is doable or not, and I'm not entirely sure how to search for this. I have several dynamic web pages that all link to the same MySQL database table, but pull different results. So for example, a dynamic web page with ID = 5 will run a query like:
SELECT * FROM myTable WHERE category1 = 1
The web page where ID = 7 will run:
SELECT * FROM myTable WHERE category2 = 1
And so on. The queries are all grabbing the data from the same table, but the WHERE clause is different for each query - its not looking at the same column. The page with ID 7 should ONLY be returning results where category2 = 1, and ignoring the results that would be returned for the page with id = 5. My website has about 20 different pages/queries like this which is why I'm looking to see if it can be done in a function instead.
Is there a way I can put that into a function, and if so, how would I set up the parameters correctly? Or is this an instance where I will have to just write out all the queries separately on each page?
function find_results(what to put here?) {
global $connection;
$query = "SELECT * FROM myTable WHERE (how to code this part?)";
$result = mysqli_query($connection, $query);
confirm_query ($result);
return $result;
}
You would add the necessary parameters to your functions argument list, then provide the values at runtime.
function find_results($column, $value)
{
global $connection;
$query = "SELECT * FROM myTable WHERE {$column} = $value";
$result = mysqli_query($connection, $query);
confirm_query ($result);
return $result;
}
//Usage:
$result = find_results("category2", 1)
If the value you are returning records by ever ends up being a string make sure your wrap $value in single quotes.
if its a constant relation between pageId and categoryId, you can just create an array to hold it indexed by pageId like:
$pageIdToCategoryMapping = [
1 => 'cateogory1',
2 => 'category5',
...
]
and then just use it to pass data to your function like
find_results($pageIdToCategoryMapping[$pageId])
function find_results($category) {
(...)
$query = "SELECT * FROM myTable WHERE ({$category} = 1)";
(...)
}
I have been using class and object methods for mysql operations. source code available in github
I would recommend you to pass array as an argument and can return query or result as array in format you required. And this function will work any number or condition
<?php
$arg['db']="database";
$arg['tabe']="table";
$arg['search']['id1']="id1";
$arg['search']['id2']="id2";
//
function searchAndReturnResultAsArray($arg)
{
$return = NULL;
$query="SELECT * FROM ".$arg['table'];
$flag=false;
foreach($arg['search'] as $key=>$value)
{
if($flag)
$query.=" AND ";
else
$flag=true;
$query.= $key." = '".$value."' ";
}
$row = mysqli_num_rows($query);
$field = mysqli_fetch_object($query);
if($row >= 1)
{
while($data = mysqli_fetch_array())
{
$return[] = $data;
}
}
return $return;
}
?>
Or alternatively you can just return query once it is ready.
i would like to get the number of rows of a mysql database table with one single statement or a function
include "opendatabase.php"; //opens database
while (NUMBEROFROWS > 0){
//do something
}
the NUMBEROFROWS should be replaced with the statement that returns the number of rows
i already tried to create a function
function getRowNumber(){
$query = "SELECT COUNT(*) FROM `votes`";
$result = mysql_query($query, $connect);
list($length) = mysql_fetch_row($result);
return $length;
}
but it does not work if i dont put the include "opendatabase.php"; in it.
what am i doing wrong
$result = mysql_query("SELECT * FROM tablename");
if (mysql_num_rows($result) > 0) {
// rows found..
}
the problem is that include "opendatabase.php"; runs in another scope like described here
http://www.php.net/manual/en/language.variables.scope.php
there is a global $connect missing within the function
Here you go:
function num(){
$data = mysql_query("SELECT * FROM table");
if(mysql_num_rows($data) > 0){
while($row = mysql_fetch_assoc($data)){
// do something with your data..
}
}
}
would this work for you ?
function getRowNumber()
{
$query = "SELECT COUNT(*) as counts FROM `votes`";
$result = mysql_query($query, $connect);
$row = mysql_fetch_array($result);
$counts = $row['counts'];
return $counts;
}
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.
I am writing a web application in PHP which will store employee data and generate employee ID cards to PDF. I am using FPDF for creation of PDFs and that works fine. I am having a problem with showing results from MySQL database.
I have to generate PDF with 4 employee ID cards and I am not sure how to get them from the database. So far I am using LIMIT option in the query to get only 4 results and i will have an if statement based on mysql.php?id=1 id which will define the limit. It is a little messy but there are not going to be more than 80 employees.
This is my code:
$id = $_GET['id'];
if ($id == 1) {
$limit_start = 0;
$limit_end = 4;
}
$result=mysql_query("SELECT users.tajemnik, users.dateCreated, users.showmeID,
users.workerName, users.dateCreated, users.workerPlace, users.workerSID, uploads.userID, uploads.data, uploads.filetype
FROM users INNER JOIN uploads ON users.showmeID = uploads.userID ORDER BY workerName DESC LIMIT $limit_start, $limit_end") or die (mysql_error());
mysql_query("SET NAMES 'utf8'") or die('Spojení se nezdařilo');
while($row = mysql_fetch_array($result)){
$workerName = $row["workerName"];
$workerPlace = $row["workerPlace"];
$workerSID = $row["workerSID"];
$tajemnik = $row["tajemnik"];
$showmeID = $row["showmeID"];
$mysqldatetime = strtotime($row['dateCreated']);
$image = $row["data"];
$phpdatetime = date("d.m.Y",$mysqldatetime);
}
This will get me the first result from the query. I need to get information from all 4 rows and have them stored in variables like $workerName1, $workerName2 etc. I hope it makes sense what I am trying to do.
Thank you for your replies!
V.
I need to get variables like $workerName1, $workerName2 etc
Nope, you don't.
You actually need an array.
So, first, get yourself a function
function sqlArr($sql){
$ret = array();
$res = mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
if ($res) {
while($row = mysql_fetch_array($res)){
$ret[] = $row;
}
}
return $ret;
}
then write a code
mysql_query("SET NAMES 'utf8'") or die('Spojení se nezdařilo');
$sql = "SELECT users.tajemnik, users.dateCreated, users.showmeID, users.workerName,
users.dateCreated, users.workerPlace, users.workerSID, uploads.userID,
uploads.data, uploads.filetype
FROM users
INNER JOIN uploads ON users.showmeID = uploads.userID
ORDER BY workerName DESC LIMIT $limit_start, $limit_end";
$data = sqlArr($sql);
Now you have all your data in the $data array.
So, you can loop over it or access single values like
echo $data[0]['tajemnik'];
or
foreach($data as $row) {
//do whatever you want with database row
echo $row['tajemnik'];
}