Fetch data row by row with Ajax - php

I want to fetch data from my mySQL db row by row so that I can combine the first column with the second and so on in a list.
I've searched and found solutions but none of them are using PDO.
Here's the php code that I'm using now to give me the first value written to the console with AJAX.
$db = new PDO('mysql:host=XXXXX;dbname=XXXXX;charset=utf8', 'XXXXX',
'XXXXX');
$partyID = ($_POST['paramName']);
$stmt = $db->prepare("SELECT * FROM wapp_Wishes_db WHERE partyID = '$partyID'");
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rows[0]);
I've also tried using Fetch_assoc, but as you can see I'm probably using it completely wrong.

Why would you like to combine those rows? Encode them and use the variables in javascript:
$stmt = $db->prepare("SELECT *
FROM wapp_Wishes_db
WHERE partyID = :partyId");
$stmt->bindParam(':partyId', $_POST['paramName'], PDO::PARAM_STR, 12);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rows);

Maybe you can use implode like that :
$result = implode('&',$rows);
echo json_encode($result);
replace '&' by what you want.
More info here on php manual

Related

Get only one Jsonobject reponse while there are two match data?

I wrote the PHP code below to get multiple JSON objects from my database:
<?php
$connection = new mysqli("localhost","root","","Fubon");
$dateCheckSQLCommand = $connection->prepare("select * from clockindata where Month(date)= 11 ");
$dateCheckSQLCommand -> execute();
$result = $dateCheckSQLCommand->get_result();
$rowOfDate = $result->fetch_assoc();
echo json_encode($rowOfDate);
I expect to get two JSON objects when I run the PHP file like below because I have two month 11 data matching in My MySQL:
[{"account":"Fu","ssid":"Fu","date":"2019-11-14 00:00:00"},{"account":"Fu","ssid":"Fu","date":"2019-11-21 00:00:00"}]
But I only get one JSON object like below:
{"account":"Fu","ssid":"Fu","date":"2019-11-14 00:00:00"}
How to solve the problem?
You need to fetch each row in your result. You're only calling fetch_assoc() once in your code. You need to either loop until fetch_assoc() returns false, or use fetch_all() (which is supported only by the mysqlnd driver.)
$connection = new mysqli("localhost","root","","Fubon");
$dateCheckSQLCommand = $connection->prepare("select * from clockindata where Month(date)= 11 ");
$dateCheckSQLCommand -> execute();
$result = $dateCheckSQLCommand->get_result();
/*** either this ****/
while($row = $result->fetch_assoc()) {
$rowOfDate[] = $row;
}
/*** or this, if it's supported ***/
$rowOfDate = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($rowOfDate);
The best solution, though, will involve changing the database API you're using. Mysqli is not very user friendly, and was written as a low-level one-to-one mapping of MySQL's C API. Even using PDO, which is PHP's other built-in database API, will make your code much easier to work with. Here's how that would look, including a parameterized query for safety:
$month = 11;
$db = new PDO("mysql:host=localhost;dbname=Fubon", "root", "of course you have a password");
$stmt = $db->prepare("SELECT * FROM clockindata WHERE MONTH(`date`) = ?");
$stmt->execute([$month]);
$data = $stmt->fetchAll(\PDO::FETCH_ASSOC);
// if your script is outputting JSON, set the MIME type appropriately
header("Content-Type: application/json");
echo json_encode($data);
Especially when you're using parameters in your query (which you already are, of course, right?) PDO becomes far easier to use than Mysqli.

Can't call PHP function multiple times

I am trying to fix my previous problem with an extra query.
However, when I am trying to make multiple calls to my PHP function it just shows the first one and not both.
Code:
<?php function test($colour)
{
$pdo = new PDO("pgsql:host=localhost;dbname=testdb","teun",""); // or use a global one
//$pdo = $GLOBALS['pdo'];
$sth = $pdo->prepare("SELECT * FROM threads WHERE cat_id = :cat_id AND thread_date=(
SELECT max(thread_date) FROM threads
)");
$sth->bindParam(':cat_id', $colour, PDO::PARAM_STR, 12);
$sth->execute();
$result = $sth->fetch();
echo $result ["thread_name"];
}
?>
(yes, I know this is unsafe but I want to achieve my thing first before I work on the safe part).
I call it using test ($row['extra_cat_id'])
Thanks!
fetch() only fetches 1 row, see PDOStatement::fetch.
Either iterate using fetch() to fetch 1 by 1, or use the fetchAll() method to fetch all results, see PDOStatement::fetchAll

PHP Fetchall only returning column header

