Failing to recognize fetch_assoc method - php

I'm trying to upload an excel file to my site and save the data in my database, however i'm failing to do so and getting: Fatal error: Call to undefined method mysqli::fetch_assoc() ... But i'm not sure how to handle it, and i haven't found a question related on SO, any help?
function getSchedule($filepath,$con,$filename){
require_once 'excel/PHPExcel/IOFactory.php';
$objPHPExcel = PHPExcel_IOFactory::load($filepath);
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
$worksheetTitle = $worksheet->getTitle();
$highestRow = $worksheet->getHighestRow(); // e.g. 10
$highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
list($location, $date) = explode('-', $filename, 2);
$LastChange = date('d/m/Y h:i:s');
$Status='Open';
$servername = "localhost";
$username = "root";
$password = "Js";
$dbname = "jr";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM Schedule";
$conn->query($sql);
// output data of each row
while($row = $conn->fetch_assoc()) {
$sql1="DELETE FROM `schedule` WHERE " . $row["Date"]. "='$date'";
$result = mysqli_query($conn,$sql1);
}
$conn->close();
for ($row = 3; $row <= $highestRow; ++ $row) {
$sql="INSERT INTO `schedule` (`Status`,`LastChange`, `Location`,`Date`,`AFNumber`,`Name`,`01-IN`, `01-OUT`, `02-IN`, `02-OUT`, `03-IN`, `03-OUT`, `04-IN`, `04-OUT`, `05-IN`, `05-OUT`, `06-IN`, `06-OUT`, `07-IN`, `07-OUT`, `08-IN`, `08-OUT`, `09-IN`, `09-OUT`, `10-IN`, `10-OUT`, `11-IN`, `11-OUT`, `12-IN`, `12-OUT`, `13-IN`, `13-OUT`, `14-IN`, `14-OUT`, `15-IN`, `15-OUT`, `16-IN`, `16-OUT`, `17-IN`, `17-OUT`, `18-IN`, `18-OUT`, `19-IN`, `19-OUT`, `20-IN`, `20-OUT`, `21-IN`, `21-OUT`, `22-IN`, `22-OUT`, `23-IN`, `23-OUT`, `24-IN`, `24-OUT`, `25-IN`, `25-OUT`, `26-IN`, `26-OUT`, `27-IN`, `27-OUT`, `28-IN`, `28-OUT`, `29-IN`, `29-OUT`, `30-IN`, `30-OUT`, `31-IN`, `31-OUT`) VALUES ('".$Status."', '".$LastChange."','".$location."','".$date."',";
for ($col = 0; $col < ($highestColumnIndex -1); ++ $col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val = $cell->getValue();
if($col==($highestColumnIndex -2)){
$sql.="'$val'";
}else{
$sql.="'$val', ";}
}
echo "Index:".$highestColumnIndex."<br>";
if($highestColumnIndex < 63){
$temp = 63 - $highestColumnIndex;
for($i = 1;$i <= $temp; $i++){
if($i == $temp){
$sql.=",''";
} else{
$sql.=", '',";
}
}
}
$sql .=")";
if ($con->query($sql) === TRUE) {
} else {
echo "<br><br>Error: " . $sql . "<br>" . $con->error;
}
}//End For Each Row
}//End For Each Worksheet
}//End getHours Function

