One column table into an array - php

I read most of the posts related to my question but none can resolve my simple issue.
I am using PHP and MySQLi to retrieve data from my server.
In my Database I have a one-dimensional table (i.e. one column only) and I want to put its data inside an array.
Until now I was using JSON to hold the data from my server.this is my code:
<?php
include 'ChromePhp.php';
$con=mysqli_connect("197.168.240.100","jsoncloud","nuahyu,hs","json");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
ChromePhp::warn('Failed to connect to MySQL');
}
$sql="SELECT `street` FROM `users` ";
$result=mysqli_query($con,$sql);
$rows = array();
while ($row = mysqli_fetch_all($result,MYSQLI_ASSOC)) {
$rows[] = $row[0];
}
echo json_encode($rows);
// Free result set
mysqli_free_result($result);
mysqli_close($con);
?>
My final goal is to echo the array back so I can use it with Ajax in another JS file
in the other JS file I have the following code:
$.ajax({
type: 'POST',
url: 'js/SQLusersstreets.php',
dataType: 'json',
success: function(jsonData) {
console.log(jsonData);
},
error: function() {
alert('Error loading SQLusersstreets.php from GoogleMapsCode.js');
}
});
This is my output when I open the browser's debugger:
I am trying to return a simple array, what am I doing wrong?

Change mysqli for PDO
Assuming a connection is already established, you will need only one line of code:
echo json_encode($pdo->query("SELECT `street` FROM `users`")->fetchAll(PDO::FETCH_COLUMN));
but if you prefer to write a lot of code, then change fetch_all to fetch_assoc

try this, if this is what you are asking about:
for($i=0;$i<sizeof($rows);$i++){
echo $rows[$i]['id']; //for example
}

mysqli_fetch_all is a shortcut for while($row = mysqli_fetch) {}, so you can skip the while cycle.
$sql="SELECT DISTINCT `street` FROM `users` ";
$result=mysqli_query($con,$sql);
$rows = mysqli_fetch_all($result,MYSQLI_ASSOC);
echo json_encode(array_map(function($i) { return $i['street']; }, $rows));
See the documentation here for more examples http://php.net/manual/en/mysqli-result.fetch-all.php

Related

OCI FetchInto does not fetch data in PHP 7

