Connect to MSSQL
session_start();
// CONEXION
$link = mssql_connect('xxx.xxx.xx.xx', 'xxx', 'xxx');
mssql_select_db("xxx",$link);
if (!$link || !mssql_select_db('BDFlexline', $link)) {
die('No se puede conectar o seleccionar una base de datos!');
}
// FIN CONEXION
if( isset( $_GET["dcto"] ) ){
$dcto = $_GET["dcto"];
$empresa = $_GET['empresa'];
}
query here
$conn ="SELECT
D.TIPODOCTO, d.CORRELATIVO, d.CLIENTE,coalesce(c.razonsocial,'') RAZONSOCIAL,
v.DESCRIPCION as VENDEDOR , D.NUMERO, D.FECHA, D.TOTAL, d.Local as CLUB
from documento D
left join Vendedor v on d.Empresa = v.EMPRESA and d.Vendedor = v.CODIGO
left join ctacte c on c.empresa=d.empresa and c.tipoctacte=d.tipoctacte and c.ctacte =d.idctacte
where d.total >= 0
and d.aprobacion not in ('S','N')
and d.tipodocto='".$dcto."'
and d.empresa='".$empresa."'
and d.vigencia not in ('N','A')
and d.Fecha between CONVERT(VARCHAR(25), DATEADD(mm, -1, DATEADD(dd,-(DAY(GETDATE())-1),GETDATE())),105)
and CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(DATEADD(mm,1,GETDATE()))),DATEADD(mm,1,GETDATE())),105)
order by d.numero";
The query is ok, work as intended from within the SQL management console, but php ...
$result= mssql_query($conn, $link);
############# PRUEBA 1 #################
$json = array();
do {
while ($row = mssql_fetch_object($result)){
$json[] = $row;
}
}while ( mssql_next_result($result) );
echo json_encode($json);
mssql_close($link);
The result is [] but must be:
[{"TIPODOCTO":"COTIZACION","CORRELATIVO":"3059","CLIENTE":"20548547-2","RAZONSOCIAL":"SERVICIOS AIR LMTD","VENDEDOR":"Diana","NUMERO":"0000003079","FECHA":{"date":"2017-07-03 00:00:00.000000","timezone_type":3,"timezone":"Europe\/Berlin"},"TOTAL":"3111964.00000000","CLUB":"ADM"},
{"TIPODOCTO":"COTIZACION","CORRELATIVO":"3062","CLIENTE":"71540800-7","RAZONSOCIAL":"UNIVERSIDAD SAC","VENDEDOR":"Ernesto","NUMERO":"0000003482","FECHA":{"date":"2017-07-05 00:00:00.000000","timezone_type":3,"timezone":"Europe\/Berlin"},"TOTAL":"16670624.00000000","CLUB":"ADM"}] .... and more
I need the result in json format beacause im using angularJS.
Thanks for any idea
I am guessing that the values of $dcto or $empressa are wrong causing a blank result set. For a test do
echo "conn=$conn<br/>";
and see what shows on the screen. Then run that query in the console and make sure it gives you the results you want.
Related
Im doing a Crud with PHP and Oracle, adding the info and deleting the info works fine. But Updating is not saving on the oracle database. Im sure that is something related to the DATE format, because I had the same project with other database and doesnt have any problem. Any guess, whats it happening?
<?php
require_once 'conexion.php';
$idautor = $_POST['ID_AUTOR'];
$nameautor = $_POST['NOMBRE_AUTOR'];
$bdate = date("m-d-Y", strtotime($_POST['FECHA_NACIMIENTO']));
$query = "UPDATE AUTOR SET NOMBRE_AUTOR ='".$nameautor."', FECHA_NACIMIENTO ='".$bdate."' WHERE ID_AUTOR = '".$idautor."' ";
// $query = "UPDATE AUTOR SET NOMBRE_AUTOR ='".$nameautor."' WHERE ID_AUTOR = '".$idautor."' ";
$statement = oci_parse($conexion,$query);
$r = oci_execute($statement,OCI_DEFAULT);
$res = oci_commit($conexion);
if ($res) {
// Mensaje si los datos cambian
echo "<script>alert('Los libros se actualizaron con exito'); window.location.href='sistema.php'</script>";
header('Location: sistema.php');
} else {
// Mensaje si los datos no cambian
echo "<script>alert('Los datos no se pudieron actualizar'); window.location.href='sistema.php'</script>";
// echo oci_error();
}
} else {
// si intenta acceder directamente a esta página, será redirigido a la página de índice
header('Location: sistema.php');
}
Your code is an open door for SQL-Injection. It should be like this:
$query = "UPDATE AUTOR SET
NOMBRE_AUTOR = :nameautor, FECHA_NACIMIENTO = TO_DATE(:bdate, 'YYYY-MM-DD')
WHERE ID_AUTOR = :idautor";
$statement = oci_parse($conexion, $query);
oci_bind_by_name($statement, ':nameautor', $nameautor, 1000, SQLT_CHR);
oci_bind_by_name($statement, ':bdate', date_format($bdate, 'Y-m-d'), 30, SQLT_CHR);
oci_bind_by_name($statement, ':idautor', $idautor, 100, SQLT_INT);
$r = oci_execute($statement, OCI_DEFAULT);
You have to use TO_DATE(...), because type like SQLT_DATE does not exist. Otherwise you rely on current session NLS_DATE_FORMAT which may change at any time.
I'm doing a web service but I need to get data from two different tables taking into account the result of a query in a relational table
How can I make 2 queries to two different tables taking into account a 3 query to obtain the data of those queries?
I have a relational table in which I keep the id's and I need to make a query of that table and then make two queries to two different tables to get the data and show them together in a json to be able to use it
example:
$ query1 = "select * from family where ID = 2";
while ($ query1) {
$ consult2 = "select * from adults where son = $ query1 ['ID']";
$ consult3 = "select * from siblings where son = $ query1 ['ID']";
}
my code for the query is this, is in PHP:
require 'Database.php';
class Union {
function __construct(){
}
public static function getById($id_vehiculo){
// Consulta del vehiculo
$consulta = "SELECT id_relacion, id_operador, id_vehiculo FROM uniontaxioperador WHERE id_vehiculo = ?";
try {
// Preparar sentencia
$comando = Database::getInstance()->getDb()->prepare($consulta);
// Ejecutar sentencia preparada
$comando->execute(array($id_vehiculo));
// Capturar primera fila del resultado
$row = $comando->fetch(PDO::FETCH_ASSOC);
return $row;
} catch (PDOException $e) {
// Aquí puedes clasificar el error dependiendo de la excepción
// para presentarlo en la respuesta Json
return -1;
}
}
}
and to show the json is this:
require 'WS_consulta.php';
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
if (isset($_GET['id_vehiculo'])) {
// Obtener parámetro id_vehiculo
$parametro = $_GET['id_vehiculo'];
// Tratar retorno
$retorno = Union::getById($parametro);
if ($retorno) {
$union["estado"] = "1";
$union["id_relacion"] = $retorno;
// Enviar objeto json de la union
print json_encode($union);
} else {
// Enviar respuesta de error general
print json_encode(
array(
'estado' => '2',
'mensaje' => 'No se obtuvo el registro'
)
);
}
} else {
// Enviar respuesta de error
print json_encode(
array(
'estado' => '3',
'mensaje' => 'Se necesita un identificador'
)
);
}
}
I want to browse data from my postgre database with a "foreach". So I made my request like that :
$conn_string = "host=localhost port=5432 dbname=test_postgre user=postgres password='1234'";
$dbconn = pg_connect($conn_string);
$sql = "SELECT id_traitement FROM public.traitement WHERE id_essai='.$id_essai.';";
$res = pg_query($sql) or die("Pb avec la requete: $sql");
$data = pg_fetch_all($res);
And I get my values with "pg_fetch_all".
After that, I'm looking for compare the data in my database (get with the request) and the data in my web page. So I created this loop :
foreach($array as $ligne_web)
{
foreach($data['id_traitement'] as $ligne_base)
{
if(($ligne_web[0] == $ligne_base) and ($flag))
{
//update de la ligne
update_traitement($id_traitement,$traitement,$code_traitement,$id_essai);
$flag2 = false;
break 1;
}
}
if(($flag) and ($flag2))
{
insert_traitement($id_traitement,$traitement,$code_traitement,$id_essai);
}
}
When I try to run it, firebug tells me : Invalid argument supplied for foreach(). So I don't know how to browse the rows in the database. Certainly my problem is in my foreach, but I don't find what's wrong.
Help please !
It seems your second foreach needs to be '$data' instead of $data['id_traitement']
So your code need to changed to ,
foreach($arr as $ligne_web)
{
foreach($data as $ligne_base) // <-- Here is the correction
{
if(($ligne_web[0] == $ligne_base) and ($flag))
{
------ REST of your Codes ------
Ok, I found an answer. Instead of an array $data from my database, and directly after the request, I created a new array.
Here is my code :
$conn_string = "host=localhost port=5432 dbname=test_postgre user=postgres password='1234'";
$dbconn = pg_connect($conn_string);
$sql = "SELECT id_traitement FROM public.traitement WHERE id_essai='.$id_essai.';";
$res = pg_query($sql) or die("Pb avec la requete: $sql");
$tableau_database_final = array();
while ($data = pg_fetch_all($res)) //Here is my array
{
$tableau_database = array('id_traitement'=>$data['id_traitement']);
array_push($tableau_database_final,$tableau_database);
}
$flag2 = true;
foreach($array as $ligne_web)
{
foreach($tableau_database_final as $ligne_base)
{
echo ($ligne_web[0]);
echo ($ligne_base);
if(($ligne_web[0] == $ligne_base)) //Si il existe une ligne ayant déjà le même id traitement
{
//update de la ligne
update_traitement($id_traitement,$traitement,$code_traitement,$id_essai);
$flag2 = false;
break 1;
}
}
if(($flag) && ($flag2))
{
//insert_traitement($id_traitement,$traitement,$code_traitement,$id_essai);
}
}
I am having an error when inserting data into a table with php using prepared statements, I am stuck cuz it gives me errno(0), I dont know what that error is, can you help me please?. Thanks!
<?php
session_start();
include '../conexion.php';
$nombre = $_POST['Nombre'];
$apellido = $_POST['Apellido'];
$mail = $_POST['Mail'];
$telefono = $_POST['Telefono'];
$ultimaventa = $_POST['Numeroventa'];
$totalcomprado = 0;
$ultimomonto = $_POST['Total'];
if($cons = $mysqli->prepare("select 1 from clientes WHERE Mail=?"));
$cons->bind_param('s',$mail);
$cons->execute();
$cons->store_result();
$existe=$cons->num_rows > 0;
if ($existe) {
$totalcomprado=totalcomprado+$ultimomonto;
if(!($cons=$mysqli->prepare("UPDATE clientes SET nombre=?,apellido=?,Mail=?,telefono=?,ultimaventa=?,ultimomonto=?,totalcomprado= ? WHERE Mail=?"))){
echo "fallo en la preparacion de la consulta:(".$mysqli->errno.")" .$mysqli->error;
}
$cons->bind_param('sssssiis',$nombre,$apellido,$mail,$telefono,$ultimaventa,$totalcomprado,$mail);
if(!($cons->execute())){
echo "fallo ejecutando la consulta:(".$mysqli->errno.")" .$mysqli->error;
}
$cons->close;
} else {
$totalcomprado=$ultimomonto;
if(!($cons=$mysqli->prepare("INSERT into clientes id,nombre,apellido,Mail,telefono,ultimaventa,ultimomonto,totalcomprado values(?,?,?,?,?,?,?)"))){
echo "fallo en la preparacion de la consulta:(".$mysqli->errno.")" .$mysqli->error;
}
$cons->bind_param('sssssis',$nombre,$apellido,$mail,$telefono,$ultimaventa,$totalcomprado);
if(!($cons->execute())){
echo "fallo ejecutando la consulta:(".$mysqli->errno.")" .$mysqli->error;
}
}
Ps.: The data types to insert are ok, the only one Integer is "ultimomonto"
This is the error:
fallo en la preparacion de la consulta:(0)
( ! ) Fatal error: Call to a member function bind_param() on a non-object in C:\wamp\www\mumushop\compras\verificar.php on line 35
You're missing the parentheses arount the column names in the INSERT statement:
if(!($cons=$mysqli->prepare("INSERT into clientes (id,nombre,apellido,Mail,telefono,ultimaventa,ultimomonto,totalcomprado) values(?,?,?,?,?,?,?)"))){
There's another problem that isn't related to the error:
if($cons = $mysqli->prepare("select 1 from clientes WHERE Mail=?"));
The ; ends this if statement, so you're not using it to execute anything based on whether this is successful. I think you want all the rest of the code to be inside this, so it should be:
if($cons = $mysqli->prepare("select 1 from clientes WHERE Mail=?")) {
$cons->bind_param('s',$mail);
$cons->execute();
$cons->store_result();
$existe=$cons->num_rows > 0;
if ($existe) {
...
} else {
...
}
}
The undefined constant error is coming from this line:
$totalcomprado=totalcomprado+$ultimomonto;
You're missing the $ before totalcomprado, it should be:
$totalcomprado=$totalcomprado+$ultimomonto;
or you can write it as:
$totalcomprado += $ultimomonto;
I am currently getting this error: pg_close(): 12 is not a valid PostgreSQL link resource. This is the code that is being executed:
function getProyectosDeUsuarioDAO($idUsuario)
{
$conexion = conectar();
$consulta = "sql things here;";
$resultado = pg_query($consulta) or die('Consulta fallida: ' . pg_last_error());
$lista = array();
$lista = pg_fetch_all($resultado);
var_dump($lista);
$listaProyectos = array();
if(!empty ($lista))
{
foreach ($lista as $p)
{
$proyecto = new Proyecto();
$proyecto->setNombre($p['nombre']);
$proyecto->setFechaInicio($p['fechainicio']);
$proyecto->setFechaFin($p['fechafin']);
$proyecto->setId($p['id']);
//Cargar roles del usuario para cada proyecto
$proyecto->setRoles(getRolesByProyecto($proyecto->getId(),$idUsuario));
array_push($listaProyectos, $proyecto) ;
}
if($conexion)
{
pg_close($conexion); //##############error here#################
}
pg_free_result($resultado);
var_dump($listaProyectos);
return $listaProyectos;
}
var_dumps are made to check if the query is working and it does work; I am not sure how to debug this.
I am using php_pgsql and WAMP server
($conexion) works for checking, however I'm not sure if connection is live or not?