Here is my web service call.
Right now, it's hard coded, but I will stick it behind a User Form.
It's returning an object. How do I use that object with a SQL query? I need to do various Select queries with Products, Manufacturers, in the WHERE criteria I need the contract vehicle ID.
<html>
<head>
<title>Call to Navigator Web Service</title>
</head>
<body>
<?php
$param = array('commodity' => 'LAPTOP', 'placeOfPerformance' => array('location' => 'LSA' , 'lsaStates' => 'NY', 'VA', 'TX', 'oconusStates' => 'ALASKA', 'EMEA'), 'equipmentType' => 'ANY', 'socioEconomicObjective' => 'NONE', 'agencyCode' => '007',);
$client = new SoapClient('https://sso-test.fas.gsa.gov/mpdev/navigator/wsdl');
$results = $client->__soapCall('retrieveContractVehicles', array('parameters' => $param));
print_r($results);
echo ("<br />");
echo ("End of line");
?>
</body>
</html>
class test_object
{
public $contractVehicle = array(
0=>'ITSchedule70',
1=>'ITCommodityProgram'
);
function get_contract()
{
return $this->contractVehicle;
}
}
$var = new test_object(); //let us say this is the part you are getting the result from web service
echo $var->contractVehicle[0]; //this is how you will get ITSchedule70
result:
ITSchedule70
what do you mean by How to insert a query? Do you mean how to save it? I am not sure about the question, but this is how I will insert a query(save to the database)
<?php
define('DB_IP',''); //this is your server's IP/name
define('DB_USERNAME',''); //database username
define('DB_PASSWORD',''); //database password
define('DB_DATABASE',''); //default database to use
class test_object //I do not have the webservice object so I just add this
{
public $contractVehicle = array(
0=>'ITSchedule70',
1=>'ITCommodityProgram'
);
function get_contract()
{
return $this->contractVehicle;
}
}
$var = new test_object(); //lets say this is the variable you will save the result when you invoke the webservice
try
{
//check for connection
$connection = mysqli_connect(DB_IP,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
if(!$connection)
{
$db_conn_err = "Unable to Connect to Database ERROR: ". mysqli_connect_error($connection);
throw new Exception($db_conn_err);
}
}
catch(Exception $e)
{
echo $e->getMessage();
}
$qry_trans = "INSERT INTO `Product`
(
`id`,
`other_column`,
`ContractVehicle`
)
VALUES
(
1, //use your own value depending on your table requirements
'use your own values',
$var->contractVehicle[0] //ITSchedule70
);";
try
{
$result = mysqli_query($connection, $qry_trans ); //execute the query
if( $result )
{
echo 'Successfully saved!';
}
else
{
$err = 'Unable to insert into table err:'.mysqli_error($connection).'<br>';
throw new Exception($err);
}
}
catch(Exception $e)
{
echo $e->getMessage();
}
?>
UPDATE BASED ON YOUR COMMENT
If the data changes, you might want to know which index in the webservice you want to find,
echo $var->contractVehicle[2]; //will return OtherContractVehicle
you might want to clarify your question or atleast post your sample data so that I can analyse it more.
Related
I have problem in updating fields in database via codeigniter update method
My controller:
$database = array(
'last_location' => $url[5]."-".$url[6],
'last_date_location' => $url[3]." ".$url[4],
);
$user = $this->API_model->get_user($url[0]);
print_r($user);
if ($this->db->update('user', $database , $user['id']) === true) {
print_r($database);
echo "MEI_TRUE";
}else {
echo "MEI_FALSE";
}
browser return MEI_TRUE that mean database successfully updated but when I check database in phpmyadmin nothing changed :(
what 's the problem?
It should work now.
$database = array(
'last_location' => $url[5]."-".$url[6],
'last_date_location' => $url[3]." ".$url[4],
);
$user = $this->API_model->get_user($url[0]);
print_r($user);
$query = $this->db->where('id',$user['id'])
->update('user', $database);
if ($query) {
print_r($database);
echo "MEI_TRUE";
}else {
echo "MEI_FALSE";
}
Can you try something like below,
$database = array(
'last_location' => $url[5]."-".$url[6],
'last_date_location' => $url[3]." ".$url[4],
);
$this->db->where('id', $user['id']);
$this->db->update('user', $database );
Hope this will help you
the thing is - what do you want to update ?
the 3rd parameter of the update query lets you enable the where clause as a string
although your example is pretty dangerous, try the following
if ($this->db->update('user', $database , "id = ".$user['id']) === true)
{
print_r($database);
echo "MEI_TRUE";
}
else
{
echo "MEI_FALSE";
}
the better way would be (as Dhanesh already mentioned):
$blnUpdateSuccess = $this->db->where("id", $user['id'])->update("user",$database);
if ($blnUpdateSuccess)
{
print_r($database);
echo "MEI_TRUE";
}
else
{
echo "MEI_FALSE";
}
For more information read the Documentation here
This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 6 years ago.
I have a php file and mysql database with fields named planname and price,and i want a dropdown list of all the planname from database and according to the planname the price of particular planname should be shown in text box below.
Here is my php file;
<?php
$servername = xxxxxxx;
$username = xxxxxx;
$password = xxxxxx";
try {
$conn = new PDO("mysql:host=$servername;dbname=vnet", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$sql="SELECT id,planname,price FROM plan";
/* You can add order by clause to the sql statement if the names are to be displayed in alphabetical order */
echo "<select name=planname value=''>Plan Name</option>"; // list box select command
foreach ($conn->query($sql) as $row){//Array or records stored in $row
echo "<option value=$row[id]>$row[planname]</option>";
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box
if(isset($_REQUEST['planname'])){
// connection should be on this page
$sql = mysql_query("select price from plan where planname =".$_REQUEST['planname']);
$res = mysql_fetch_assoc($sql);
echo $res['price'];die;
}
echo '<input type="text3" name="price[]" id="price" value="', $row['price'], '" disabled="disabled" />';
?>
I got the list in dropdown but not able to get price according to planname dynamically.can anyone help me out of this?
$sql = mysql_query("select price from plan where planname =".$_REQUEST['planname']);
You are searching in the column planname, but by defining the <option>'s as
echo "<option value=$row[id]>$row[planname]</option>";
You are sending the id as value.
So your query should be:
$sql = mysql_query("select price from plan where id =".$_REQUEST['planname']);
// better: pdos prepared statements
$stmt = $conn->prepare("select sub_id from sub where sub_id = ?");
$stmt->execute(array($_GET['planname']));
Also read the other comments. You are mixing the mysql_* api and PDO, you should only use PDO. Why shouldn't I use mysql_* functions in PHP? And see this when you are at it: How can I prevent SQL injection in PHP?
The structure of your code will make maintainance really troublesome, you should first do all the logical work, gather all the data and then display your html and the data in the next step.
How to do implement your plan
You need / might want to use two different scripts, to get your dynamic ui. (You could use the same file but things could get messy and it is better to split tasks)
1. The frontend:
As previously said, you should structure code in a meaningful order. You can see I am first setting up the database connection, then doing the querying and already fetching of the result. This way I already have all the data needed before I start to output other stuff (if something goes wrong as in I notice there is something invalid with the data/whatever I could still redirect to another page as there has not been a header sent).
To start the output, I added some basic HTML structure to your script, don't know if you already had it, at least it is not in your snippet.
So I added header and body, in the header is the javascript code which will execute the request to the backend and receive the response to act accordingly.
Note:
I am not really familiar with vanilla javascript, so I just followed a
tutorial http://www.w3schools.com/ajax/ajax_php.asp
I think you should check out jQuery if you haven't yet, it makes things really really easy.
Other than that I reduced some noise and used other code formatting than you, basically I don't like to use echo to output my HTML as some IDEs are not able to do syntax highlighting when done so.
I also added a <p></p> in which the error message can be displayed to the user, if something in the backend goes wrong.
<?php
$servername = 'xxxxxxx';
$username = 'xxxxxx';
$password = 'xxxxxx';
try {
$conn = new PDO("mysql:host=$servername;dbname=vnet", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
trigger_error("Connection failed: " . $e->getMessage());
}
$selectPlans = "SELECT id, planname, price FROM plan";
$rows = $conn->query($selectPlans)->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function getPrice(id){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
var jsonObj = JSON.parse(xmlhttp.responseText);
if(jsonObj.success === true){
document.getElementById("price").value = jsonObj.price;
}else{
document.getElementById("price").innerHTML = jsonObj.message;
}
}
};
xmlhttp.open("GET", "ajax.php?id=" + id, true);
xmlhttp.send();
}
</script>
</head>
<body>
<select name="planname" id="plannameSelect" onchange="getPrice(this.value)">
<?php foreach ($rows as $row): ?>
<option value="<?= $row['id'] ?>"><?= $row['planname'] ?></option>
<?php endforeach; ?>
</select>
<input type="text" name="price[]" value="" id="price" disabled="disabled">
<p id="error"></p>
</body>
2. The backend: (in this case called ajax.php)
A simple piece of code, nothing special to do.
First step: validating the input. In this case, I simply check if there is an id in the $_GET-Array. I used json_encode() on an array in which I tell the frontend whether the operation was successfull or not. The first case of failure would be if there was no id.
Then connect to the database, ask for errors and if so return them immediately to the user (by using echo), again via the json_encoded array.
Prepare the statement for selecting the price of the id (I skipped the error check here, you might want to add it). Then execute it.
Check if it was successfull -> return the json_encoded array as success and with the price, or set success false again and return the array with an error message.
<?php
$servername = 'xxxxxxx';
$username = 'xxxxxx';
$password = 'xxxxxx';
if(!isset($_GET['id'])){
echo json_encode(array('success' => false, 'price' => '', 'message' => 'no id given'));
exit;
}
try {
$conn = new PDO("mysql:host=$servername;dbname=vnet", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
trigger_error("Connection failed: " . $e->getMessage());
echo json_encode(array('success' => false, 'price' => '', 'message' => 'shit happened' . $e->getMessage()));
exit;
}
$stmt = $conn->prepare("SELECT price FROM plan WHERE id = ?");
$stmt->execute(array($_GET['id']));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($result === false){
trigger_error('Query failed: ' . $conn->errorInfo());
echo json_encode(array('success' => false, 'price' => '', 'message' => 'shit happened'));
exit;
} else {
echo json_encode(array('success' => true, 'price' => $result['price'], 'message' => ''));
exit;
}
I cannot resolve why what works locally fails at the host server. It connects to the database, retrieves and displays data, but it fails to retrieve the data and include the form. Hopefully, I have included enough code.
First the data is retrieved and displayed:
/*------------------- DISPLAY ACCESSORIES ------------------*/
if(isset($_GET['table']) && $_GET['table'] === "accessories")
{
$table = 'accessories';
include '../includes/dbconnect.php';
try {
$result = $db->query("SELECT * FROM $table");
while($row = $result->fetch(PDO::FETCH_ASSOC)){
$accessories[] = array(
'id' => $row['id'],
'buy_link' => $row['buy_link'],
'img' => $row['img'],
'item_number' => $row['item_number'],
'name' => $row['name'],
'description' => $row['description'],
'laser_series' => $row['laser_series'],
'laser_model' => $row['laser_model'],
'quantity' => $row['quantity'],
'price' => $row['price'],
);
}
}
catch (PDOException $e)
{
$error = 'Error fetching data.' . $e->getMessage();
include 'error.html.php';
exit();
}
try {
$sql2 = 'DESCRIBE accessories';
$s2= $db->prepare($sql2);
$s2->execute();
$table_fields = $s2->fetchAll(PDO::FETCH_COLUMN);
}
catch (PDOException $e)
{
$error = 'Error fetching data from database.';
include 'error.html.php';
exit();
}
// Close database connection
$db = null;
// Display data on included page
include 'display-accessories.html.php';
exit();
}
Then, in the row the user wishes to edit, he clicks the edit button. Here's that html:
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post">
<input type="hidden" name="id" value="<?php htmlout($accessory['id']); ?>">
<button class="btn btn-default btn-sm" type="submit" name="action" value="edit_accessories">Edit</button>
</form>
Clicking the edit button triggers this php, which fails (not locally). It does not include the file (the path is correct; in the same folder).
/*------------------- EDIT ACCESSORIES ------------------*/
if(isset($_POST['action']) && $_POST['action'] === "edit_accessories")
{
// Assign name of table being queried to variable
$table = 'accessories';
// Sanitize posted data
$id = sanitize($_POST['id']);
// Connect to database
include '../includes/dbconnect.php';
try {
$sql = "SELECT * FROM $table WHERE id = :id";
$s = $db->prepare($sql);
$s->bindValue(':id', $id);
$s->execute();
}
catch (PDOException $e)
{
$error = 'Error fetching data.' . $e->getMessage();
include 'error.html.php';
exit();
}
// Store single row result in $item associative array
$item = $s->fetch(PDO::FETCH_ASSOC);
// Close database connection
$db = null;
// Display row content in form
include 'edit-accessories-form.html.php';
exit();
}
If anyone has any ideas why this does not work, I welcome your insight!
Just change the sentence:
FROM: '../includes/dbconnect.php';
TO: $_SERVER['DOCUMENT_ROOT'].'/includes/dbconnect.php';
In the server the path can't be write as '../' because there is a whole different server path configuration.
I have this code is working fine my application gets the data with json and is all fine but when I insert special characters like ñ which I need to get I can't have been told that I should use the utf8_encode but I just don't know how to apply it here since.
<?php
require_once(dirname(__FILE__).'/ConnectionInfo.php');
//Set up our connection
$connectionInfo = new ConnectionInfo();
$connectionInfo->GetConnection();
if (!$connectionInfo->conn)
{
//Connection failed
echo 'No Connection';
}
else
{
if (isset($_POST['mod']) && isset($_POST['lec']) && isset($_POST['clase']))
{
$mod = $_POST['mod'];
$lec = $_POST['lec'];
$clase = $_POST['clase'];
//Create query to retrieve all contacts
$query = 'SELECT TituloEjercicio,PreguntaEjercicio,Opcion1Ejercicio,Opcion2Ejercicio,Opcion3Ejercicio,Opcion4Ejercicio,EstaCorrectaEjercicio FROM ejercicios WHERE QueModulo = ? and QueLeccion = ? and Queclase = ?';
$params = array($mod,$lec,$clase);
$stmt = sqlsrv_query($connectionInfo->conn, $query,$params);
if (!$stmt)
{
//Query failed
echo 'Query failed';
}
else
{
$contacts = array(); //Create an array to hold all of the contacts
//Query successful, begin putting each contact into an array of contacts
while ($row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC)) //While there are still contacts
{
//Create an associative array to hold the current contact
//the names must match exactly the property names in the contact class in our C# code.
$contact = array("lbl_variable_cuestionario_titulo" => $row['TituloEjercicio'],
"lbl_variable_pregunta" => $row['PreguntaEjercicio'],
"opcion1" => $row['Opcion1Ejercicio'],
"opcion2" => $row['Opcion2Ejercicio'],
"opcion3" => $row['Opcion3Ejercicio'],
"opcion4" => $row['Opcion4Ejercicio'],
"EstaCorrecta" => $row['EstaCorrectaEjercicio']
);
//Add the contact to the contacts array
array_push($contacts, $contact);
}
//Echo out the contacts array in JSON format
echo json_encode($contacts);
sqlsrv_close($connectionInfo->conn);
}
}
sqlsrv_close($connectionInfo->conn);
}
sqlsrv_close($connectionInfo->conn);
?>
If your issue lies with pushing non-latin characters to MySQL then you might just have to configure your database to use UTF8. There are good tutorials online that show you how to do that.
I have retrieved data from DB and inserted into a html table however I want to make each value in the table a hyperlink to another page. Below I have tried making the pupil_id and link to a profile.php but all pupil_id values have now vanished!
(if (!isset($_POST['search'])) {
$pupils = mysql_query("SELECT * FROM pupil") or die("Cant find Pupils");
$count = mysql_num_rows($pupils);
if ($count == 0) {
$totalpupil = "There are currently no Pupils in the system.";
} else {
while ($row = mysql_fetch_array($pupils)) {
?>
<tr>
<td><?php echo '<a href="profile.php?id=' .$row['pupil_id'] . '"</a>' ?></td>
<td><?php echo $row['pupil_name'] ?></td>
<td><?php echo $row['class_id'] ?></td>
</tr>
<?php
}
}
})
The finishing table should display every hyperlink as a hyperlink to another page. Any help?
Because your HTML is invalid, you are missing a closing > and you have no text defined for the hyperlink
<?php echo '<a href="profile.php?id=' .$row['pupil_id'] . '"</a>' ?> //Wrong
Correct would be
<?php echo ''.$row['pupil_id'].''; ?>
Try replace this:
<?php echo '<a href="profile.php?id=' .$row['pupil_id'] . '"</a>' ?>
with this:
<?php echo "<a href='profile.php?id=".$row['pupil_id']."'>link</a>"; ?>
Also, you dont have <table> tags at all.
You don't put any text between your link tags, text here
Maybe this will help you:
<td><?php echo ''.$row['pupil_name'].'' ?></td>
http://uk3.php.net/mysql_query
Watch out, which ever resource you are learning from may well be quite old. mysql_query is now deprecated.
http://uk3.php.net/manual/en/ref.pdo-mysql.php is a replacement.
Here is a kick starter to using PDO (this is much much safer) i write a while ago.
Include this file in which ever php script needs to access your db. An example file name would be 'database.php' but that is your call. Set the namespace from 'yourproject' to whatever your project is called. Correct the database credentials to suit your database
This will save you a lot of headaches hopefully!
I have given some example uses at the bottom for you. I remember when i started out getting clear advice was sometimes hard to come by.
//***** in a database class file*****/
namespace yourproject;
class Database {
private $db_con = '';
/*** Function to login to the database ***/
public function db_login()
{
// Try to connect
try{
// YOUR LOGIN DETAILS:
$db_hostname = 'localhost';
$db_database = 'yourdatabasename';
$db_username = 'yourdatabaseusername';
$db_password = 'yourdatabasepassword';
// Connect to the server and select database
$this->db_con = new \PDO("mysql:host=$db_hostname;dbname=$db_database",
"$db_username",
"$db_password",
array(\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
// Prevent emulation of prepared statements for security
$this->db_con->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
$this->db_con->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
return true;
}
// If it fails, send user to maintenance page
catch(PDOException $e)
{
header("location:http://yourwebsiteurl.com/maintenance.php");
exit();
}
}
/*** Function for database control ***/
public function db_control($query , $parameters, $returnID = false)
{
if(!is_array($query) && is_array($parameters))
{
try{
//prepare the statement
$statement = $this->db_con->prepare($query);
//execute the statement
$statement->execute($parameters);
//check whether this is a select, if it is then we need to retrieve the selected data
if(strpos($query, 'SELECT') !== false)
{
//fetch the results
$result = array();
while( $row = $statement->fetch(\PDO::FETCH_ASSOC) )
{
$result[] = $row;
}
//count the results
$count = count($result);
//return the array
return array( 'results' => $result, 'result_count' => $count );
}
//else return the number of affected rows
else{
//count the affected rows and place into a returnable array
$affected_rows = $statement->rowCount();
$returnArray = array('result_count' => $affected_rows);
//check to see if we are to return a newly inserted autoincrement ID from an INSERT
if($returnID)
{
//find the newly created ID and add this data to the return array
$insertID = $this->db_con->lastInsertId();
$returnArray['ID'] = $insertID;
}
return $returnArray;
}
}
catch(PDOException $e)
{
return false;
}
}
else{
return false;
}
}
}
// Start the database class and connect to the database then create a globally accessible function for ease of reference
$db = new \yourproject\Database();
$db->db_login();
function _db( $sql , $params , $returnID = false ){
return $GLOBALS['db']->db_control( $sql , $params , $returnID );
}
When you include this file you now have a new function: _db(). As the function is global it can be called from within any class or std file. When called into a variable as demonstrated below will result in an array like this:
array(
'result_count' => 3,
'results' => array(
array(/*row 1*/),
array(/*row 2*/),
array(/*row 3*/),
.. etc etc
)
)
Now include your database file in your php script:
//call in the database file
require_once 'database.php';
//your query as in the op
$sql = 'SELECT * FROM pupil';
//your params for the query
$params = array();
//running the query and getting the results returned into a variable called $query
$query = _db($sql,$params);
//if no results
if( $query['result_count'] == 0 )
{
echo 'sorry no pupils in the system';
}
else
{
//looping through each result and printing into a html table row
for( $i = 0 ; $i < $query['result_count'] ; ++$i )
{
echo '<tr><td><a href="profile.php?id=' . $query['results'][$i]['pupil_id'] . '"</a></td>';
echo '<td>'. $query['results'][$i]['pupil_name'] . '</td>';
echo '<td>'. $query['results'][$i]['class_id'] . '</td></tr>';
}
}
Your original query but with some parameters passed through
//Passing parameters to the query
//your query
$sql = 'SELECT * FROM pupil WHERE pupil_id = :pupil_id AND class_id = :class_id';
//your params for the query
$params = array(
':pupil_id' => 12,
':class_id' => 17,
);
//running the query and getting the results returned into a variable called $query
$query = _db($sql,$params);
//deal with the results as normal...
If you set the 3rd param as true you can return the automatic id of the row just entered eg:
//where $sql is a query that will INSERT a row
$query = _db($sql,$params, true);