accessing a set of values through single query in postgres - php

Im trying to use postgres for the first time.. I want to retrieve the value company name from a the values inside an array named testArray
The ajax request that I wrote is
$(document).ready(function()
{
var testArray=[0001001871, 0001001843, 0001001853];
$.ajax({
type:'GET',
url: 'php/databaseAccess.php',
data: {'CIKs': testArray},
success: function(success)
{
document.write(success);
}
});
});
and the PHP file that Ive used to access db is
<?php
$link = pg_connect("host=hostname dbname=dbNAme user=username password=password");
if(!$link)
{
//echo "Connection cannot be established";
exit;
}
else
{
$cik_array = $_GET['CIKs'];
$safe_ciks = array();
foreach($cik_array as $cik)
{
$safe_ciks[] = pg_escape_string($cik);
}
$in_string = "'" . implode("','", $safe_ciks) . "'";
$result = pg_exec($link, "select company_name from company_names where cik=".$in_string);
if (!$result) {
//echo "<br> Could not successfully run query from DB";
exit;
}
else
{
echo "<br> Query Executed Successfully<br>";
echo pg_result($result, 0);
}
}
?>
This code will only output the company name with cik 0001001807, I want to get the company names of all values inside the array "testArray" through a single query itself.. How is that possible?

The SQL Query should be
SELECT
company_name
FROM
company_names
WHERE
cik= IN('0001001807','0001001843', '0001001853')
This will return all company names with a CIK in that list. The IN parameter accepts a comma separated list of values.
In terms of passing the Array of CIKs, you could change the "data" parameter of the Ajax request to send the CIKs.
data: {'CIKs': testArray},
Which I believe would pass all of the CIKs to databaseAccess.php, and could then be accessed by the following command
$cik_array = $_GET['CIKs'];
//escape the CIKs, to prevent SQL injection
$safe_ciks = array();
foreach($cik_array as $cik)
{
$safe_ciks[] = pg_escape_string($cik);
}
//get the CIKs in a format compatible with the IN function
$in_string = "'" . implode("','", $safe_ciks) . "'";
That would produce $in_string, which could be used with the SQL query above.

Related

INSERT not complete before SELECT query

