Using MYsql 5.6 Memcache - php

I must be missing something really obvious here I think, but what I am trying to do is use MySQL 5.6 and return values through memcache
So I have set up MYSQL to use the memcache plugin, set up the details in the innodb_memcache.containers table
I now have two items in that table, the default ones entered by MySQL and my own settings, both of them have table names.
To get the data via php I use:
$memcache->get($key);
Where $key is the data in the db column
However this returns nothing, I suspect the reason is that, according to the MySQL Docs if no table name is specified, it choose the first one in the list, which is not the one I want, what I don't understand is how I specify the correct table name in the key, so it knows which table to look for the key in.
Additional Information:
table design:
table: codes
id INT PK
code VARCHAR UNIQUE
codeval VARCHAR
innodb_memcache.containers :
name: mycode
db_schema: databaseName
db_table: codes
key_columns: code
value_columns: codeval
flags: id
cas_column: null
expire_time_column: null
unique_idx_name_on_key: code
Code:
$table = "mycode";
$key = "123456";
$memcache = new Memcache;
$memcache->connect($this->CONNECTURL, $this->CONNECTPORT) or die ("Could not connect");
$version = $memcache->getVersion();
echo "Server's version: ".$version."<br/>\n";
$key = "##" . $table . "." . $key . "." . $table;
$get_result = $memcache->get($key);
print_r($get_result);
The above code returns the server version without issue, so the connection is working.
print_r($get_result) returns blank, when it should be returning a value
It does throw a notice: Trying to get property of non-object
So if someone could let me know how I specify with the $key which table I am using to query through memcache, I would be much appreciated!

