Parse query mdb on php - php

I have code like these
<?php
$mdb_file = realpath('../PEB_MDB/dbPEB.mdb');
$dsn='Driver={MSAccess};DBQ='.$mdb_file.';';
//$mdb_file = $_SERVER['DOCUMENT_ROOT']."/sapfiles/web_supp/PEB_MDB/dbPEB.mdb";
$user = "";
$password = "MumtazFarisHana";
$conn = odbc_connect($dsn,$user,$password);
var_dump($conn);
$sql = "SELECT a.NAMABELI,s.URBRG1,a.NAMABELI,a.NEGBELI,a.NEGTUJU,a.CAR,a.KDKTR,a.PELMUAT,
a.NODAFT,a.TGDAFT,a.FOB,d.NoDok,d.TgDok FROM (tblpebhdr AS a INNER JOIN tblpebdok AS d
ON a.CAR = d.CAR) INNER JOIN tblpebdtl AS s ON a.CAR = s.CAR
WHERE d.KdDok='380' and a.TGDAFT>=#01/jan/2018# AND a.TGDAFT<=#01/Apr/2018#";
$rs = odbc_exec($conn, $sql) or die(odbc_errormsg());
var_dump($rs);
?>
When I try running these code, it said Couldn't parse SQL, if I change my query like SELECT * FROM tblpebhdr it working prefectly, But why my first query didn't work at all? Is because the hashtag (#)? or something else?

Your syntax is correct Access SQL syntax, so try to remove one field at the time and you should find the offending field name.
Also, never use text months in filters as the names are expected to be localised, and - while the "reverse" US format is accepted, thus can't be the source of your error, if TGDAFT is of data type DateTime - make it a habit to use the ISO sequence yyyy-mm-dd:
a.TGDAFT>=#2018/01/01# AND a.TGDAFT<=#2018/04/01#";

Related

Selecting data from two tables, inserting it into new table? (SQL / PHP)

For days I've been trying the following: I have a HTML form. After receiving the data (MENGE / PRODUKT / LIEFERANT) I want to insert the data into the table "bestellung". For this purpose, I need two different data points from two different tables: the Waren_ID from the WARE table and the kunde_lieferant_ID from the kunde_lieferant table.
Every time I try this, I get a new error in whatever form (syntax, ...). I've read dozens of Stack Overflow posts, but none helped me out. It would be great if someone could give me a hint :-)
<?php
$server="localhost";
$username="xy";
$passwort="xy";
$database="xy";
$conn=mysqli_connect($server, $username, $passwort, $database)
or die ("Fehler im System");
if (!empty($_POST["Lieferant"]) AND !empty ($_POST["Produkt"]) AND !empty ($_POST["Menge"]))
{
$Menge = $_POST ["Menge"];
$Produkt = $_POST["Produkt"];
$Lieferant = $_POST ["Lieferant"];
$sql="SELECT Waren_ID FROM ware WHERE Name='$Produkt'";
$speichern = mysqli_query($conn, $sql);
$rs = mysqli_fetch_array($speichern);
$Waren_ID=$rs['Waren_ID'];
$abfrage="SELECT kunde_lieferant_ID FROM kunde_lieferant WHERE Name='$Lieferant'";
$result = mysqli_query($conn, $abfrage);
$ts = mysqli_fetch_array($result);
$kunde_lieferant_ID=$ts['kunde_lieferant_ID'];
$final="INSERT INTO bestellung (Menge, Waren_ID, kunde_lieferant_ID) values ($Menge, $Waren_ID, $kunde_lieferant_ID)";
$ende=mysqli_query($conn, $final)
or die ("Fehlgeschlagen: SQL-Error:" . mysqli_error($conn));
}
mysqli_close($conn);
?>
Add MYSQLI_ASSOC as a second argument to mysqli_fetch_array() to use the key name instead of the integer index number:
$rs = mysqli_fetch_array($speichern); becomes $rs = mysqli_fetch_array($speichern, MYSQLI_ASSOC);
and
$ts = mysqli_fetch_array($result); becomes $ts = mysqli_fetch_array($result, MYSQLI_ASSOC);
You may also use $rs = mysqli_fetch_assoc($speichern); and $rs = mysqli_fetch_assoc($speichern); to access the associative array by key name instead of index.
One potential problem in your insert statement is that you are not single-quoting the values that your are passing : to MySQL, this means that they are all numeric (but is « Menge » numeric for example ?).
To avoid this and also prevent your code from SQL injection, you probably should use parameterized queries.
By looking more globally at your code, I think that you should be able to achieve what you want in a single INSERT ...SELECT statement, like :
INSERT INTO bestellung
SELECT
:menge,
w.Waren_ID,
k.kunde_lieferant_ID
FROM
ware w
INNER JOIN kunde_lieferant k
ON k.Name = :lieferant
WHERE w.Name = :produkt

sql function statement w joins & calling specified records via variable assignment in php

first time user of stack here. Apologies for the long winded title, but i wasn't exactly sure on how to word it. So here's my setup.
Within my functions.php file i have the following sql:
function getCustomersTable() {
$sql = "SELECT * FROM customers
LEFT JOIN leads on customers.customer_id = leads.customer_id
LEFT JOIN events on customers.customer_id = events.customer_id";
return resourceToTwoDimensionalArray(query($sql));
}
I will be inserting certain data from my query into a html table. My code for that is:
$customers = $getCustomersTable();
foreach($customers as $customer) {
$id = $customer['customer_id'];
$title = $customer['event_title'];
$pickup = $customer['pickup_time'];
$pickupLocation = $customer['pickup_instructions'];
$totalPassengers = $customer['num_passengers'];
// Print the data to the table
echo "
<td>$title</td>
<td>$pickup</td>
<td>$pickupLocation</td>
<td>$totalPassengers</td>
";
When i run it. I get a fatal error "function name must be a string" on $customers = $getCustomersTable();
Any ideas?
Greatly appreciate it!
$customers = $getCustomersTable();
^----
You're trying to use a variable function, with an undefined variable. Since the variable's undefined, it's basically acting as the equivalent of
$customers = null();

Building interactive WHERE clause for Postgresql queries from PHP

I'm using Postgresql 9.2 and PHP 5.5 on Linux. I have a database with "patient" records in it, and I'm displaying the records on a web page. That works fine, but now I need to add interactive filters so it will display only certain types of records depending on what filters the user engages, something like having 10 checkboxes from which I build an ad-hoc WHERE clause based off of that information and then rerun the query in realtime. I'm a bit unclear how to do that.
How would one approach this using PHP?
All you need to do is recieve all the data of your user's selected filters with $_POST or $_GET and then make a small function with a loop to concatenate everything the way your query needs it.
Something like this... IN THE CASE you have only ONE field in your DB to match with. It's a simple scenario and with more fields you'll need to make it so that you add the field you really need in each case, nothing too complex.
<?php
//recieve all the filters and save them in array
$keys[] = isset($_POST['filter1'])?'$_POST['filter1']':''; //this sends empty if the filter is not set.
$keys[] = isset($_POST['filter2'])?'$_POST['filter2']':'';
$keys[] = isset($_POST['filter3'])?'$_POST['filter3']':'';
//Go through the array and concatenate the string you need. Of course, you might need AND instead of OR, depending on what your needs are.
foreach ($keys as $id => $value) {
if($id > 0){
$filters.=" OR ";
}
$filters.=" your_field = '".$value."' ";
}
//at this point $filters has a string with all your
//Then make the connection and send the query. Notice how the select concatenates the $filters variable
$host = "localhost";
$user = "user";
$pass = "pass";
$db = "database";
$con = pg_connect("host=$host dbname=$db user=$user password=$pass")
or die ("Could not connect to server\n");
$query = "SELECT * FROM table WHERE ".$filters;
$rs = pg_query($con, $query) or die("Cannot execute query: $query\n");
while ($row = pg_fetch_row($rs)) {
echo "$row[0] $row[1] $row[2]\n";
//or whatever way you want to print it...
}
pg_close($con);
?>
The above code will get variables from a form that sent 3 variables (assuming all of them correspond to the SAME field in your DB, and makes a string to use as your WHERE clause.
If you have more than one field of your db to filter through, all you need to do is be careful on how you match the user input with your fields.
NOTE: I did not add it here for practical reasons... but please, please sanitize user input.. ALWAYS sanitize user input before using user controlled data in your queries.
Good luck.
Don't do string concatenation. Once you have the values just pass them to the constant query string:
$query = "
select a, b
from patient
where
($x is not null and x = $x)
or
('$y' != '' and y = '$y')
";
If the value was not informed by the user pass it as null or empty. In the above query the x = $x condition will be ignored if $x is null and the y = '$y' condition will be ignored if $y is empty.
With that said, a check box will always be either true or false. What is the exact problem you are facing?
Always sanitize the user input or use a driver to do it for you!
I have created a Where clause builder exactly for that purpose. It comes with the Pomm project but you can use it stand alone.
<?php
$where = Pomm\Query\Where::create("birthdate > ?", array($date->format('Y-m-d')))
->andWhere('gender = ?', array('M'));
$where2 = Pomm\Query\Where::createWhereIn('something_id', array(1, 15, 43, 104))
->orWhere($where);
$sql = sprintf("SELECT * FROM my_table WHERE %s", $where2);
$statement = $pdo->prepare($sql);
$statement->bind($where2->getValues());
$results = $statement->execute();
This way, your values are escaped and you can build dynamically your where clause. You will find more information in Pomm's documentation.

Mysql sum not working

i am trying to add up some records from a table, however, it isn't working properly, i.e. when i try var_dump to see what the value is showing i just get string(0) ""
Here is the code
$current_wealth1 = mysql_query("SELECT SUM(estimated_wealth) as total_house_wealth FROM user_houses WHERE user_id='$user_id'");
var_dump($total_house_wealth);
$current_wealth = $ved_balance + $total_house_wealth;
In terms of output, i am just using conventional php print to output $current_wealth.
Any ideas, what could be the problem?
EDIT: Here is my current code, getting a syntax error on the second line
$current_wealth1 = mysql_query("SELECT SUM(estimated_wealth) as total_house_wealth FROM user_houses WHERE user_id='$user_id'");
$total_house_wealth = mysql_fetch_array($current_wealth1)[0];
$current_wealth = $ved_balance + $total_house_wealth;
You need of course to do
var_dump(mysql_fetch_array($current_wealth1));
Also most likely you get a syntax error becuase you don't have php 5.4. You can't do ...)[0];
try splitting the fetch array to 2 lines to remove your syntax error?
$current_wealth1 = mysql_query("SELECT SUM(estimated_wealth) as total_house_wealth FROM user_houses WHERE user_id='$user_id'");
$total_house_wealth = mysql_fetch_array($current_wealth1);
$total_house_wealth = $total_house_wealth[0];
$current_wealth = $ved_balance + $total_house_wealth;
also, in your table structure, is user id a character string, or integer? if its an integer, then the userid='$user_id' in the WHERE clause shouldn't be single quoted (e.g. userid=$user_id *although you may want to sanitize the user_id var first*)
$total_house_wealth isn't declare nor set with any value, so what you are seeing is expected behaviour. What you actually want is a different thing
$total_house_wealth = mysql_fetch_array($current_wealth1)[0];

mysql_query arguments in PHP

I'm currently building my first database in MySQL with an interface written in PHP and am using the 'learn-by-doing' approach. The figure below illustrates my database. Table names are at the top, and the attribute names are as they appear in the real database. I am attempting to query the values of each of these attributes using the code seen below the table. I think there is something wrong with my mysql_query() function since I am able to observe the expected behaviour when my form is successfully submitted, but no search results are returned. Can anyone see where I'm going wrong here?
<form name = "search" action = "<?=$PHP_SELF?>" method = "get">
Search for <input type = "text" name = "find" /> in
<select name = "field">
<option value = "Title">Title</option>
<option value = "Description">Description</option>
<option value = "City">Location</option>
<option value = "Company_name">Employer</option>
</select>
<input type = "submit" name = "search" value = "Search" />
</form>
$query = "SELECT Title, Descrition, Company_name, City, Date_posted, Application_deadline
FROM job, employer, address
WHERE Title = $find
OR Company_name = $find
OR Date_posted = $find
OR Application_deadline = $find
AND job.employer_id_job = employer.employer_id
AND job.address_id_job = address.address_id";
There seems to be at least four problems:
You don't have quotes around $find, i.e. WHERE Title = '$find'.
You don't seem to be using mysql_real_escape_string (or did you just omit that code in your question for brevity?)
You spelled Description incorrectly.
AND has higher precedence than OR so you probably want parentheses in your expression:
WHERE (Title = '$find'
OR Company_name = '$find'
OR Date_posted = '$find'
OR Application_deadline = '$find')
AND job.employer_id_job = employer.employer_id
AND job.address_id_job = address.address_id"
I suspect that one or more of these are the reason why it's not working. However to be sure you should post more of your code and your table structure.
Another point is that you are using the old ANSI-89 join syntax. I would recommend using the newer syntax added in SQL-92 (FROM a JOIN b ON ...). This would have prevented you from making the fourth error, as well as having numerous other advantages over the older syntax.
Also try using mysql_error to find out what the exact error message is. And please include the message in your question.
If you like to learn by doing then learn by doing it in PDO and bind the parameters. This is the safe and correct way to do it these days.
Use single quotes for values in where clause.
Try this one:
$fields= array('Title','Company_name', 'Date_posted','Application_deadline');
if(!in_array($_GET['field'],$fields)) die(); // do some error handling here
$query = "SELECT Title, Descrition, Company_name, City, Date_posted, Application_deadline
FROM job, employer, address
WHERE
$field = '".mysql_real_escape_string($_GET['find']) ."'
AND job.employer_id_job = employer.employer_id
AND job.address_id_job = address.address_id";
If single quotes isn't your only problem (it is certainly part of it), check the return of mysql_error().
Check the code samples here:
http://www.php.net/manual/en/function.mysql-query.php
I would suggest also using ezSQL to do all your query handling, it's easy to drop into your code and makes all the processing easy, just include the db info in a config file, include the classes for ezSQL in the config file, setup a global call to the class like
$db = new ez_SQL();
then in your referencin php files, just do this
global $db;
$results = $db->query("SELECT statment", ARRAY_A);
you can get ezsql from: http://justinvincent.com/ezsql

Categories