I have a PHP script that is split into two separate PHP scripts (As they each serve a purpose and are quite lengthy). For simplicity let's call these 1.php and 2.php.
Script 1.php does an API call to a website passes the payload to a function. Once has truncated and inserted the new records into the table, it then includes the 2nd script. This is where the issue begins. Seemingly when I query the marketPlace table it returns a null array however if I insert a sleep(1) before I include 2.php it works! I can only summize that somehow the truncate and insert queries in 1.php had not completed before the next queries were called? (I've never come across this before!).
There is only one database connection and is defined by a database class which is contained in 1.php:
class Database
{
// This class allows us to access the database from any function with ease
// Just call it with Database::$conn
/** TRUE if static variables have been initialized. FALSE otherwise
*/
private static $init = FALSE;
/** The mysqli connection object
*/
public static $conn;
/** initializes the static class variables. Only runs initialization once.
* does not return anything.
*/
public static function initialize()
{
Global $servername;
Global $username;
Global $password;
Global $dbname;
try {
if (self::$init===TRUE)return;
self::$init = TRUE;
self::$conn = new mysqli($servername, $username, $password, $dbname);
}
catch (exception $e) {
date('Y-m-d H:i:s',time()) . " Cant' connect to MySQL Database - re-trying" . PHP_EOL;
}
}
public static function checkDB()
{
if (!mysqli_ping(self::$conn)) {
self::$init = FALSE;
self::initialize();
}
}
}
The function that trunctated and inserted into the marketplace is:
function processMarketplace($marketData) {
// Decode to JSON
$outputj = json_decode($marketData, true);
$marketplaceCounter = 0;
// Check for success
if (($outputj['success']==true) && (!stristr($marketData, "error"))) {
// Create the blank multiple sql statement
$sql = "TRUNCATE marketplace;"; // Clears down the current marketPlace table ready for new INSERTS
//Loop through each multicall
foreach ($outputj['multiCall'] as $orderBook) {
foreach ($orderBook['marketplace'] as $orderLine) {
$type = $orderLine['type'];
$price = $orderLine['amountCurrency'];
// Add new SQL record (This ignores any duplicate values)
$sql .="INSERT IGNORE INTO marketplace (type, price) VALUES ('" . $type . "'," . $price . ");";
}
$marketplaceCounter++;
}
// Now run all the SQL's to update database table
if (strlen($sql) > 0) {
if (Database::$conn->multi_query($sql) === TRUE) {
echo mysqli_error(Database::$conn);
//echo "New records created successfully";
} else {
echo mysqli_error(Database::$conn);
echo "Error: " . $sql . "<br>" . Database::$conn->error;
}
}
echo date('Y-m-d H:i:s',time()) . " == Marketplace Orderbook retreived == <BR><BR>" . PHP_EOL;
} else {
echo date('Y-m-d H:i:s',time()) . " Failed to get Marketplace data. Output was: " . $marketData . "<BR>" . PHP_EOL;
die();
}
}
I've chased this around for hours and hours and I really don't understand why adding the sleep(1) delay after I have called the processMarketplace() function helps. I've also tried merging 1.php and 2.php together as one script and this yields the same results. 2.php simply does a SELECT * FROM marketPlace query and this returns NULL unless i have the sleep(1).
Am I missing something easy or am I approaching this really badly?
I should add I'm using InnoDB tables.
This is how its called in 1.php:
$marketData = getData($user,$api); // Get Marketplace Data
processMarketplace($marketData); // Process marketplace data
sleep(1); // Bizzare sleep needed for the select statement that follows in 2.php to return non-null
include "2.php"; // Include 2nd script to do some select statements on marketPlace table
2.php contains the following call:
$typeArray = array('1','2','3');
foreach ($typeArray as $type) {
initialPopulate($type);
}
function initialPopulate($type) {
// Reset supplementary prices
mysqli_query(Database::$conn, "UPDATE marketPlace SET price_curr = '999999' WHERE type='" . $type . "'");
echo mysqli_error(Database::$conn);
// Get marketplace data <--- This is the one that is strangely returning Null (after the first loop) unless I place the sleep(1) before including 1.php
$query = "SELECT * FROM marketPlace WHERE type='" . $type . "'";
$result = mysqli_query(Database::$conn, $query);echo mysqli_error(Database::$conn);
$resultNumRows = mysqli_num_rows($result);echo mysqli_error(Database::$conn);
// Create array from mysql data
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
// Get information from the offertypes table
$query2 = "SELECT offerID FROM queryTypes WHERE type='" . $type . "'";
$result2 = mysqli_query(Database::$conn, $query2);echo mysqli_error(Database::$conn);
// Create array from mysql data
$rows2 = array();
while($r2 = mysqli_fetch_row($result2)) {
$rows2[] = $r2;
}
// Loop through marketplace data and apply data from the offertypes table
$sql1 = ""; // Create a blank SQL array that we will use to update the database
$i = 0;
foreach ($rows as $row) {
$sql1 .= "UPDATE marketPlace SET enrichmentType = " . $rows2[$i][0] . " WHERE type='" . $type . "';";
$i++;
}
// Now run all the SQL's to update database table
if (strlen($sql1) > 0) {
if (Database::$conn->multi_query($sql1) === TRUE) {
echo mysqli_error(Database::$conn);
//echo "New records created successfully";
} else {
echo mysqli_error(Database::$conn);
echo "Error: " . $sql1 . "<br>" . Database::$conn->error;
}
}
}
You are using mysqli:multi_query.
Unlike query, multi_query does not retrieve the results immediately. Retrieving the results must be done using mysqli::use_result
An example from the documentation:
/* execute multi query */
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->use_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->close();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
You don't need to print the results, but if you don't retrieve them, you are not guaranteed the INSERT has completed.
Note in the documentation for use_result at
https://www.php.net/manual/en/mysqli.use-result.php
it states
"Either this or the mysqli_store_result() function must be called
before the results of a query can be retrieved, and one or the other
must be called to prevent the next query on that database connection
from failing."
As a result of not calling store_result or use_result, you are having unpredictable results.

Retrieve search results | PHP & SQL

I have a table created with all the fields necessary like (ID, Name, surname, etc.)
In search php file, when you type the ID it shows you all the information corresponding of this ID, e.g. (ID=1, name=Jack)
MY IDEA: When i do a custom search, inside the php I want to add a link to another php file that shows the same search result but with additional info.
QUESTION: How can I call to a custom search result from other php file?
Regarding this example, If I search for ID=2, I want to link to another php file "Extrainfo.php" that shows more info of that custom search.
Here is the code I used:
//database connection
global $conn;
$servername = "localhost"; //host name
$username = "root"; //username
$password = ""; //password
$mysql_database = "info"; //database name
//mysqli prepared statement
$conn = mysqli_connect($servername, $username, $password) or die("Connection failed: " . mysqli_connect_error());
mysqli_select_db($conn,$mysql_database) or die("Opps some thing went wrong");
if(isset($_GET['idNumber']))
{
$IDNUMBER =$_GET['idNumber'];
$stmt = $conn->prepare("select * from madea where idNumber=? ");
$stmt->bind_param('s',$IDNUMBER);
$stmt->execute();
$val = $stmt->get_result();
$row_count= $val->num_rows;
if($row_count>0)
{
$result =$val->fetch_assoc();
echo $result['idNumber'];
echo $result['name'];
}
else
{
echo "identification_number not Match";
}
$stmt->close();
$conn->close();
// Probably need to save the variable to call in the other php file?
$idNumber = $result['idNumber'];
}
?>
Extrainfo
This is what I can show you.
You 1st php,
if(isset($_GET['idNumber']))
{
$IDNUMBER =$_GET['idNumber'];
$stmt = $conn->prepare("select * from madea where idNumber=? ");
$stmt->bind_param('s',$IDNUMBER);
$stmt->execute();
$val = $stmt->get_result();
$row_count= $val->num_rows;
if($row_count>0)
{
$result =$val->fetch_assoc();
echo $result['idNumber'];
echo $result['name'];
echo "More Info";
}
else
{
echo "identification_number not Match";
}
$stmt->close();
$conn->close();
// Probably need to save the variable to call in the other php file?
$idNumber = $result['idNumber'];
}
Now I'm using AJAX and Jquery so please link the appropriate libraries.
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click', '.moreInfo', function(){
$.ajax({
url: 'moreInfo.php',
type: 'post',
data: {
'idNumber': $('.moreInfo').prop('id')
}
}).then(function (response) {
$('#morInfoDiv').html(response);
});
})
})
</script>
The moreInfo.php,
if(isset($_POST['idNumber']))
{
$IDNUMBER =$_GET['idNumber'];
$stmt = $conn->prepare("select * from madea where idNumber=? ");
$stmt->bind_param('s',$IDNUMBER);
$stmt->execute();
$val = $stmt->get_result();
$row_count= $val->num_rows;
if($row_count>0)
{?>
Name:<? echo $result['Name']; ?><br>
Address:<? echo $result['address']; ?><br>
Date of Birth:<? echo $result['dob']; ?><br>
<?php }
else
{
echo "identification_number not Match";
}
$stmt->close();
$conn->close();
}
Now in your 1st php file can have a DIV which will show the response from the moreInfo.php
<html>
<body>
<div id="morInfoDiv"></div>
</body>
</html>
AJAX script will send the data in post method then capture the response text from the 2nd PHP and add it to the DIV ided as "moreInfo".
Well I finally do it by another way.
result.php only added an href that redirects to a moreinfo.php but with the query string of the id number.
Download PDF INFO
And here comes the other part of code in moreinfo.php
At first, get the id number on query string that it previously redirected by the link and get it into a variable to use it after in the sql query
$reportNumber = $_GET['idNumber'];
$result = mysqli_query($con,"SELECT * FROM madea where reportNumber='".$idNumber."'");
And the rest, only show the results what I really need:
while($row = mysqli_fetch_array($result))
{
$html .= '<td>'.$row['idNumber'].'</td><td>' . $row['Name']. '</td>';
}
Hope it helps to further issues. So appreciated for all the help!! :)

