This question already has answers here:
ErrorException : implode(): Passing glue string after array is deprecated. Swap the parameters
(6 answers)
Closed 4 months ago.
Please help,
i got error "Warning: join(): Invalid arguments passed in ... on line...".
Here is my code:
$query = "SELECT `id`, `kategori`, `sub_kategori` FROM `table` ORDER BY `id` DESC";
$stmt = $DB_con->prepare($query);
$stmt->execute();
$kategori = array();
if($stmt->rowCount()>0) {
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
$kategori = print($row['kategori']);
}
}else{
echo "Nothing here...";
}
join($kategori, ',');
I expect the output : Data,Data,Data,Data,Book,Book
but the actual output is "DataDataDataDataBookBook" anda error "Warning: join(): Invalid arguments passed in ... on line..."
Just append $row['kategori'] in each iteration and change the order of parameteres in join() or implode() call:
<?php
// Get data
$query = "SELECT `id`, `kategori`, `sub_kategori` FROM `table` ORDER BY `id` DESC";
$stmt = $DB_con->prepare($query);
$stmt->execute();
// Fetch data
$kategori = array();
if ($stmt->rowCount() > 0) {
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$kategori[] = $row['kategori'];
}
} else {
echo "Nothing here...";
}
// Output
echo implode(',', $kategori);
?>
An alternative to fetching a bunch of records and then joining them together would be to use GROUP_CONCAT() in mysql to do the work for you. Also as you are not binding anything - you can just call query(). Then you will have 1 row from the database with the content - so the last bit is to say if it's empty, then set the value to Nothing here... (done using ?:)
...
$query = "SELECT GROUP_CONCAT(`kategori`) as kategori
FROM `table`
ORDER BY `id` DESC";
$stmt = $DB_con->query($query);
$row=$stmt->fetch(PDO::FETCH_ASSOC);
$output = $row['kategori']?:"Nothing here...";
echo $output;
If you still need the individual data rows, then another alternative is to use PDO::FETCH_COLUMN and fetchAll() to return the results, then implode() as in the other solution...
$query = "SELECT `kategori`
FROM `table`
ORDER BY `id` DESC";
$stmt = $DB_con->query($query);
$kategori=$stmt->fetchAll(PDO::FETCH_COLUMN);
echo implode(',', $kategori)?:"Nothing here...";
Related
This question already has answers here:
How to solve PHP error 'Notice: Array to string conversion in...'
(6 answers)
Create PHP array from MySQL column
(12 answers)
Closed 2 years ago.
When I ran the following query in PHPMyAdmin, it returned the correct number of results. However when I try to echo the results in PHP, it only outputs one result, even when there is more thn one. How do I fix this so that every result is displayed?
$sql1 = "SELECT userFirstname FROM users WHERE userID IN (SELECT userID FROM note_editors WHERE noteID = (SELECT noteID FROM notes WHERE uniqueID = ?))";
$stmt1 = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt1, $sql1)) {
header("Location: note-premium.php?error=sql");
exit();
}
else {
mysqli_stmt_bind_param($stmt1, "s", $unique);
mysqli_stmt_execute($stmt1);
$result1 = mysqli_stmt_get_result($stmt1);
while ($row1 = mysqli_fetch_assoc($result1)) {
$names = $row1['userFirstname'];
}
}
echo($names);
Second attempt: I tried creating an array. But this just outputs the word array and the error message, "Notice: Array to string conversion". Why?
$sql1 = "SELECT userFirstname FROM users WHERE userID IN (SELECT userID FROM note_editors WHERE noteID = (SELECT noteID FROM notes WHERE uniqueID = ?))";
$stmt1 = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt1, $sql1)) {
header("Location: note-premium.php?error=sql");
exit();
}
else {
mysqli_stmt_bind_param($stmt1, "s", $unique);
mysqli_stmt_execute($stmt1);
$result1 = mysqli_stmt_get_result($stmt1);
$column = array();
while ($row1 = mysqli_fetch_assoc($result1)) {
$column[] = $row1['userFirstname'];
}
}
echo($column);
As you're looping through the results and storing the value of the column 'userFirstName' in $names, you're overwriting the previous value stored in it.
You've got two options - display the value as you're looping through the results, or store the value in an array and then display that afterwards.
Option 1 - display the value as you're looping through the results:
while ($row1 = mysqli_fetch_assoc($result1)) {
echo $row1['userFirstname'];
}
Option 2 - store the values in an array and display that after the loop
$names = [];
while ($row1 = mysqli_fetch_assoc($result1)) {
$names[] = $row1['userFirstname'];
}
foreach($names as $name) {
echo '<p>'.$name.'</p>';
}
Obviously you can customise how you want to loop through the array values and display them. I've wrapped each value in a <p> tag so that they display on a new line. If you just want to display the unformatted contents of the array, use print_r($names)
This question already has answers here:
SELECT COUNT(*) AS count - How to use this count
(5 answers)
Closed 1 year ago.
I'm trying to get the sum of a column from my database. When I try this code I get the error Undefined index: sum(col_1). How can I do this? I'm a real beginner so keep it a bit simple.
$sql = "SELECT * FROM table_1";
$run = mysqli_query($conn, $sql);
while($rows = mysqli_fetch_assoc($run)){
$col_ans[1] = $rows['sum(col_1)'];
echo $col_ans[1];
}
You can easily find sum of a column this way.
$sql = "SELECT sum(col_1) as col_1_sum FROM table_1";
$run = mysqli_query($conn, $sql);
while($rows = mysqli_fetch_assoc($run)){
echo $rows['col_1_sum'];
}
Your problem is that you didn't use the SUM() function inside your query, so you won't get any sum from the query
You can also try the following:
$query = "SELECT productName, SUM(productQty) AS 'Products Ordered'
FROM ctrlaproducttab
GROUP BY productName
";
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_assoc($result))
{
$productName = $row['productName'];
$itemsOrdered = $row['Products Ordered'];
}
Notice that we're giving an alias name Products Ordered to the result of expression SUM(productQty), and now we can use this alias name as an index in the associative array returned by mysqli_fetch_assoc()
This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 8 months ago.
I don't know what the problem is with this line or how to fix it, before was okay and now I'm getting this error:
mysqli_fetch_object() expects parameter 1 to be mysqli_result
Here is my PHP code:
<?php
}
if($_GET['action']=="user_info")
{
$userid = $_GET['user_id'];
$query = "SELECT * FROM user WHERE user_id ='{$userid}'";
$result = mysqli_query($link, $query);
$user = mysqli_fetch_object($result);
$queryt = "SELECT * FROM user_title WHERE id='".$user->title."'";
$resultt = mysqli_query($link, $queryt);
$rowt = mysqli_fetch_object($resultt);
$title = $rowt->name;
$sorgu = "select * from pub_author where user_id='$userid'";
$publications = mysqli_query($link, $sorgu);
while($a = mysqli_fetch_object($publications))
{
$ids .= $a->pub_id . ',';
}
$ids = rtrim($ids,",");
$sorgu2 = "select count(id) as total , year from publication where id IN ($ids)
GROUP BY YEAR(`year`) order by `year` ";
$publications2 = mysqli_query($link, $sorgu2);
while($a2 = mysqli_fetch_object($publications2))
{
$mount = explode('-', $a2->year);
$accyaz[$mount[0]] = $a2->total;
}
}
?>
As far as your exact error is concerned one of your query is failing, the following steps might help. Ofcourse you question looks duplicate but here are some of the things that addresses your question
Your first query should be like this, with no curly braces, ofcourse untill you have explicitly ids wrapped in curly braces in your table.
SELECT * FROM user WHERE user_id ='$userid'
Secondly you are executing multiple queries so you might wanna consider error checking if your query executes properly or not(because of syntax error columns mismatch table name mismatch many more possibilities): do error checking like this as for while($a...) part
if ($result=mysqli_query($link, $sorgu);)
{
while($a=mysqli_fetch_object($result))
{
$ids .= $a->pub_id . ',';
}
$sorgu2 = "select count(id) as total , year from publication where id IN ($ids) GROUP BY YEAR(`year`) order by `year` ";
//... Your further code
}
else
{
echo "Something went wrong while executing query :: $sorgu";
}
Third i see your are getting pub_id make a comma seperated list of it so that you can give it as a parameter in your last query which is a long shot, why not use sub query for you IN clause like this:
SELECT
COUNT(id) as total, year
FROM publication
where id
IN (
SELECT pub_id FROM pub_author WHERE user_id='$userid'
)
GROUP BY `year`
order by `year`;
The error you are stating translates to this: The query fails somehow, instead of running the mysqli_query($link, $sorgu); line echo $sorgu, go to phpmyadmin and test your query, if it is bad, fix it in phpmyadmin until it works and set it up in the code correctly
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
How do i “echo” a “Resource id #6” from a MySql response in PHP?
I am looking for the result out of a query, but it keeps giving me resource id #3.
The following is my code.
$type = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$typeResult = mysql_query($type);
print_r($typeResult);
What step am I missing here?
You need to fetch the result. All you're doing is sending the query.
Be aware that if you are writing new code, you should use mysqli_ or PDO functions as your query is vulnerable to SQL injection and mysql_ functions are being deprecated. Hesitantly, below is a sample for mysql_fetch_assoc.
<?php
$sql = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$result = mysql_query($sql);
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
// then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
echo $row[sellingid];
}
mysql_free_result($result);
?>
Reference
$type = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$typeResult = mysql_query($type);
$row = mysql_fetch_array($typeResult);
print_r($row);
More clear hint - use MySQLi class/functions, read this:
http://lt1.php.net/manual/en/mysqli-result.fetch-assoc.php
or if you like OOP approach more then
http://lt1.php.net/manual/en/mysqli-result.fetch-object.php
You are not actually fetching the results of your query. Below are two examples that use WHILE loops to fetch the results as rows. You can then grab the column values and work with them.
Incorrect and depreciated method, but working:
$type = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$typeResult = mysql_query($type);
// for each row
while ($row = mysql_fetch_array($typeResult)) {
// grab the columns
$value = $row['column_name'];
}
I would recommend using MySQLi or PDO like to following (MySQLi):
$mysqli_connection = new mysqli("hostname", "username", "password", "database");
$type = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$res = $mysqli_connection->query($type);
while($row = $res->fetch_array(MYSQLI_ASSOC)) {
$value = $row['column_name'];
}
$res->free();
$mysqli_connection->close();
This question already has answers here:
How to change mysql to mysqli?
(12 answers)
Closed 1 year ago.
I have some php code that was like this:
$row = mysql_fetch_array ( mysql_query("SELECT * FROM `tblFacilityHrs` WHERE `uid` = '$uid'"));
I'm now trying to convert it to mysqli_fetch_array as shown here http://php.net/manual/en/mysqli-result.fetch-array.php (Example #1 Object oriented style)
I'm not sure what the example means by "$result".
This is what I've converted my code to so far:
<?php
include('../config.php');
if (isset($_GET['uid']) ) {
$uid = $_GET['uid'];
$id = $_GET['id'];
if (isset($_POST['submitted'])) {
foreach($_POST AS $key => $value) { $_POST[$key] = mysqli_real_escape_string($value); }
//Query for tblFacilityHrs
$sql = " UPDATE tblFacilityHrs SET `title`='{$_POST['title']}',`description`='{$_POST['description']}' WHERE `uid` = '$uid' ";
$result = $mysqli->query($sql) or die($mysqli->error);
//Query for tblFacilityHrsDateTimes
$sql2 = "UPDATE tblFacilityHrsDateTimes SET `startEventDate`='{$_POST['startEventDate']}',`endEventDate`='{$_POST['endEventDate']}', `startTime`='{$_POST['startTime']}',`endTime`='{$_POST['endTime']}',`days`='{$_POST['days']}',`recurrence`='{$_POST['recurrence']},`finalDate`='{$_POST['finalDate']}' WHERE `id` = '$id' "; print $sql2;
$result2 = $mysqli->query($sql2) or die($mysqli->error);
echo ($mysqli->affected_rows) ? "Edited row.<br />" : "Nothing changed. <br />";
echo "<a href='list.php'>Back</a>";
}
$row = $result->fetch_array($mysqli->query("SELECT * FROM `tblFacilityHrs` WHERE `uid` = '$uid'"));
$row2 = $result2->fetch_array($mysqli->query("SELECT * FROM `tblFacilityHrsDateTimes` WHERE `id` = '$id'"));
?>
There is probably a lot wrong with as I am learning mysqli, but right now it errors on
Fatal error: Call to a member function fetch_array()
UPDATE queries do not return result objects, it returns TRUE (assuming success). You're then trying to call TRUE->fetch_array(), which obviously won't work.
Now, for doing what you actually want to do, try this:
$row = $mysqli->query("SELECT.....")->fetch_array();
Looks like you are trying to use an old result object (result of your UPDATE) to get results for a new query. You need to run the new query first, assign its result to an object, and then fetch the results from object. Check out the last three lines of your script re-written:
$facilityHoursQueryResult = $mysqli->query("SELECT * FROM `tblFacilityHrs` WHERE `uid` = '$uid'");
$facilityHoursDateTimesQueryResult = $mysqli->query("SELECT * FROM `tblFacilityHrsDateTimes` WHERE `id` = '$id'");
$facilityHoursRow = $facilityHoursQueryResult == FALSE ? NULL : $facilityHoursQueryResult->fetch_array();
$facilityDateTimesRow = $facilityHoursDateTimesQueryResult == FALSE ? NULL : $facilityHoursDateTimesQueryResult->fetch_array();
?>
Here is a helpful page with other result object methods:
http://www.php.net/manual/en/class.mysqli-result.php