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.
Related
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);
?>
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
I'm trying to implement pagination using PHP. I found that calling exec to the connected database prevents the further query calls from working.
The piece of code at hand:
<?php
// Pagination logic
//Here we count the number of results
$query = "SELECT COUNT(*) as num FROM gig";
$total_pages = $db->exec($query);
$total_pages = $total_pages[num];
?>
After it if I try to use a query such as:
<?php>
foreach ($db->query("SELECT sname, start, venue FROM gig WHERE start = '0000-00-00 00:00:00'") as $a) {
$row="<tr><td>$a[sname]</td><td>To be announced</td><td>$a[venue]</td></tr>\n";
print $row;
}
?>
it returns
Warning: Invalid argument supplied for foreach()
As soon as the first code block is removed, the query works fine. When I check the value of $total_pages, it's 0, so something must be going wrong along the way. As far as I know, I use it in the same way as the query(which works on its own), so is there any reason why it doesn't work?
The PDO is initialized in the following way:
try {
$db = new PDO("mysql:dbname=$db_name;host=$db_server", $db_user, $db_pw);
} catch (PDOException $e) {
die('Connection failed: ' . $e->getMessage());
}
session_start();
From Manual
PDO::exec() does not return results from a SELECT statement. For a
SELECT statement that you only need to issue once during your program,
consider issuing PDO::query(). For a statement that you need to issue
multiple times, prepare a PDOStatement object with PDO::prepare() and
issue the statement with PDOStatement::execute().
Used a function of the STATEMENT object had after using querying to count the rows instead of exec:
$dbq = $db->query("SELECT * FROM gig");
$rows = $dbq->rowCount();
About the latter code block not working because of the exec failing - it seems to just be the way php queries work, if one fails, all fail. The foreach() error is for the object it's provided is not an array, for it failed.
I am using the mysqli functions (mysqli_connect, mysqli_select_db, mysqli_query) to call 1 select query and 2 stored procedures.
It seems that when I am using the same $connection (returned by mysqli_connect) multiple times, I am getting the following error message: "Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in..."
Below is my code:
<?php
$server="localhost";
$user="user";
$pass="pass";
$db="db";
$connection=mysqli_connect("$server","$user","$pass");
mysqli_select_db($connection, "$db") or die('Unable to select database.');
//First SELECT using $connection
$query=mysqli_query($connection, "SELECT item_name FROM items ORDER BY item_name DESC");
While ($result=mysqli_fetch_array($query,MYSQL_NUM))
{
$complete_result[] = $result[0];
$total_rows = $total_rows + 1;
}
//CALL to first sp using $connection
$query2 = mysqli_query($connection, "CALL sp_check_edits_remaining()");
while ($row2 = mysqli_fetch_array($query2, MYSQL_ASSOC)) {
$edits_remaining = $row2['edits_remaining'];
} // End while
//CALL to second sp using $connection
$query3 = mysqli_query($connection, "CALL sp_edit_data");
while ($row3 = mysqli_fetch_array($query3, MYSQL_ASSOC)) {);
$edits_id = $row3['id'];
} // End while
?>
Like I described, when I call the second sp, the above code gives me the error message mentioned above. (Please note that the connection is never closed.)
However, when I create another connection and provide it to the second sp call, this error disappears. This is shown in the code below
$connection2=mysqli_connect("$server","$user","$pass");
mysqli_select_db($connection2, "$db") or die('Unable to select database.');
//CALL to second sp using $connection
$query3 = mysqli_query($connection2, "CALL sp_edit_data");
while ($row3 = mysqli_fetch_array($query3, MYSQL_ASSOC)) {
$edits_id = $row3['id'];
} // End while
Can anyone please help me why this unexpected behavior?
Thanks and in advance!
It seems I have found a solution, which might be specific to my scenario.
My stored procs return only one row in the resultset.
So, after the CALL to the first sp and the corresponding while loop, I have simply added:
mysqli_next_result($connection);
This has removed the error message/warning I was receiving.
Anyone wants to comment whether this is the 'professional' approach?
You have an error somewhere, causing one of the mysql functions (probably the query call(s)) to return a boolean false, which you then blindly use in a fetch call. You need to add extra error handling, e.g.
$query = mysqli_query($connection, "...") or die(mysqli_error($connection));
never assume a query has succeeded.
enter code hereafter the query is finished, you must close the $connection then for another query, connect and assign the $connection again.
mysqli_close($connection);
$connection=mysqli_connect(bla,bla,bla,bla).
I am in the middle of creating a custom shopping cart and I', building a query that begins with retrieving a session_id I just saved into the carts table. I know this value was saved, and I run this query at the mysql command line and it returns just what I need BUT I am not getting the value into the $cart_id. There are other INSERT queries above and below this point in the script so I know I'm connecting to the db just fine.
//Get cart id
$cart_id_select_q = "SELECT c.id FROM carts AS c WHERE c.user_session_id='$uid'";
$cart_id = $mysqli->query($conn, $cart_id_select_q);
echo "<pre>Debug: $cart_id_select_q</pre>";
if ( !$cart_id ) {
printf("error: %s\n", mysqli_error($conn));
}
else {
echo 'get session id from cart: execute success';
print_r($cart_id);
var_dump($cart_id);
}
I'm also on a VPS server with errors suppressed not I'm not getting a mysqli_error to display in the browser but I am getting the following 2 warnings in my error_log.
[29-Jul-2011 09:29:24] PHP Warning: mysqli::query() expects parameter 2 to be long, string given in /home/sopadmin/public_html/dev/cart.php on line 89
[29-Jul-2011 09:29:24] PHP Warning: mysqli_error() expects parameter 1 to be mysqli, null given in /home/sopadmin/public_html/dev/cart.php on line 92
I've also tried to use mysqli_num_rows() and fetch_assoc() but none have helped. the $cart_id remains null and I don't know how to retrieve the mysql error in this server configuration. Posting here is a last resort after toying with it all night.
I should note, I am just starting to really use the new mysqli extension and I'm also beginning to code in a more OO way. But I'm usually starting out coding procedurally and then creating classes when I have the design laid out. But that's just a comment on my experience level, what I don't understand is why this query is not returning a vlue inside my script.
When using object oriented mysqli API, you do not need (in fact you can't) pass a connection as the first argument.
This: $cart_id = $mysqli->query($conn, $cart_id_select_q);
should be: $cart_id = $mysqli->query($cart_id_select_q);
And this: printf("error: %s\n", mysqli_error($conn));
should be: printf("error: %s\n", mysqli->error);
I've no idea what $conn is (looks like a string), but it surely is not a MySQLi connection object.
Simple example to avoid such failure:
/* Select queries return a resultset */
$result = $mysqli->query("SELECT Name FROM City LIMIT 10");
if (!is_null($result)) {
printf("Select returned %d rows.\n", $result->num_rows);
/* free result set */
$result->close();
} else {
error_log("Mysql query failed" . $mysqli->error);
}