Returning a value from database after writing in data as function return

I'm sending my database a string to write into a database. I have 2 fields, one called num that's set to auto increment, and one called cards into which my string is written. So far I've been able to get my php to write the variable into the database, but now I would like it to return the num associated with it, so I can use it on my page. Can anyone help me how to write that, I'm new to php. I guess I need another sql query? (I want it to echo the num column of the row I've just written in, instead of "Records added successfully.").
php:
// Attempt MySQL server connection *
$link = mysqli_connect
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$cards = mysqli_real_escape_string($link, $_GET['cards']); //get data from javascript
$sql = "INSERT INTO drafts (cards) VALUES ('$cards')"; }
mysqli_query($link, $sql);
if(mysqli_query($link, $sql)){
echo mysqli_insert_id($link);
} else {
echo "failed!";
}
// Close connection
mysqli_close($link);
?>
js:
function writeDraft() {
$.ajax({
url: 'php/write.php',
type: 'get', //data type post/get
data: {
cards: output
},
complete: function (response) {
$('#draftNum').text(response.responseText);
},
error: function () {
console.log('Bummer: there was an error!');
}
});
return false;
}
writeDraft();
mysqli_insert_id() will do the job
if(mysqli_query($link, $sql)) {
echo "Records added successfully with id: ".mysqli_insert_id($link);
}
$sql = "SELECT * FROM drafts";
$result = mysqli_query($link, $sql);
$num = mysqli_num_rows($result);
$sql = "INSERT INTO drafts (cards) VALUES ('$cards')"; }
if(mysqli_query($link, $sql)){
echo $num+1, " Records added successfully.";
}
// Close connection
mysqli_close($link);
?>