The table name (table_id in ##table_id) must be the value from your mappings (innodb_memcache.containers), not the actual table name, if that varies.
And if you table name in mappings is mycode, then the resulting query through memcache should look like this:
$table = 'mycode';
$key = '123456';
$memcache->get( '##' . $table . '.' . $key );
There is no extra '.' . $table at the end.
Some details are available from InnoDB memcached Plugin documentation page.
To name a few of importance here:
Use select * from innodb_memcache.containers; to get defined mappings;
Note the queries organization:
For example, ##t1.some_key and ##t2.some_key have the same key value,
but are stored in different tables and so do not conflict.

From: http://dev.mysql.com/doc/refman/5.6/en/innodb-memcached-intro.html
Namespaces: memcached is like a single giant directory, where to keep files from conflicting with each other you might give them elaborate names with prefixes and suffixes. The integrated InnoDB / memcached server lets you use these same naming conventions for keys, with one addition. Key names of the format ##table_id.key.table_id are decoded to reference a specific a table, using mapping data from the innodb_memcache.containers table. The key is looked up in or written to the specified table.
The ## notation only works for individual calls to the get, add, and set functions, not the others such as incr or delete. To designate the default table for all subsequent memcached operations within a session, perform a get request using the ## notation and a table ID, but without the key portion. For example:
get ##table_x
Subsequent get, set, incr, delete and other operations use the table designated by table_x in the innodb_memcache.containers.name column.

If you still have the default tables, you can try using telnet.
Note: This was used on an AWS RDS instance with memcached, it should be the same for any MySQL implementation using memcached, but I'm not sure.
telnet localhost 11211
stats
#=> should return a long list of stats including pid, uptime, etc
get AA
#=> should return
VALUE AA 8 12
HELLO, HELLO
END
quit #exit telnet session
I know this doesn't answer your question, but it might help in troubleshooting.

<?php
$memc = new Memcache;
$memc->addServer('localhost','11211');
if(empty($_POST['film'])) {
?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Simple Memcache Lookup</title>
</head>
<body>
<form method="post">
<p><b>Film</b>: <input type="text" size="20" name="film"></p>
<input type="submit">
</form>
<hr/>
<?php
} else {
echo "Loading data...\n";
$film = htmlspecialchars($_POST['film'], ENT_QUOTES, 'UTF-8');
$mfilms = $memc->get($film);
if ($mfilms) {
printf("<p>Film data for %s loaded from memcache</p>", $mfilms['title']);
foreach (array_keys($mfilms) as $key) {
printf("<p><b>%s</b>: %s</p>", $key, $mfilms[$key]);
}
} else {
$mysqli = mysqli('localhost','sakila','password','sakila');
if (mysqli_connect_error()) {
sprintf("Database error: (%d) %s", mysqli_connect_errno(), mysqli_connect_error());
exit;
}
$sql = sprintf('SELECT * FROM film WHERE title="%s"', $mysqli->real_escape_string($film));
$result = $mysqli->query($sql);
if (!$result) {
sprintf("Database error: (%d) %s", $mysqli->errno, $mysqli->error);
exit;
}
$row = $result->fetch_assoc();
$memc->set($row['title'], $row);
printf("<p>Loaded (%s) from MySQL</p>", htmlspecialchars($row['title'], ENT_QUOTES, 'UTF-8');
}
}
?>
</body>
</html>
With PHP, the connections to the memcached instances are kept open as long as the PHP and associated Apache instance remain running. When adding or removing servers from the list in a running instance (for example, when starting another script that mentions additional servers), the connections are shared, but the script only selects among the instances explicitly configured within the script.

Related

Why search query not showing any result in PHRETS?

I am using this php script to get the result from a simple search query documented here
And I have downloaded this excel file of metadata of property here
$rets_login_url = "http://sef.rets.interealty.com/Login.asmx/Login";
$rets_username = "xxxxxxxx";
$rets_password = "xxxxxxxx";
$rets_user_agent = "PHRETS/1.0";
$rets_user_agent_password = "xxxxxxx";
//////////////////////////////
// start rets connection
$rets = new phRETS;
// Uncomment and change the following if you're connecting
// to a server that supports a version other than RETS 1.5
$rets->AddHeader("RETS-Version", "RETS/1.5");
$rets->AddHeader("User-Agent", $rets_user_agent);
echo "+ Connecting to {$rets_login_url} as {$rets_username}<br>\n";
$connect = $rets->Connect($rets_login_url, $rets_username, $rets_password, $rets_user_agent_password);
// check for errors
if ($connect) {
echo " + Connected<br>\n";
}
else {
echo " + Not connected:<br>\n";
print_r($rets->Error());
exit;
}
$search = $rets->SearchQuery("Property","ResidentialProperty","(ListDate=1990-01-01+)");
while ($listing = $rets->FetchRow($search)) {
echo "Address: {$listing['StreetNumber']} {$listing['StreetName']}, ";
echo "{$listing['City']}, ";
echo "{$listing['State']} {$listing['ZipCode']} listed for ";
echo "\$".number_format($listing['ListPrice'])."\n";
}
$rets->FreeResult($search);
echo "+ Disconnecting<br>\n";
$rets->Disconnect();
when I run this script it shows the result connected and then disconnected. But no result is found. I tried many things suggested on some questions for which result was not showing, But nothing is working for me. Where I am wrong?
My RETS server information are here:
RETS Server: SEF RETS System
RETS System ID: SEFRETS
Login URL: http://sef.rets.interealty.com:80/Login.asmx/Login
RETS Version: 1.5
Server Software: Microsoft-IIS/6.0
I also could not understand what is $rets_modtimestamp_field = "LIST_87";
Please Help me. I need some suggestion over how to get data from the RETS.
The issue is with the parameters in your SearchQuery.
One of the fields in your search query is ListDate. Looking at the attached excel file containing the metadata, "ListDate" is in Column B under StandardNames. The RETS specification uses System Names as default (see below). You need to specify '"StandardNames" => 1' in the options parameter in the SearchQuery function:
$search = $rets->SearchQuery("Property","ResidentialProperty","(ListDate=1990-01-01+)",array("StandardNames" => 1));
Also, check to make sure the second argument, class, of your SearchQuery is correct. To do this you could use the GetMetadataClasses function in PHRETS.
You could also use retsmd.com by logging in with your RETS Server url, username, and password.
The $rets_modtimestamp_field is the field which is a datetime value indicating the date and time when a listing was last modified.
In section 7.4.7 in the RETS 1.7.2 Specification document, http://www.reso.org/assets/RETS/Specifications/rets_1_7_2.pdf,
"Queries may use either standard names or system names in the query (Section 7.7). If the
client chooses to use standard names, it MUST indicate this using the StandardNames
argument...If this entry is set to ("0") or is not present the field names passed in the search are the
SystemNames, as defined in the metadata."
To address your last comment, you need to specify ListingStatus as well, as it is also a required field when running a query. The lookup values for ListingStatus are:
A = Active-Available
B = Backup Contract-Call LA
C = Cancelled
CS = Closed Sale
PS = Pending Sale/Rental
Q = Terminated
T = Temp Off Market
W = Withdrawn
X = Expired
So try something like this instead:
$query ="(922=MIAMI),(246=A)";
Or if you're using standard names:
$query ="(City=MIAMI),(ListingStatus=A)";
And finally:
$search = $rets->SearchQuery("Property", $class, $query, array("StandardNames" => 1, 'Limit' => 10, ));
This should allow you to get some results back at least. Beyond that you can just tweak your query until you get the results you want.

php5 using SimpleXML from XML file INSERT INTO ON DUPLICATE KEYS UPDATE mysql

I'm trying to figure out how to build my script and need some help.
I'm using PHP 5 and MySQL 5.1.67
My goal is to be able to extract certain fields from the DB, reformat them in PHP and display them as a list. The reformatting will include HTML sequences. My goal is to have an automated CRON script from this which will automatically update the webpages.
I have very little experience with these languages. So any help would be good.
My logic is that I should load everything into one (mysql) table. My XML uses latin1 character set. Category, id, title, and description are each columns in the table.
Here is the mysql structure:
category mysql uses VARCHAR Latin1
site just used to group below
id mysql uses VARCHAR Latin1
title mysql uses VARCHAR Latin1
description mysql uses VARCHAR Latin1
The XML structure is as follows:
// XML Structure
// 23 categories to loop through
// hunderds of sites to loop through per category
//
<catalog>
<category>
<name>Category_Name</name>
<site>
<id>UR545665U</id>
<pagerank>1</pagerank>
<title>Title_Name</title>
<description>Description_of_the_site</description>
</site>
</category>
</catalog>
//
//
I've gotten to the point of loading my XML and DB using the below code.
//mysql connection
$con2 = mysql_connect("www.hosting.com","db_username","db_password");
if (!$con2) {
die('Could not connect: ' . mysql_error());
}
$dbcon1 = mysql_select_db("database_name", $con2);
if (!$dbcon1) {
die ('Can\'t use database_name : ' . mysql_error());
}
//simplexml load xml file with simplexml
$library= simplexml_load_file('feed.xml');
if ($xml === false) {
echo "Failed loading XML\n";
foreach(libxml_get_errors() as $error) {
echo "\t", $error->message;
}
}
Then here is where I'm having trouble... I need to loop through categories and within them loop through sites. The trouble I'm having is that I can't use the getName() function since <category> and <site> are not named witin the xml. So I'm using <name> to identify the category since it is unique, and <id> to identify the site and also unique.
So my logic here is to have a foreach() function within itself. Looping through categories and looping through each site within its category.
//begin loop each category and each site
foreach($library->xpath('/Catalog/Category/Name') as $category) {
foreach($library->xpath('/Catalog/Category/Name/Site/Id') as $id) {
$site = $library->xpath('//Site');
$title = $site->Title;
$description = $site->Description;
From this point, is the proper formatting of the sql process with mysql 5 proper escape sequences to avoid hacking.
The way I'm thinking of doing this is as follows:
// Format Query String into a variable
// Note: VALUES are in "" because they may contain strings
// sprintf() will run on each loop to format the new <site> string
$mynewquery = sprintf('REPLACE INTO Table_Name (id, title, description, category) VALUES (\"%4$s\",\"%6$s\",\"%7$s\",\"%3$s\")');
if ($mynewquery === false) {
echo "Failed formatting query string\n";
foreach(libxml_get_errors() as $error) {
echo "\t", $error->message;
}
}
//Run Query String to load data into DB
mysql_query($mynewquery);
if (!$mynewquery) {
die ('Error running Query: ' . mysql_error());
}
//
// close the loops and database connection after this.
I've used echo statements (not shown) to get feedback on the process. It goes all the way through loading the XML without error. My guess is that I have a syntax problem in the looping process. So I have a few questions:
Is my logic correct?
if the XML has a DTD referenced within it, is there any special coding I need to place in my script?
Am I using proper variables and functions to accomplish my intent?
Any suggestions on how to make this work? I've tried it, but DB doesn't load the data.
You're looping through the xml elements, but not referring to the loop variables at all. You need something more like this:
foreach($library->Category as $category) {
foreach($category->Site as $site) {
$id = $site->Id;
$title = $site->Title;
$description = $site->Description;
//- insert into db here
}
}

Migrating databases using phpMyAdmin's tracking mechanism

In a development database, I have phpMyAdmin Tracking enabled on all tables. It logs all the changes I make to the tables' structures (in this case I'm not interested in data tracking.) So far so good.
What I want to do then is to take out a report, for ALL tracked tables, with the changes made from a specific version (or a date would even work,) so that I can run the resulting SQL on my production database, when upgrading to new versions, and make sure that the databases are identical, without the worry of the errors that come with manual handling of this.
However, there is no function that I can find that generates such a report. All the tracking reports are for individual tables, and if I have to click through all tables (20+) it takes away the benefit of this function. All tables don't change, but I don't want to keep track of what's changed, that's what I want phpMyAdmin to do for me.
I have tried to make my own query against the pma_tracking table where the changes are stored, and had partial success. The problem is that all changes for one version are stored as one BLOB, and with each new version a DROP TABLE / CREATE TABLE statement is made, and I can't drop tables on the production db since there is data there (I'm not recreating the database every time, only adding incremental changes). I just want to upgrade the structure, and the only time I want CREATE TABLE statements is when I actually create a new table in the database. So I thought I could filter those out with SQL, but then it's stored as a blog, and then I would have to parse and mess with the blob text which seems overly complicated.
So, as a summary, this is what I'm looking for:
An automated tracking system/workflow that logs all structure updates, and can create incremental SQL reports for the whole database from a version or point in time.
I'd prefer to not use any additional third party apps (I'd like to use phpMyAdmin or MySQL only), if possible
Also, I would love comments on the workflow, if someone has ideas of a better one. Any help appreciated.
The algorithm for parsing the BLOB field of the "pma_tracking" table is located in the getTrackedData method of the PMA_Tracker class, in the libraries/Tracker.class.php source file.
Starting from that code, I've written a simple PHP script to extract all the data definition statements (except the "DROP TABLE" statements) from the "pma_tracking" table.
For example, suppose that you want to get the list of all the changes of all the tables of the "test" database since version "1":
<?php
$link = mysqli_init();
// Adjust hostname, username, password and db name before use!
$db = mysqli_real_connect($link, "localhost", "myuser", "mypass", "phpmyadmin")
or die(mysqli_connect_error());
// Adjust also target db name and tracking version
$db_name = "test";
$version = "1";
$sql = "SELECT schema_sql FROM pma_tracking
WHERE db_name='{$db_name}' AND version>='{$version}'
ORDER BY version,date_created";
$result = mysqli_query($link, $sql) or die(mysqli_error($link));
while ($myrow = mysqli_fetch_assoc($result)) {
$log_schema_entries = explode('# log ', $myrow['schema_sql']);
foreach ($log_schema_entries as $log_entry) {
if (trim($log_entry) != '') {
$statement = trim(strstr($log_entry, "\n"));
if (substr($statement, 0, 11) != "DROP TABLE ") {
echo "{$statement}\n";
}
}
}
}
?>
By redirecting the script output on a file, you'll obtain a SQL commands file with (almost) all the statements needed to replicate the schema changes on the target (eg. production) database; this file must be executed by specifying the "-f" (force) MySQL option:
-f, --force Continue even if we get an SQL error.
By doing so, MySQL will ignore all the "Table already exists" error that will be thrown each time that a CREATE TABLE statement for an existing table is encountered, thus creating only the tables that still does'nt exist in the target database.
This kind of approach obviously has some drawbacks:
ALL the DROP TABLE commands will be ignored (not only those automatically inserted from phpMyAdmin) so, if you have deleted a table in the source database, that table won't be deleted in the target database.
ALL the script errors will be ignored, so it may not be 100% affordable.
A final word of advice: always do a full backup of your target database before proceeding!
I don't know how you could solve this problem using phpMyAdmin, but there are other tools that might help you achieve the effect your looking for. Liquibase is one of them. I've used it some times in the past and it was pretty good. It takes a little to get the hang of it, but I think it might help you.
I'm not too familiar with SQL tools, so I cannot recommend anything to help you out there, but I can try and help with a custom workflow...
Create a table called structure_log
Create a PHP script called print_stucture.php that prints whatever info you desire to a file on the server, saves the file as a timestamp (this will be your version number), and saves the name in the structure_log table
Create a crontab that runs print_structure.php however often you desire
Create a PHP script called delete_dups.php that grabs the last two records from your structure_log table, compares those two files, and if they are the same (representing no change to structures), deletes the one with the latest timestamp (filename) and removes that record from the structure_log table
Create a crontab that runs delete_dups.php half as often as the one that runs print_structure.php
This will make a versioning folder on your server. You can manually run the print_structure.php script whenever you desire and compare it against the latest version log you have in your server folder to see if your database you just ran it on, is the same as the last time the version check was ran.
I've had some success with MySQL Workbench:
Import (reverse engineer) your dev database into workbench. You can do this by either exporting your schema to an SQL file and loading it into workbench, or workbench will get the schema directly from the server.
Next, generate your diff file with the "Synchronise model" option. You select the production database, then which tables to sync, and workbench generates an SQL file you can run to sync both models.
A word of caution: the first time, there will likely be quite a few apparently uneeded changes while the DB is updated to workbench "style". For subsequent updates, the tool is rather reliable, though I would never let an automated tool have free range over my production DB ;-)
Always check the SQL file for errors, in some cases, dropping a column then adding another of the same name but different type will generate an alter column which will fail.
I don't have anything that creates an incremental diff between two databases but here's the script I use to compare two MySQL databases:
<?php
//------------------------------------------------------------------------------
// Define the variables we'll be using.
//------------------------------------------------------------------------------
$db1_con = NULL;
$db1_constraints = array();
$db1_dbname = 'db1';
$db1_host = 'localhost';
$db1_password = 'password1';
$db1_tables = array();
$db1_username = 'username1';
$db2_con = NULL;
$db2_constraints = array();
$db2_dbname = 'db2';
$db2_host = '123.123.123.123';
$db2_password = 'password2';
$db2_tables = array();
$db2_username = 'username2';
//------------------------------------------------------------------------------
// Connect to the databases.
//------------------------------------------------------------------------------
try{
$db1_con = new PDO("mysql:host=$db1_host;dbname=information_schema", $db1_username, $db1_password);
$db1_con->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE); // Try to use the driver's native prepared statements.
$db1_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Let's use exceptions so we can try/catch errors.
}catch(PDOException $e){
echo "<p>Connection failed for $db1_host: " . $e->getMessage() . '</p>';
exit;
}
try{
$db2_con = new PDO("mysql:host=$db2_host;dbname=information_schema", $db2_username, $db2_password);
$db2_con->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE); // Try to use the driver's native prepared statements.
$db2_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Let's use exceptions so we can try/catch errors.
}catch(PDOException $e){
echo "<p>Connection failed for $db2_host: " . $e->getMessage() . '</p>';
exit;
}
if (NULL !== $db1_con && NULL !== $db2_con){
echo "<h2>Column Analysis</h2>";
$sql = 'SELECT * FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = ? ORDER BY TABLE_NAME, ORDINAL_POSITION';
$statement1 = $db1_con->prepare($sql);
$statement1->bindValue(1, $db1_dbname);
$statement2 = $db2_con->prepare($sql);
$statement2->bindValue(1, $db2_dbname);
if (TRUE === $statement1->execute()){
while ($row = $statement1->fetch(PDO::FETCH_ASSOC)){
$db1_tables[$row['TABLE_NAME']][$row['COLUMN_NAME']] = array();
foreach ($row AS $key => $value){
$db1_tables[$row['TABLE_NAME']][$row['COLUMN_NAME']][$key] = $value;
}
}
}
if (TRUE === $statement2->execute()){
while ($row = $statement2->fetch(PDO::FETCH_ASSOC)){
$db2_tables[$row['TABLE_NAME']][$row['COLUMN_NAME']] = array();
foreach ($row AS $key => $value){
$db2_tables[$row['TABLE_NAME']][$row['COLUMN_NAME']][$key] = $value;
}
}
}
foreach ($db1_tables AS $table => $info){
if (!isset($db2_tables[$table])){
echo "<p>Table <strong>$table</strong> does not exist in the SECOND database!</p>";
}else{
foreach ($info AS $column => $data){
if (!isset($db2_tables[$table][$column])){
echo "<p>Column <strong>$column</strong> does not exist in table <strong>$table</strong> in the SECOND database!</p>";
}else{
if (count($data)){
foreach ($data AS $key => $value){
if ($db1_tables[$table][$column][$key] !== $db2_tables[$table][$column][$key]){
echo "<p>Column <strong>$column</strong> in table <strong>$table</strong> has differing characteristics for <strong>$key</strong> (". $db1_tables[$table][$column][$key] ." vs. ". $db2_tables[$table][$column][$key] .")</p>";
}
}
}
}
}
}
}
foreach ($db2_tables AS $table => $info){
if (!isset($db1_tables[$table])){
echo "<p>Table <strong>$table</strong> does not exist in the FIRST database!</p>";
}else{
foreach ($info AS $column => $data){
if (!isset($db1_tables[$table][$column])){
echo "<p>Column <strong>$column</strong> does not exist in table <strong>$table</strong> in the FIRST database!</p>";
}else{
if (count($data)){
foreach ($data AS $key => $value){
if ($db2_tables[$table][$column][$key] !== $db1_tables[$table][$column][$key]){
echo "<p>Column <strong>$column</strong> in table <strong>$table</strong> has differing characteristics for <strong>$key</strong> (". $db2_tables[$table][$column][$key] ." vs. ". $db1_tables[$table][$column][$key] .")</p>";
}
}
}
}
}
}
}
echo "<h2>Constraint Analysis</h2>";
$sql = 'SELECT * FROM information_schema.KEY_COLUMN_USAGE WHERE TABLE_SCHEMA = ? ORDER BY TABLE_NAME, ORDINAL_POSITION';
$statement1 = $db1_con->prepare($sql);
$statement1->bindValue(1, $db1_dbname);
$statement2 = $db2_con->prepare($sql);
$statement2->bindValue(1, $db2_dbname);
if (TRUE === $statement1->execute()){
while ($row = $statement1->fetch(PDO::FETCH_ASSOC)){
foreach ($row AS $key => $value){
$db1_constraints[$row['TABLE_NAME']][$row['COLUMN_NAME']][$key] = $value;
}
}
}
if (TRUE === $statement2->execute()){
while ($row = $statement2->fetch(PDO::FETCH_ASSOC)){
foreach ($row AS $key => $value){
$db2_constraints[$row['TABLE_NAME']][$row['COLUMN_NAME']][$key] = $value;
}
}
}
foreach ($db1_constraints AS $table => $info){
foreach ($info AS $column => $data){
if (isset($db2_constraints[$table][$column])){
if (count($data)){
foreach ($data AS $key => $value){
if ('CONSTRAINT_NAME' !== $key && $db1_constraints[$table][$column][$key] !== $db2_constraints[$table][$column][$key]){
echo "<p>Column <strong>$column</strong> in table <strong>$table</strong> has differing characteristics for <strong>$key</strong> (". $db1_constraints[$table][$column][$key] ." vs. ". $db2_constraints[$table][$column][$key] .")</p>";
}
}
}
}else{
echo "<p>Column <strong>$column</strong> in table <strong>$table</strong> is missing a constraint in the SECOND database!</p>";
}
}
}
foreach ($db2_constraints AS $table => $info){
foreach ($info AS $column => $data){
if (isset($db1_constraints[$table][$column])){
if (count($data)){
foreach ($data AS $key => $value){
if ('CONSTRAINT_NAME' !== $key && $db2_constraints[$table][$column][$key] !== $db1_constraints[$table][$column][$key]){
echo "<p>Column <strong>$column</strong> in table <strong>$table</strong> has differing characteristics for <strong>$key</strong> (". $db2_constraints[$table][$column][$key] ." vs. ". $db1_constraints[$table][$column][$key] .")</p>";
}
}
}
}else{
echo "<p>Column <strong>$column</strong> in table <strong>$table</strong> is missing a constraint in the FIRST database!</p>";
}
}
}
}
?>
Edited to add code that shows differences in constraints as well.

