This question already has answers here:
php warning: mysqli_close() expects parameter 1 to be mysqli
(2 answers)
Closed 2 years ago.
I am having a slight problem when I try to connect to a db remotely and I would be really grateful for any tips. Here is the code:
$con=mysqli_connect($port, $username, $password, $database);
$sql = "SELECT name, date FROM `view_tickets`;";
if ($result = mysqli_query($con, $sql))
{
// If so, then create a results array and a temporary one to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
while($row = $result->fetch_object())
{
// Add each row into our results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Finally, encode the array to JSON and output the results
echo json_encode($resultArray);
}
mysqli_close($result);
mysqli_close($con);
I want to result in json to be able to run this from a mobile app. At the moment nothing is displaying on the browser (I am running Xampp). I added some prints and can confirm that the connection is successful and the array is being filled properly. I managed to print it out using print_r(array_values($resultArray));
Is something wrong with my json?
I don't know if this helps but noticed that I am getting the following warning;
Warning: mysqli_close() expects parameter 1 to be mysqli, object given in /Applications/XAMPP/xamppfiles/htdocs/www/service.php on line 39
This corresponds to mysqli_close($result);
Any ideas?
Here is optimised version of your code.
Note that tempArray is remove (there is no need of it)..
mysqli_close($result) is replaced with unset($result) because $result is not a connection object. How ever unsetting is not required if this is the end of your code because after the end of the script php will unset all variables by it self..
$con=mysqli_connect($port, $username, $password, $database);
$sql = "SELECT name, date FROM `view_tickets`;";
$resultArray = array();
if ($result = mysqli_query($con, $sql)) {
// Loop through each row in the result set
while($row = $result->fetch_object()){
$resultArray[] = $row;
}
}
unset($result);
mysqli_close($con);
// Finally, encode the array to JSON and output the results
echo json_encode($resultArray);
The mysqli_close needs to connection given to close, but you're give the function your result from your Query!
Change it to
mysqli_close($con);
Then it should be working, if not just comment
I had an issue with the encoding of the character set. Databases can have different encoding, make sure it is utf8
Related
This question already has answers here:
mysql_fetch_array skipping first row
(6 answers)
Closed 3 years ago.
When query this select statement directly to my database (in phpmyadmin) I get back 5 rows. :
SELECT class.* FROM class, professor, administers WHERE professor.professorID = administers.professorID AND class.classID = administers.classID AND professor.uName='username';
When i query using mysqli I am getting back 5 rows in my mysqli_num_rows($result). However when I try to transfer each row of $result to an array, I am losing the first row. I know this is an error on my part in my PHP but I cannot figure out where I've gone wrong. I've tried many variations on my while loop as well as some variations of for loops and I've exhausted my ideas. On my logic page i use the following:
$stmt = mysqli_stmt_init($conn);
$sql = "SELECT class.* FROM class, professor, administers WHERE professor.professorID = administers.professorID AND class.classID = administers.classID AND professor.uName=?;";
$acct = $_SESSION['userUid'];
if (!mysqli_stmt_prepare($stmt, $sql))
{
header("Location: ../index.php?error=sqlerror");
exit();
}
else{
mysqli_stmt_bind_param($stmt, "s", $acct);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
}
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
mysqli_fetch_assoc($result);
while ($row = mysqli_fetch_assoc($result))
{$asocres[] = $row;}
and when I print_r($asocres); on the front end page I get back 4 rows (first row missing)
My question is why am i losing the first row of my query?
-----EDIT-----
i realized that it was the first instance of mysqli_fetch_assoc($result); before the while loop. Why was this causing an issue though? how did this result in the first row being skipped in my while loop?
Try this way
$stmt = mysqli_stmt_init($conn);
$sql = "SELECT class.* FROM class, professor, administers WHERE professor.professorID = administers.professorID AND class.classID = administers.classID AND professor.uName=?;";
$acct = $_SESSION['userUid'];
if (!mysqli_stmt_prepare($stmt, $sql))
{
header("Location: ../index.php?error=sqlerror");
exit();
}
else{
mysqli_stmt_bind_param($stmt, "s", $acct);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
}
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
while ($row = mysqli_fetch_assoc($result))
{$asocres[] = $row;}
Try to print the rows in while loop and see if you get the 1st row.
Why its happening is beacuse the first call sets the array pointer to the first element, and then the second call -in while loop- set the pointer to the second element.
I hope my is answer is helpful.
You need to remove:
mysqli_fetch_assoc($result);
And you are good to go.
Note:-mysqli_fetch_assoc($result); will fetch first record and moves the internal data pointer to the next record. So while() will start from second record.
mysqli_fetch_assoc returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead.
Calling mysqli_fetch_assoc simply moves the result set's internal pointer further down the list of rows, eventually pointing to NULL (end of list). The rows are all still there, you haven't removed any of them: you've simply traversed the list, and you could run through them again by using something like mysqli_data_seek to reset the internal pointer to a specific row.
For this issue use mysqli_fetch_assoc only inside loop.
Additional Info
You'd need to call mysqli_free_result to "free" the result set.
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 2 years ago.
I an trying to query a mySQL database using a PHP function. Intermittantly, the function that I am using does not seem to return a result. As far as I can detect, it's not a null response, and based on the function, it doesn't seem to be returning an invalid result ( the return string Nuthin in this case ).
function GeneratePiece2 ($sqlstr){
$conn = new mysqli(gHOST, gUSER, gPASSWORD, gDATABASE);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = $conn->query($sqlstr);
$returnable = "";
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo $row;
$returnable = $row;
}
} else {
return "nuthin";
}
$conn->close();
return $returnable;
}
I've been using the same SQL Query of
SELECT Name FROM Char_Name_full WHERE Male=1 AND DivisionID=12 ORDER BY RAND() LIMIT 1
Around 80% of the time I will receive a result of something like {"Name":"Christoph"} but 1 out of 10 returns nothing.
If someone is having problems with fetch_assoc() returning "Undefined index":
Check the indexes names (database Column name) - they are case sensitive.
Example:
For "SELECT Name FROM..." Your code must be $row["Name"]. Not NAME or name.
In your query, you are checking if the number of rows is greater than zero, but you are not doing anything to check if the value that is returned is Null. The behaviour that you are describing matches the scenario of at least 1 row in 'Name' that has a NULL value.
Note that I am not going to comment on your code structure or syntax here, but I have changed your response values to help identify / prove that a null value is the issue here.
Also, if your query is limited to a single row, then the while loop will only iterate once.
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
// Echo out the values for Name in the result set
if(is_null($row["Name"], ))
echo '[NULL]';
else
echo $row["Name"];
// your application logic ;)
$returnable = $row;
}
} else {
return "no rows";
}
Please consider using a SQL IDE like Toad for MySQL along side your development, then you can visually inspect your data for these issues without writing code hacks :)
I am a novice when it comes to working with JSON/PHP. I have been trying to get this to work based off this answer.
How to generate .json file with PHP?
I am trying to query a MySQL database to output it in a JSON format without having it write to a new file I.E. file.json since I am pulling dynamic data. I can create a script that creates a json array but, I need the output in a JSON format. The script I have been working with below from the example link above connects to the DB but, it is not populating with data. It just gives me this output. I added the DB connection check to check if the script was connecting to the DB.
Connected successfully{"streamers":[]}
This is the code I am currently working with. Is there anyone who could tell me what I am missing and could improve on. DB info removed for security reasons.
<?php
header('Content-type:application/json;charset=utf-8');
//Make connection to database
$db=new PDO('mysql:dbname=streamdb;host=localhost;','root','');
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
echo "Connected successfully";
//Prepare the query for analyzing
$sql=$db->prepare('select * from maintable');
$response = array();
$streamers = array();
$result=mysql_query($sql);
while($sql=mysql_fetch_array($result))
{
$displayname=$row['DisplayName'];
$streamkey=$row['StreamKey'];
$streamers[] = array('DisplayName'=> $displayname, 'StreamKey'=> $streamkey);
}
$response['streamers'] = $streamers;
echo stripslashes(json_encode($response));
?>
-Thanks!
First, use PDO only. No mysql_* functions.
Then your code should look like this:
$pdo = new PDO('mysql:host=...', 'username', 'password', [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);
$result = $pdo->query('SELECT DisplayName, StreamKey FROM ...');
$rows = $result->fetchAll(PDO::FETCH_ASSOC);
header('Content-Type: application/json;charset=utf-8');
echo json_encode(['streamers' => $rows],
JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
The PDO::ERRMODE_EXCEPTION sets PDO to throw all errors as exceptions, so they can be handled in an easy and consistent way.
The PDO::FETCH_ASSOC sets fetchAll() to return rows as arrays where column names are used as array keys.
The json_encode() will take care of producing a valid JSON output. Since you are not embedding JSON into HTML, there is no need for escaped slashes and we will make it nicely indented for easier debugging.
So as I said in a comment, the problem is probably that "$row" is not initialized. It should probably be:
while($row=mysql_fetch_array($result))
Also, you used mysql_ functions which are not compatible with PDO. You should do your request using $db->query.
As you asked for suggestions, I may give you a trick that I use.
I think that it's a lot of code for just retrieving a table that is basically the content of the result of your query (in $result). And I guess you have similar code for almost every request. So what I do in general is that I build a generic function called extractResult that directly makes an array of lines from the result of a query.
Here is the function:
/**
* Extract a php array from the result of a db query.
* This result can be directly parsed in JSON for instance.
*/
function extractResult($res) {
$arr = array();
while($line = $res->fetch()) {
$count = count($line)/2;
for ($i=0; $i<$count; $i++) {
unset($line[$i]);
}
array_push($arr, $line);
}
return $arr;
}
Note: the for loop with the "unset" is made to remove the entries with digits. What's returned by a fetch is something like this:
Array("DisplayName" => "Loulou", 0 =>"Loulou", "StreamKey" => 12, 1 => 12)
So it removes the numerical duplicates.
So you could use it like this and your code becomes way lighter:
<?php
header('Content-type:application/json;charset=utf-8');
//Make connection to database
$db=new PDO('mysql:dbname=streamdb;host=localhost;','root','');
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
echo "Connected successfully";
$result=$db->query('select display_name AS DisplayName, stream_key AS StreamKey from maintable');
$response = array();
$response['streamers'] = extractResult($result);
echo json_encode($response);
?>
Note that you have to specify the columns name that you want directly in the request! :)
Don't know if it's nteresting, but I always use this trick so building JSON from DB is so much easier and lighter. :) Good luck.
Here you can check the working code
<?php
$con=mysqli_connect($servername,$username,$password,$databasename);
if (mysqli_connect_errno())
{
echo "Connection Error" . mysqli_connect_error();
}
$query = "SELECT * FROM TableName";
$result = mysqli_query($con,$query);
$querydata = array();
while($data = mysqli_fetch_array($result)) {
$querydata[] = $data;
}
echo json_encode($querydata);
mysqli_close($con);
?>
I am attempting a connection to a sql db via php and keep getting an error I can't figure out. I can connect with another debug scripts with no errors. I get my connection and pull my data but pulls an error at the end.
$con=mysqli_connect("localhost","username","password","dbname");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// This SQL statement selects ALL from the table 'Locations'
$sql = "SELECT * FROM Locations";
// Check if there are results
if ($result = mysqli_query($con, $sql))
{
// If so, then create a results array and a temporary one
// to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
while($row = $result->fetch_object())
{
// Add each row into our results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Finally, encode the array to JSON and output the results
echo json_encode($resultArray);
}
// Close connections
mysqli_close($result);
mysqli_close($con);
?>
Brings this out
[{"Name":"Apple","Address":"1 Infinity Loop Cupertino, CA","Latitude":"37.331741","Longitude":"-122.030333"},{"Name":"Googleplex","Address":"1600 Amphitheatre Pkwy, Mountain View, CA","Latitude":"37.421999","Longitude":"-122.083954"}]
Warning: mysqli_close() expects parameter 1 to be mysqli, object given in /home/jfletch/public_html/appone/connect.php on line 36
mysqli_close($result);
The line above is incorrect. You only need to call mysqli_close() once (if at all since, as pointed out in the comments, the connection is closed at the end of the execution of your script) and the parameter should be your link identifier, not your query resource.
Remove it.
Traditionally we FREE the result, and CLOSE the connection. It looks like both those lines were copied from the same source during a copy/paste.
So the first mysqli_close does have a bad parameter.
You want mysqli_free_result($result); there instead.
Leaving aside that it is supposedly not necessary if the script ends. It cannot hurt. There may be a great many connections before the script ends if you do not re-use connections.
This question already has answers here:
remove duplicating fields in php-mysql result rows
(2 answers)
Closed 8 years ago.
Hey guys (and girls) I'm having a problem with arrays, this code below looks like duplicating each column inside a array! :/
<?php
//quantidade_de_registro
include("mysqlconfig.inc");
$query = "SELECT * FROM contas ";
$res = mysql_query($query);
while($row = mysql_fetch_array($res)){
$arr[] = $row;
}
echo json_encode($arr);
mysql_close($con);
?>
It will returns something like this:
[{"0":"5","ID":"5","1":"Zenny","Login":"Zenny","2":"Zeny","Nome":"Zeny","3":"daniel_queiroz789#hotmail.com","Email":"daniel_queiroz789#hotmail.com","4":"23021994","Senha":"23021994"}]
Each Column appears twice, But I need each column appears just once, a friend mine said that I need to re-parse the array and put it into the array, I don't know what it means or how I can do that :/
Please help :)
you can modify your script by adding a second parameter to the fetch
mysql_fetch_array($res,MYSQL_ASSOC)
However I will second that you should use PDO or mysqli instead
Use mysql_fetch_assoc
No, don't do that. Instead use PDO or mysqli and their respective fetch methods.
mysql_fetch_array fetches both numeric and associative arrays simultaneously.
mysql_fetch_array() as it's second paramter by default at "MYSQL_BOTH" meaning it return an array with both numerical and associative key.
To have only one of those, you can specify it in the call
mysql_fetch_array($res, MYSQL_ASSOC); // for assosiative
// OR
mysql_fetch_array($resm MYSQL_NUM); // for numeric
For more information you can take a look at the PHP documentation : http://php.net/manual/en/function.mysql-fetch-array.php
Try using PDO. The PDOStatement class fetch methods allow you to set the format of the returned data.
Here is some code for retrieving your data in an associative array:
try {
$dbh = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$sth = $dbh->prepare("SELECT * FROM contas");
if($sth->execute()) {
$contacts = $sth->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($contacts);
} else {
throw new PDOException(print_r($sth->errorInfo(), true));
}
} catch(PDOException $e) {
echo $e->getMessage();
}