Checkbox that updates dynamically

I have a checkbox that dynamically updates a MySQL database when it is checked/unchecked using PHP and Ajax.
I am now trying to pass the users name so that the Ajax script can update the database with the users full name.
I have the name held in a variable called $full_name. I cannot seem to get this working though. Please see the code below:
Javascript:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function chkit(uid, chk) {
chk=document.getElementById("chk").checked;
$.ajax({
type: 'GET',
url: 'ajax.php',
data: { chkYesNo: chk, record_id: uid, full_name: user},
success:function(data){
// successful request; do something with the div background color
if(data==1)
{
$("#replace").addClass("checked_div_status").removeClass("replace");//removing first class and adding second class
}
else
{
$("#replace").addClass("replace").removeClass("checked_div_status");//removing second class and adding first class
}
}
});
}
</script>
HTML:
<?php
$record_id = $_GET['veh_id'];
include '../dbconnect.php';
//fetching data from database
$select=mysql_fetch_array(mysql_query("select invoice_checked from vehicle_details where veh_id = '$record_id' "));
?>
<!--The checkbox whose enable to change div his background color and onclick call function to update database-->
<table width=“100%”>
<td id="replace2" class="<?php if($select['invoice_checked']==1) { echo 'checked_div_status2'; } else{ echo 'replace2'; } ?>">
<input name="chk2" type="checkbox" id="chk2" value="1" onclick="chkit2(<?php echo $record_id;?>,'chk2');" <?php if($select['invoice_checked']==1) { echo 'checked'; } else{ echo ''; } ?> />
Invoice Checked
</td>
</table>
Ajax.php:
<?php
mysql_connect("server", "username", "password") or die("Could not connect: " . mysql_error());
mysql_select_db("database");
//here $get variable receive checkbox value true(1) either false(0)
$get=$_GET['chkYesNo'];
//here $get_id variable receive value of current id that you passed
$get_id=$_GET['record_id'];
$get_user=$_GET['full_name'];
if($get=="true")
{
$mysql_query=mysql_query("update vehicle_details set hpi_registered='1', check_user='".$get_user."' where veh_id='".$get_id."'");
$select=mysql_fetch_array(mysql_query("select hpi_registered from vehicle_details where veh_id='".$get_id."'"));
echo $select['hpi_registered'];
}
else
{
$mysql_query=mysql_query("update vehicle_details set hpi_registered='0', check_user='0' where veh_id='".$get_id."'");
$select=mysql_fetch_array(mysql_query("select hpi_registered from vehicle_details where veh_id='".$get_id."'"));
echo $select['hpi_registered'];
}
?>
Any help would be greatly received.
Thanks,
John
Some debug lession for you. Please, check my comments:
// Do not need to replicate your code, if the same things happens in it.
//instead, use a condition to set your variables, and use these variables later.
if ($get == "true") {
$hpi_registered = 1;
//Escape your variable to avoid sql injection
$checkUser = mysqli_real_escape_string($conn, $_GET["full_name"]);
} else {
$hpi_registered = 0;
$checkUser = 0;
}
//Store your query in a variable, so you can debug / dump it
//Let's dump it, see, what is your query, and try to run in directly in sql.
//Maybe it has syntax error.
$sql = "UPDATE vehicle_details SET"
. " hpi_registered='" . intval($hpi_registered) . "',"
. " check_user='" . $checkUser . "'"
. " WHERE veh_id='" . intval($get_id) . "'";
mysqli_query($conn, $sql);
//What happens, if you run it directly in sql? If this fails, now here is your
//error.
$sql = "SELECT hpi_registered"
. " FROM vehicle_details"
. " WHERE veh_id='" . intval($get_id) . "'";
//Do the same like previous query.
$res = mysqli_query($conn, $sql);
$select = mysqli_fetch_array($res);
echo $select['hpi_registered'];
DO NOT use mysql functions, because they are deprecated. Use mysqli or PDO instead.
Avoid sql injection by escaping your variables.