I have a database that I am trying to query to get information to display to my user. I have used
fetch(PDO::FETCH_ASSOC)
before when retrieving a single row or
$row = mysql_fetch_array($result)
with good results. However, it is my understanding that it is better practice to use PDO so that is what I am trying to do.
The problem I am running into is that my results are only showing me the first row of the data I need. In this instance it is displaying the column header over and over and never giving me the data.
$stmt = $conn->prepare("SELECT ? FROM application");
$stmt->bindparam(1, $application_ID);
$stmt->execute();
$results = $stmt->fetchall(PDO::FETCH_ASSOC);
foreach($results as $row){
echo $row['application_ID'];
}
Here are the results
application_IDapplication_IDapplication_IDapplication_ID
It is good that you are aware that MySQL has been oficially deprecated and now we are supposed to used MySQLi or better yet, PDO.
Since you are not accepting any user input, there is no need of using a prepared statement.
Simply do this:
$stmt = $conn->query("SELECT * FROM application");
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($results as $row){
echo $row['application_ID'];
//output other rows here
}
As per the php documentation pdo::fetchAll
you have to use fetchAll, instead of fetchall.

PHP PDO mysql_data_seek

I'm converting some code to access a database to PDO. I've come across the following:
mysql_data_seek($result, 0);
$row0 = mysql_fetch_assoc($result);
And from my readings on Google etc, I understand this should be:
$row0 = $result->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_ABS, 0);
however this isn't working. Any ideas what i'm doing wrong?
From manual;
Fetches a row from a result set associated with a PDOStatement object. The fetch_style parameter determines how PDO returns the row.
You need a stmt that was created by PDO::prepare method.
Let's see this;
// assuming $pdo was created before as well
$sth = $pdo->prepare("SELECT name, colour FROM fruit");
// exec here
$sth->execute();
// get a row here
$row = $sth->fetch(PDO::FETCH_ASSOC);
// here probably you'll get a print out like
// Array([name] => Banana, [color] => Yellow)
print_r($row);
See more details here: PHP PDOStatement::fetch
First option with query:
You can iterate query result directly..
foreach ($db->query($sql) as $row) {
echo $row['FirstName'];
}
Second option with execute:
$sth = $db->prepare($sql);
$sth->execute();
$row = $sth->fetch(PDO::FETCH_ASSOC); // fetch the next row from statement
echo $row['FirstName'];

Store elememts of a datatable into an array

I have a database table made in phpmyadmin. I want the elements of the table to be stored row-wise in an array. I have three columns named edge_id, vertexA and VertexB. I want the elements of these three columns to be stored into an array.
I don't know those commands for PHP. Please help me out.
i have columns in my table named
"vertexa" and "vertexb",i want to
store the colums in two separate
arrays ...how can i do it??
The simplest way would be:
$db = new PDO('mysql:host=localhost;dbname=your_db_name;', $user, $password);
$vertices_a = array();
$vertices_b = array();
foreach($db->query('SELECT * from your_table_name') as $row){
$id = $row['edge_id'];
// add them to the proper array using the edge_id as the index -
// this assumes edge_id is unique
$vertices_a[$id] = $row['vertexa'];
$vertices_b[$id] $row['vertexb'];
}
So with PDO:
$db = new PDO('mysql:host=localhost;dbname=your_db_name;', $user, $password);
foreach($db->query('SELECT * from your_table_name') as $row){
echo $row['edge_id'];
echo $row['vertexA'];
echo $row['vertexB'];
}
Now if you need to use input data you need to escape it. The best way to do this is to use a prepared statement because escaping is handle when the parameters are bound to the query.
Lets say for example you want to use the edge_id supplied from a get request like mysite.com/show-boundry.php?edge=5...
$db = new PDO('mysql:host=localhost;dbname=your_db_name;', $user, $password);
// create a prepared statement
$stmt = $db->prepare('SELECT * from your_table_name WHERE edge_id = ?');
// execute the statement binding the edge_id request parameter to the prepared query
$stmt->execute(array($_GET['edge']));
// loop through the results
while(false !== ($row = $stmt->fetch(PDO::FETCH_ASSOC))){
echo $row['edge_id'];
echo $row['vertexA'];
echo $row['vertexB'];
}
Also you shouldnt use mixed case column/table names like vertexA instead use underscore separators like vertex_a.
You first need to connect to the database:
$link = mysql_connect('localhost','username','password');
if (!$link) {
// Cannot connect
}
$ret = mysql_select_db('database-name', $link);
if (!$ret) {
// Cannot select database
}
Then you need to execute your query:
$ret = mysql_query('SELECT * FROM `table`;', $link);
if (!$ret) {
// Query failed
}
Then you simply load each row:
$data = array();
while ($row = mysql_fetch_assoc($ret)) {
$data[] = $row;
}
Then you should free your request results
mysql_free_result($ret);
And voilĂ .
$res = mysql_query("............");
$row = mysql_fetch_array($res);
Checkout: mysql_fetch_array PHP page

Categories