I am trying to fetch data from a table in oracle database using php 7. I am using OCIFetchInto but when i look to the result array, i find it empty, although it shouldn't be actually empty. knowing that the connection to the database is successful and the table in the database is not empty.
I have debugged the code, and i am getting Resource #4 from the execute function, I have changed the execute function but i still get the same result.
i also changed the data[0] to data['columnname'] but i still cannot retreive it.
Thanks in advance
The code below:
require_once("../include_tse/class_ora_db.php");
$oracle_db = new ora_database("abc");
$error="";
if ($oracle_db->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$Wip=$_REQUEST['rechts'];
echo $Wip;
$sql_query="SELECT Om_Wip_Entity_Name,Quantity,Country_Description FROM abc_print WHERE Om_Wip_Entity_Name= '$Wip'";
$cursor = $oracle_db->execute_sql($sql_query);
$counter=0;
while (OCIFetchInto ($cursor,$row))
{
echo "2222222";
$data[]=$row;
$Wip= $data['0'];
$Quantity= $data['1'];
$Country= $data['2'];
$counter ++;
}
echo "row.$Quantity";
As of PHP 5.4 the ocifetchinto alias has been deprecated (http://php.net/manual/en/function.ocifetchinto.php)
You should change it to something like...
while ($row = oci_fetch_assoc ($cursor))
{
$Wip= $row['Om_Wip_Entity_Name'];
$Quantity= $row['Quantity'];
$Country= $row['Country_Description'];
$data[]=$row;
$counter ++;
}
I'm a bit confused as to how your using the data, but this should give a better idea of how to get it working.

Selecting * from table returns nothing

I wrote this php script that allows me to fetch all the rows in a table in my MySQL database.
I have put the echo "1", etc. to see whether it gets to the code at the very end. The output proves it does. However, it does not output anything when echoing json_encode($resultsArray), which I can't seem to figure out why.
Code:
// Create connection
$connection = mysqli_connect("localhost", "xxx", "xxx");
// Check connection
if (!$connection) { die("Connection failed: " . mysqli_connect_error()); } else { echo "0"; }
// select database
if (!mysqli_select_db($connection, "myDB")) { die('Unable to connect to database. '. mysqli_connect_error()); } else { echo "1"; }
$sql = "select * from myTable";
$result = mysqli_query($connection, $sql) or die(mysqli_error($connection));;
echo "3";
$resultsArray = array();
while($row = mysqli_fetch_assoc($result)) {
// convert to array
$resultsArray[] = $row;
}
echo "4";
// return array w/ contents
echo json_encode($resultsArray);
echo "5";
Output:
01345
I figured, it is not about the json_encode, because I can also try to echo sth. like $result['id'] inside the while loop and it just won't do anything.
For testing, I went into the database using Terminal. I can do select * from myTable without any issues.
Any idea?
After around 20hrs of debugging, I figured out the issue.
As I stated in my question, the code used to work a few hours before posting this question and then suddenly stopped working. #MichaelBerkowski confirmed that the code is functional.
I remembered that at some point, I altered my columns to have a default value of an empty string - I declared them as follows: columnName VARCHAR(50) NOT NULL DEFAULT ''.
I now found that replicating the table and leaving out the NOT NULL DEFAULT '' part makes json_encode() work again, so apparently there's an issue with that.
Thanks to everybody for trying anyway!

PHP PDO prepared delete statement with MySQL fails inside Ajax call [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
I have a failing PDO Prepared DELETE statement inside a PHP file called with AJAX.
My AJAX call looks like this:
var data = {action: "deleteTask", value: "1"};
$.ajax({
type: "POST",
dataType: "json",
url: "ajax.php",
data: data,
success: function(data) {
alert(data);
},
error: function() {
alert("Something's wrong!");
}
});
My ajax.php looks like this:
<?php
...
function delete(){
$return = "something must be right...";
require('connect.php');
$sql = "DELETE FROM 'tasks' WHERE 'task_id' = ?";
$stmt = $dbcon->prepare($sql);
$stmt->execute(array($_POST["value"]));
$return["json"] = json_encode($return);
echo json_encode($return);
}
?>
Here is a sample of connect.php:
<?php
// Configuration
$username = 'me';
$password = '1234';
$server = 'localhost';
$database = 'mydb';
try {
$dbcon = new PDO("mysql:host=$server;dbname=$database",$username,$password);
$dbcon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $er) {
echo 'ERROR: ' . $er->getMessage();
}
?>
A few things that I have already established:
1) My ajax call works fine if I comment out everything related to the PDO statement;
2) My connect.php file works, because I have tested it with standard HTML forms (as opposed to calling it from ajax);
3) there are no typos in the names of the table and the field of the DB;
4) The $_POST["value"] gives the the right value corresponding to the record I am trying to delete.
5) When I set brakepoints on each line related to the PDO, when I am at the line: $stmt->execute(array($_POST["value"])); and I click "Step Into", it jumps straight to the alert("Something's wrong!"); in the Ajax (nothing gets executed in the ajax.php after that line)
I have spent many hours trying to figure out what is wrong with this and read all the posts that exist on the subject, but my problem seems particular, so any help would be much appreciated! Thanks.
You should look into the browser's the Net responce. It should show a SQL error. If you use MySQL your query should look:
DELETE FROM `tasks` WHERE `task_id` = ?
And if it is PostgreSQL:
DELETE FROM "tasks" WHERE "task_id" = ?
Seems like you forgot to add the code:
delete();
Once you will add it, you will actually call the function and not only declare it.
Another option, try and set PDO to print error. http://php.net/manual/en/pdo.errorinfo.php Then you will the error printed back in the console.

How to get a text string from sql database to use in html code