Php code does not send query to database

I am trying to update my database using ajax, but I cannot seem to understand why the php code does not update the database. The script:
function Insert () {
if (XMLHttpRequestObject) {
XMLHttpRequestObject.open("POST","list_insert.php");
XMLHttpRequestObject.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
XMLHttpRequestObject.onreadystatechange = function() {
if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) {
var returnedData = XMLHttpRequestObject.responseText;
var messageDiv = document.getElementById('messageDiv');
messageDiv.innerHTML = returnedData;
}
}
var item = document.getElementById('items').value;
var desc = document.getElementById('description').value;
var data = item + '|' + desc + '|';
XMLHttpRequestObject.send("data=" + data);
}
return false;
}
This is the php code for list_insert:
<?php
include "function_list.php";
$myData = $_POST['data'];
$datetime = date('Y-m-d H:i:s');
list($items,$description) = explode ('|',$myData);
$statement = "INSERT INTO record ";
$statement .= "(items,description) ";
$statement .= "VALUES (";
$statement .= "'".$items."', '".$description."')";
print $statement;
insert($statement);
print "done";
?>
My php function to insert into the db (function_list):
<?php
$con=mysqli_connect("localhost","shop");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
function insert($statement) {
global $con;
mysqli_query($con,$statement);
}
?>
When I print the statement out, the query is correct (I have verified this by manually copy pasting it in mysql). I think the issue is with my insert function.
Any help is appreciated,
thank you.
Firstly, all mysql statements must end in a semicolon.
Secondly, have you made sure $items and $description are the values you expect them to have? Do they have any unescaped quotes?
Also, typically you would send each of the fields as a separate value like so:
var item = document.getElementById('items').value;
var desc = document.getElementById('description').value;
XMLHttpRequestObject.send("items=" + item + "&desc=" + desc);
$$items = $_POST['items'];
$description = $_POST['desc'];
By default, the username for mysql is root, and the password is blank, even though you aren't prompted for these, they are set by default.
I think this might be the issue
in ur global variable $con letz say you put this
$con = new mysqli("host", "user", "pwd", "dbname");
then
function insert($statement) {
$con->query($statement);
$con->close();
}

Categories