From php.net:
array mysqli_result::fetch_assoc ( void )
This means that you should provide it with a result of a query, not a connection. Change your code to this and it should work
$results = $conn->query($sql); //assign query to a variable and get mysqli_result in return
while($row = $results->fetch_assoc()) { //use that in the while loop

You are overwriting the connection object $conn.Use
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {

Try this:
$sql = "SELECT * FROM Schedule";
$result = $conn->query($sql);
// output data of each row
while($row = $result->fetch_assoc()) {

Related

Multiple for-loops from one $result = $conn->query($query)

I have imported data into a table and I am now accessing that data with PHP using the code as follows,
<?php
require_once 'connect.php';
$query = "SELECT * FROM JunkData";
$result = $conn->query($query);
if(!$result) die("Fatal Error");
$rows = $result->num_rows;
for ($name = 0; $name < $rows; ++$name)
{
$row = $result->fetch_array(MYSQLI_ASSOC);
echo htmlspecialchars($row['Name']) . '<br/>';
}
$result->close();
$conn->close();
This works!
I am really just curious why adding a second for-loop does not work, unless I declare $result again?
<?php
require_once 'connect.php';
$query = "SELECT * FROM JunkData";
$result = $conn->query($query);
if(!$result) die("Fatal Error");
$rows = $result->num_rows;
for ($name = 0; $name < $rows; ++$name)
{
$row = $result->fetch_array(MYSQLI_ASSOC);
echo htmlspecialchars($row['Name']) . '<br/>';
}
for ($number = 0; $number < $rows; ++$number)
{
$row = $result->fetch_array(MYSQLI_ASSOC);
echo htmlspecialchars($row['Number']) . 'Flag<br/>';
}
$result->close();
$conn->close();
Doesn't work, although 'Flag' is printed an appropriate number of times.
Whereas if I declare $result again.
<?php
require_once 'connect.php';
$query = "SELECT * FROM JunkData";
$result = $conn->query($query);
if(!$result) die("Fatal Error");
$rows = $result->num_rows;
for ($name = 0; $name < $rows; ++$name)
{
$row = $result->fetch_array(MYSQLI_ASSOC);
echo htmlspecialchars($row['Name']) . '<br/>';
}
$result = $conn->query($query);
for ($number = 0; $number < $rows; ++$number)
{
$row = $result->fetch_array(MYSQLI_ASSOC);
echo htmlspecialchars($row['Number']) . '<br/>';
}
$result->close();
$conn->close();
The code does work.
I have tried unsetting a few variables with unset($row) etc and I did notice if I remove the line,
$row = $result->fetch_array(MYSQLI_ASSOC);
from the second for loop, it will print the last value in the Number column as many times as the loop will run.
I hope that is understandable. I am wondering what is happening in the code that I need to re-declare $result if I want to run a second for loop against it.
The standard solution I would recommend is to do fetch_all()
Instead of:
$rows = $result->num_rows;
for ($name = 0; $name < $rows; ++$name)
{
$row = $result->fetch_array(MYSQLI_ASSOC);
Do
$rows = $result->fetch_all();
foreach ($rows as $row)
{
...
}
// then you can re-loop same array of $rows
foreach ($rows as $row)
{
...
}
There is an internal pointer when you call fetch_* function.
In your first for loop, you send the pointer to the end of the result set.
So, the next fetch will return nothing.
If you run $result->data_seek(0) you will reset this pointer and can reuse:
for ($name = 0; $name < $rows; ++$name)
{
$row = $result->fetch_array(MYSQLI_ASSOC);
echo htmlspecialchars($row['Name']) . '<br/>';
}
$result->data_seek(0); //<---- REPLACE HERE
for ($number = 0; $number < $rows; ++$number)
{
$row = $result->fetch_array(MYSQLI_ASSOC);
echo htmlspecialchars($row['Number']) . '<br/>';
}
Of course, usually there is no need to loop the same result set twice, you may need to rethink your logic and loop only once.

MySQL Data to JSON Array with inserting a string

This is my Code for now but it only works until the for loop in the mySQLResultsetToJSON().
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "123456";
$table = "ticketing";
$link = new mysqli($servername, $username, $password, $table);
if ($link->connect_error) {
die("Connection failed: " . $link->connect_error);
}
echo "Connected successfully";
$result = $link->query("SELECT * from Ticket");
print_r($result);
$final_result = mySQLResultsetToJSON($result);
print_r($final_result);
$link->close();
function mySQLResultsetToJSON($resultSet)
{
for($i = 0; sizeof($resultSet); $i++)
{
$rows = array();
while($r = mysqli_fetch_assoc($resultSet[$i])) {
$rows[] = $r;
}
$jsonResult[$i] = json_encode(array('Results' => $rows));
}
print_r($jsonResult);
return $jsonResult;
}
?>
Thank you!
Thomas
echo "mysql data<br />";
$result = $link->query("SELECT * from users");
print_r($result->fetch_object());
echo "<br />";
echo "in json<br />";
$res = ['Results' => $result->fetch_object() ];
echo json_encode($res);
$link->close();
User like
$result = $link->query("SELECT * from Ticket");
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
print "<pre>";
print_r(json_encode(array('Results' =>$rows)));
$link->close();

Query to return connecting flights given source and destination

So I have a table called "Flights" that stores the source and destination of a flight. Say you have A -> B and B -> C in a table, and you give the source as 'A' and destination as 'C', the query should return the path between these two A - > B, B -> C. I have tried this query:
$result = $mysqli -> query(
"SELECT *
FROM Flights a
JOIN Flights b
ON a.Destination = b.Source
AND '{$source}' = a.Source
AND '{$destination}' = b.Destination");
As a side note: I'm using mysqli in PHP. I have done this query in the mysql console and it returns everything I need. But if I ran this query in PHP on the example table I gave it would return B -> C only. Any ideas where I went wrong? I think it could have to do with the PHP string formatting.
<?php
if(isset($_POST['source'])){
$source = $_POST['source'];
}
if(isset($_POST['destination'])){
$destination = $_POST['destination'];
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "Airport Tracking";
$table ="Flights";
$flag = 0;
// Create connection
$mysqli = new mysqli($servername, $username, $password, $dbname);
if ($mysqli->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['source']) && isset($_POST['destination'])){
$columns= $mysqli -> query("SHOW COLUMNS FROM $table");
$sql = "SELECT *
FROM Flights a
JOIN Flights b
ON a.Destination = b.Source
AND {$source} = a.Source
AND {$destination} = b.Destination";
echo "$sql";
$result = $mysqli -> query($sql);
if($result == FALSE){
echo "<br><b>Incorrect input</b>";
$flag = 1;
}
else if($result->num_rows == 0){
echo "<br><b>Returned no results</b>";
$flag = 1;
}
}
$array = array();
$i = 0;
if(isset($_POST['source']) && $flag == 0){
// Display results
echo "<table>";
echo "<thead><tr>";
while ($row = $columns -> fetch_array(MYSQLI_BOTH)) {
echo "<th>" .$row['Field']. "</th>";
$array[] = $row['Field'];
}
echo "</tr></thead>";
while ($row = $result -> fetch_array(MYSQLI_BOTH)) {
echo "<tr>";
while ($i < sizeof($array)) {
echo "<td>" .utf8_encode($row[$array[$i]]). "</td>";
$i++;
}
echo "</tr>";
$i = 0;
}
echo "</table>";
}
$mysqli->close();
?>
That is my PHP code. I apologize because I know indenting is incorrect.

Why Getting only 1 array instead of many arrays?

I am a completely newbie in programming php I would like to make this code below return many arrays(to flash as3), however I only receive one array.Can anyone please pinpoint what is my mistake here? thanks.
$data_array = "";
$i = 0;
//if(isset($_POST['myrequest']) && $_POST['myrequest'] == "get_characters")
//{
$sql = mysqli_query($conn, "SELECT * FROM ns_users ORDER BY Char_id");
while($row = mysqli_fetch_array($sql))
{
$i++;
$fb_name = $row["Username"];
$fb_id = $row["Fb_id"];
$fb_at = $row["Access_token"];
$fb_sig = $row["Fb_sig"];
$char_id = $row["Char_id"];
if($i == 1)
{
$data_array .= "$fb_name|$fb_id|$fb_at|$fb_sig|$char_id";
}
else
{
$data_array .= "(||)$fb_name|$fb_id|$fb_at|$fb_sig|$char_id";
}
echo "returnStr=$data_array";
exit();
}
When you write your exit insight your loop you stop executing your program and you get only one record. You should set the echo and exit after your while loop.
$data_array = "";
$i = 0;
$sql = mysqli_query($conn, "SELECT * FROM ns_users ORDER BY Char_id");
while($row = mysqli_fetch_array($sql)) {
$i++;
$fb_name = $row["Username"];
$fb_id = $row["Fb_id"];
$fb_at = $row["Access_token"];
$fb_sig = $row["Fb_sig"];
$char_id = $row["Char_id"];
if($i == 1) {
$data_array .= "$fb_name|$fb_id|$fb_at|$fb_sig|$char_id";
} else {
$data_array .= "(||)$fb_name|$fb_id|$fb_at|$fb_sig|$char_id";
}
}
echo "returnStr=$data_array";
exit();
Those two last line of your should be outside of your loop:
$data_array = "";
$i = 0;
//if(isset($_POST['myrequest']) && $_POST['myrequest'] == "get_characters")
//{
$sql = mysqli_query($conn, "SELECT * FROM ns_users ORDER BY Char_id");
while($row = mysqli_fetch_array($sql))
{
$i++;
$fb_name = $row["Username"];
$fb_id = $row["Fb_id"];
$fb_at = $row["Access_token"];
$fb_sig = $row["Fb_sig"];
$char_id = $row["Char_id"];
if($i == 1)
{
$data_array .= "$fb_name|$fb_id|$fb_at|$fb_sig|$char_id";
}
else
{
$data_array .= "(||)$fb_name|$fb_id|$fb_at|$fb_sig|$char_id";
}
}
echo "returnStr=$data_array";
exit();
If you would name the columns that you want in the SELECT then it's much simpler. Make sure to use MYSQLI_ASSOC in the fetch:
$sql = mysqli_query($conn, "SELECT Username, Fb_id, Access_token, Fb_sig, Char_id FROM ns_users ORDER BY Char_id");
while($row = mysqli_fetch_array($sql, MYSQLI_ASSOC))
{
$data_array[] = implode('|', $row);
}
echo "returnStr=" . implode('(||)', $data_array);
exit();

How do I output certain index values from a foreach array?

This is the structure in the database:
items |itemLink
----------------------
Kill Bill|Kill Bill link
Preman |Preman link
This is the code:
$db = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$items = 'SELECT items FROM menus';
$itemLink = 'SELECT itemLink FROM menus';
$itemQuery = $db->query($items);
$linkQuery = $db->query($itemLink);
$fetchItem = $itemQuery->fetchAll(PDO::FETCH_ASSOC);
$fetchLink = $linkQuery->fetchAll(PDO::FETCH_ASSOC);
$merged = array_merge($fetchItem,$fetchLink);
foreach($merged as $entry) {
foreach( $entry as $key => $value ) {
}
}
From the above code, how do I output only the items' datas?
Using the example above you could then do something like this to answer you question
$result = mysql_query('Select * from names');
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo $row["FirstName"] . " " . $row["LastName"] . "<br>";
}
mysql_close($conn);
?>
I would use something like this, not two arrays for something that could be one query. I have shown three methods, using var_dump or print_r will show how each works.
$conn = mysql_connect($hostname, $username, $password);
if (!$conn) {
die('Could not connect to MySQL: ' . mysqli_connect_error());
}
$db_selected = mysql_select_db('sample', $conn);
if (!$db_selected) {
die("Can\t use db : ' . mysql_error()");
}
$result = mysql_query('Select * from names');
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
print_r($row);
}
$result = mysql_query('Select * from names');
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
print_r($row);
}
$result = mysql_query('Select * from names ');
while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
print_r($row);
}
mysql_close($conn);

Categories