I want to get stings form a mysql server to use as text on my webpage.
That way I can edit the text without editing the html file.
Problem is that the code I have to get the string is quite long, and I don't want to paste it everywhere on the page.
I would also like a tip on how to get just one datafield from the server, and not the whole column like I do here.
So this is what I got. And what I think is to write a function I can call from all the places I want the webpage to get a string or field from the sqlserver. But I don't know how. Can anyone help me?
<?php
$con=mysqli_connect("localhost","user..", "passwd..","db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT topic FROM web_content";
$result = $con->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
echo $row["topic"]. "<br>";
}
} else
{
echo "error";
}
$con->close();
?>
Problem is that the code I have to get the string is quite long, and i
dont want to paste it everywhere on the page.
Put the code into a function, call that function wherever you need to. Then it is just a single line you have to insert.
PHP:
<?php
function connect() {
$con=mysqli_connect("localhost","user..", "passwd..","db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
return $con;
}
}
function renderContent($con) {
$sql = "SELECT topic FROM web_content";
$result = $con->query($sql);
if ($con && ($result->num_rows > 0))
{
// output data of each row
while($row = $result->fetch_assoc())
{
echo $row["topic"]. "<br>";
}
} else {
echo "error";
}
}
HTML:
<?php $con = connect(); ?>
[...]
<div>
<?php renderContent($con); ?>
</div>
[...]
I would also like a tip on how to get just one datafield from the
server, and not the whole coloumn like i do here.
Not the whole column would mean not all rows, but one or some selected ones. That means you are looking for sqls ''WHERE'' clause.
SELECT topic FROM web_content WHERE <where clause>;
Where <where clause> is some clause to narrow down the result set. For example you can narrow down to topics containing some string: ... WHERE topid LIKE '%word%'; or by the IDs are a date range of the entries in your table. You should take a look into the documentation of the query syntax for an explanation: http://dev.mysql.com/doc/refman/5.0/en/select.html
Obviously all of this is just a rough sketch of what you are looking for. Lots of things need improving. Using exceptions for error handling is one thing, just to give an example...

PHP constant SQL query

I need to constantly read from my database every 1 second to get the latest values. Here is my code:
<?php
// connect to the "tests" database
$conn = new mysqli('localhost', 'root','','Test');
// check connection
if (mysqli_connect_errno()) {
exit('Connect failed: '. mysqli_connect_error());
}
// SELECT sql query
$sql = "SELECT * FROM `Value`";
// perform the query and store the result
$result = $conn->query($sql);
if (!$result)
print 'Error!';
// if the $result contains at least one row
if ($result->num_rows > 0) {
// output data of each row from $result
while($row = $result->fetch_assoc()) {
$output=$row;
print_r($output);
}
}
else {
print '0 results';
}
$conn->close();
?>
My HTML code refreshes every 1 second as follows:
function reload (){
setInterval(getData,1000);
}
function getData()
{
$.get('test.php', function(data) {
var output = data;
document.getElementById("output").innerHTML = "Info: " + output;
});
}
....
<body onload="reload();">
<p id="output"></p>
</body>
Everything works fine but after around 5-10 mins the MYSQL server crashes. I'm assuming it is being overloaded. My thoughts are that I keep running the php script every time which connects each second. Am I doing this incorrectly? Anyone have any suggestions on a better implementation?
I think you are looking for something to have the database "unclosed" when the script has ended.
In mysqli you can prepend the hostname by adding p: to use a so called persistant database connection
// connect to the "tests" database
$conn = new mysqli('p:localhost', 'root','','Test');
Read more about persistant connections here:
http://php.net/manual/en/features.persistent-connections.php
You might try having it not start the next request until 1 second after the last one finishes by calling setTimeout() in the callback like so:
function getData()
{
$.get('test.php', function(data) {
var output = data;
document.getElementById("output").innerHTML = "Info: " + output;
setTimeout(getData, 1000);
});
}
....
<body onload="getData();">
This is generally a better approach than using setInterval(), cuz you may end up having two concurrent connections and request A may start before request B, but may end after B, because something happened and it took more than a second to finish the request. This could cause some weird behavior.
This may also fix your issue, because maybe it fails because it ends up having several concurrent connections open from the same IP, etc.
Yes it can be implement in a much better way.
As you are using same Database connection configuration every-time, there is no need to connect and close database on page refresh.Connecting to database server every-second is very expensive call.
Why don't you just reload/refresh the query statement?
The idea is:
Use Persistent Database Connection
Refer BlaM answer in following post to know why persistent connections is optimal.
Put the queries in a separate div say #load.
echo '<div id="load">';
// SELECT sql query
$sql = "SELECT * FROM `Value`";
// perform the query and store the result
$result = $conn->query($sql);
if (!$result)
print 'Error!';
// if the $result contains at least one row
if ($result->num_rows > 0) {
// output data of each row from $result
while($row = $result->fetch_assoc()) {
$output=$row;
print_r($output);
}
}
else {
print '0 results';
}
echo '</div>';
Use jquery function to refresh only #load div
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$("#load").load("filename.php #load");
}15000); // refresh every 1 second
</script>
I had implemented this for auto-refresh leaderboard page.It worked perfectly and server didn't crash even in 50 hrs.

Categories