problems with PHP and ADODB library and SQL server

I have a PHP function using ADODB library. My query is simple, select distinct SessID from 'table'.
When I iterate, I keep getting the following error:
Notice: Undefined index: SessID in C:\Program Files\xampp\htdocs\conference\AbstractSearchDAO.php on line 116
Here is the code:
public function searchAbstracts($name,$title){
/**,$dayArray,$sessionTypeArray, $abstractTypeArray,$groupBy*/
$sql_abstract_session_ids = "select distinct SessID from ABSTRACT where ";
if($name!=null && $title!=null){
$sql_abstract_session_ids .= "FALastName like "."'%".$name."%' or AbstractTitle like "."'%".$title."%'";
}elseif($name!=null && $title==null){
$sql_abstract_session_ids .= "FALastName like "."'%".$name."%'";
}elseif($name==null && $title!=null){
$sql_abstract_session_ids .= "AbstractTitle like "."'%".$title."%'";
}elseif($name==null && $title==null){
$sql_abstract_session_ids = "select distinct SessID from ABSTRACT";
}
$connect = new ATSDataSourceLocator();
$conn = $connect->connectConference2011();
echo $sql_abstract_session_ids;
//////////////////////////////////////////////////////////
//let's get the session ids from the abstract table.
//we can then match them with another search on the session table (where SessID in (...abstract_session_ids....)
$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
$rs = $conn->Execute($sql_abstract_session_ids);
if($rs==false) die('failed');
$sql_session_data = "select * from SESSION where SessID in (";
$count = $rs->RecordCount();
$myCount = 0;
while(!$rs->EOF){
$sql_session_data.="'".$rs->fields['SessID']."'";
if($myCount<($count-1)){
$sql_session_data.=",";
}
$myCount++;
$rs->MoveNext();
}
$sql_session_data.=")";
//$conn->Close();
echo $sql_session_data;
}
Whenever I try to Iterate and get the field 'SessID' It fails.
Any ideas?
Check out how ADODB_ASSOC_CASE is defined and compare that value to the ADODB manual. If you're not setting it explicitly, it should be defaulted to 2, which means your capitalization in your script has to match exactly the capitalization in the table. Also, note that this must be define'd before you include adodb.inc.php. And lastly, double- and triple-check that the field is definitely SessID in your ABSTRACT table.
Have you tried $rs->fields('SessID') in your iteration - i.e. replace the square brackets with round? Or, for example, keep the square brackets and use $rs->fields[0] (if it's the first field)?
With MySQL this isn't an issue, but it will throw an error if you use round instead of square with a field index, as opposed to name. I don't have a SQL Server DB handy to test against.
Something in the back of my mind says this behaviour may also vary depending upon your ADODB_FETCH setting. This, at least, does indeed appear to be driver-specific:
"If no fetch mode is predefined, the fetch mode defaults to ADODB_FETCH_DEFAULT. The behaviour of this default mode varies from driver to driver, so do not rely on ADODB_FETCH_DEFAULT. For portability, we recommend sticking to ADODB_FETCH_NUM or ADODB_FETCH_ASSOC. Many drivers do not support ADODB_FETCH_BOTH."

Extract all the data from a database

Hey, I am wondering how to extract the data from a table in a database onto a table in a page (users.php),
For example:
I want to be able to get all of the usernames and all the id's from my database onto a table.
So if I have in my database:
1 - Fred
2 - Frank
3 - Margret
It will see that I have them user's and id's in the database and print them onto a table.
Any help would be great,
Thanks.
Connect to your database. Host is the location, like localhost if its on your computer, or on the same server as your code. User and Password are self explanatory.
mysql_connect("host", "user", "pass");
The name of the database you want to access.
mysql_select_db("database");
The actual mysql query.
$result = mysql_query('SELECT `User_Name`, `User_ID` FROM TABLE');
Sort it into an array
while($temp = mysql_fetch_array($result)
{
$id = $temp['User_ID'];
$array[$id]['User_ID'] = $id;
$array[$id]['User_Name'] = $temp['User_Name'];
}
Turn the array into a table. (You could skip the last step and go right to this one.
$html ='<table><tr><td>User ID</td><td>User Name</td></tr>';
foreach($array as $id => $info)
{
$html .= '<tr><td>'.$info['User_ID'].'</td><td>'.$info['User_Name'].'</td></tr>';
}
echo $html . '</table>';
Or, the formatting you wanted
$html ='User Id - User Name';
foreach($array as $id => $info)
{
$html .= $info['User_ID'].' - '.$info['User_Name'].'<br>';
}
echo $html;
(For this answer, I will use the mysqli extension -- you could also want to use PDO ;; note that the mysql extension is old and should not be used for new applications)
You first have to connect to your database, using mysqli_connect (And you should test if the connection worked, with mysqli_connect_errno and/or mysqli_connect_error).
Then, you'll have to specifiy with which database you want to work, with mysqli_select_db.
Now, you can send an SQL query that will select all data from your users, with mysqli_query (And you can check for errors with mysqli_error and/or mysqli_errno).
That SQL query will most likely look like something like this :
select id, name
from your_user_table
order by name
And, now, you can fetch the data, using something like mysqli_fetch_assoc -- or some other function that works the same way, but can fetch data in some other form.
Once you have fetched your data, you can use them -- for instance, for display.
Read the pages of the manual I linked to : many of them include examples, that will allow you to learn more, especially about the way those functions should be used ;-)
For instance, there is a complete example on the page of mysqli_fetch_assoc, that does exactly what you want -- with countries insteand of users, but the idea is quite the same ^^
You can do something like the following (using the built-in PHP MySQL functions):
// assuming here you have already connected to the database
$query = "SELECT id,username FROM users";
$result = mysql_query($query, $db);
while ($row = mysql_fetch_array($result))
{
print $row["id"] . " - " . $row["username"] . "\n";
}
which will give you (for example):
1 - Fred
2 - Frank
3 - Margret
Where I've put the print statement, you can do whatever you feel like there eg put it into a table using standard HTML etc.

Categories