I'm trying to get specific columns from a database table rather than selecting the whole table and put them to json format. There's no need for irrelevant columns. This is what i have so far.
$sql = "SELECT (col1,col2,col3) FROM table1";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);
mysqli_close($connection);
This code returns with an error: Operand should contain 1 column(s)
Any ideas what I'm doing wrong?
Thanks
The error is with the query. You are selecting 3 columns but putting them in brackets () would project them as single column. Try -
SELECT col1,col2,col3 FROM table1
You can refer to this answer for details.
You have to specify column name when access query result.
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$sql = "SELECT col1,col2,col3 FROM table1";
$emparray = array();
$index = 0;
while($row =mysqli_fetch_assoc($result))
{
$emparray[$index][] = $row['col1'];
$emparray[$index][] = $row['col2'];
$emparray[$index][] = $row['col3'];
$index++;
}
echo json_encode($emparray);
mysqli_close($connection);
Related
I'm trying to use foreach loop, for showing my DB but I always get error. What I want is to print each row and column. My code is like this :
$sql = "SELECT a.*, b.klasifikasi FROM kl_stre as b
INNER JOIN data_latih as a
ON a.id_stres = b.id_stres
ORDER BY a.id_dl";
$result = mysqli_query($conn, $sql);
foreach ($result as $dt_train => $row_dt_train):
foreach ($row_dt_train as $attr => $attr_dt_train):
echo $result[$row_dt_train][$attr_dt_trian]; // this line is the problem
endforeach;
endforeach;
the error I get is
Warning: Illegal offset type in C:\xampp\htdocs\knn\array_db.php on line 43
Would you mind explaining what is wrong with this code and how to solve this problem ?
you need to first check your query
if (!$result) {
die('query is not correct'.mysqli_error($conn));//$con is your database connection paste it after $result = mysqli_query($conn, $sql);
}
after that fetch record and simply remove foreach and try to use while() loop
while ($row=mysqli_fetch_array($result)) {
echo $row['your database field name'];
}
your code will be
$sql = "SELECT a.*, b.klasifikasi FROM kl_stre as b
INNER JOIN data_latih as a
ON a.id_stres = b.id_stres
ORDER BY a.id_dl";
$result = mysqli_query($conn, $sql);
if (!$result) {
die('query is not correct'.mysqli_error($conn));
}
while ($row=mysqli_fetch_array($result)) {
echo $row['your database field name'];
}
i want fetch all users data but am getting only one user details, please help me to solve
$conn = mysqli_connect("localhost", "root", "", "bitmining");
$sql6="SELECT username FROM users";
if($result = mysqli_query($conn, $sql6)){
while ($row=mysqli_fetch_array($result)){
//Hashrate Data Fetch
$investedusername = $row['username'];
$sql3="SELECT sum(hashrate_amount) as total FROM buyhashrate WHERE invested_username='$investedusername'";
$result = mysqli_query($conn, $sql3);
$row = mysqli_fetch_assoc($result);
//Total Value of Hashrate
echo $row['total'] . " GH/s";
echo "<br />";
}
$result->close();
}
Your re-using the $result field, change your second reference to something like ...
$result1 = mysqli_query($conn, $sql3);
$row = mysqli_fetch_assoc($result1);
This will stop it reseting the value your using for your main loop in
while ($row=mysqli_fetch_array($result)){
You use the $result variable for both mysqli_query
$result = mysqli_query($conn, $sql3);
While other answers are right about your mistake, I want to give you a better solution.
Try to use a join like this:
$conn = mysqli_connect("localhost", "root", "", "bitmining");
$sql="SELECT SUM(hashrate_amount) AS total FROM users AS t1 LEFT JOIN buyhashrate AS t2 ON (t1.username=t2.invested_username) GROUP BY t1.username";
if($result = mysqli_query($conn, $sql)){
while ($row=mysqli_fetch_array($result)){
//Total Value of Hashrate
echo $row['total'] . " GH/s";
echo "<br />";
}
$result->close();
}
This way you do just one query from database. But using your method you have n+1 queries which n is the number of users. So for one hundred users there is 101 queries.
I have a problem with getting the right value after I counted the rows from a table. I searched on the web but didn't find an answer.
In the database i have a table with all the categories in it they all have an id, and i would like to count using this column.
I have this PHP code, it works but is there an other and better to get over this?
$sql2 = "SELECT COUNT(id) FROM categories";
$stmt2 = sqlsrv_query($conn, $sql2);
$res = sqlsrv_fetch_array($stmt2, SQLSRV_FETCH_ASSOC);
foreach($res as $row)
{
$rows = $row;
}
//if there are categories display them otherwise don't
if ($rows > 0)
{
$sql = "SELECT * FROM categories";
$stmt = sqlsrv_query($conn, $sql);
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
echo "<a href='#' class='cat_links'>" . $row['category_name'] . " - <font size='-1'>" . $row['category_description'] . "</font></a>";
}
}
else
{
echo "<p style='text-align: center'>No categories yet.</p>";
}
I think has to be a better way to convert the $stmt2 variable from a SQL resource to an actual number, or to convert the $res variable from an array to an number. If I try to echo the whole array using foreach, it will only print out the number of rows. This is why I use it to count the rows now.
I can't use the sqlsrv_num_rows function because I then get an error, or no answer.
I want to print out details from the database with a unique ID which is taken from the URL.
I've used the $_GET array to get the event ID from the URL, but how would i look up the details of that event in the SQL statement? I've attempted it below but i don't think it's right. When I run the code, the page comes up blank.
<?php
$eventID = clean_string($db_server, $_GET['eventid']);
$query = "SELECT eventname, eventimage, eventdate FROM events WHERE eventID=$eventID";
$result = mysqli_query($db_server, $query) or die(mysql_error($db_server));
if (!$result) die('Query failed: ' . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
}
mysqli_free_result($result);
?>
mysqli_query returns a mysqli_result object.
mysqli_fetch_array returns the result rows as both an associative or a numeric array.
TRY
// Numeric array
while($row = mysqli_fetch_array($result)){
echo $row[0];
echo $row[1];
//etc
}
// Associative array
while($row = mysqli_fetch_array($result)){
echo $row["eventname"];
echo $row["eventimage"];
//etc
}
I'm using the code below to return and echo an array. If I define mysqli_fetch_array($results, MYSQLI_BOTH) then my array is truncated by one result. The 1st result in the array drops off the list. If I remove the MYSQLI_BOTH then I get the results that I expect, but my hosting company (Dreamhost) throws this error:
Warning: mysqli_fetch_array() [function.mysqli-fetch-array]: The result type should be either MYSQLI_NUM, MYSQLI_ASSOC or MYSQLI_BOTH in /blah/blah/blah.co.uk/index.php on line 14
What I really want is to use mysqli_fetch_array($results, 0) so that I catch all of the results, but do not get this error message.
CODE:
$dbc = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname) or die('This is the die connect error');
$query = "SELECT DISTINCT continent FROM tour";
$result = mysqli_query($dbc, $query) or die('This is the die query error');
$row = mysqli_fetch_array($result, MYSQLI_BOTH); // was ($result, 0) to start at 0, now in error, starts at 1 missing results
while($row = mysqli_fetch_array($result)) {
echo '' . $row['continent'] . "<br />\n";
}
mysqli_close($dbc);
The difference in those parameters is only in how the array will be defined.
MYSQLI_NUM = Array items will use a numerical index key.
MYSQLI_ASSOC = Array items will use the column name as an index key.
MYSQLI_BOTH = Array items will be duplicated, with one having a numerical index key and one having the column name as an index key.
You're not losing results.
You are however fetching twice before outputting, which meant you were skipping a row... do it like this:
$query = "SELECT DISTINCT continent FROM tour";
$result = mysqli_query($dbc, $query) or die('This is the die query error');
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo '' . $row['continent'] . "<br />\n";
}
mysqli_close($dbc);
You are using distinct in your query. Ditinct return the unique records only. please check your database if you have multiple continents name in your table or not.
$query = "SELECT DISTINCT continent FROM tour";
$result = mysqli_query($dbc, $query) or die('This is the die query error');
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo '' . $row['continent'] . "<br />\n";
}
mysqli_close($dbc);