Troubleshooting mysql Query - mysql

I'm having trouble with querying this simple table with a passed in variable:
Here is the relevant code:
// MySQL connection saved to variable $db
// variable $item is passed in as the string "Camera1"
$accessQuery = "SELECT Available FROM inventory WHERE Item = '" . $item . "'";
// This outputs properly as "SELECT Available FROM inventory WHERE Item = 'Camera1'"
echo $accessQuery;
if($oldVal = mysqli_query($db, $accessQuery)){
echo $oldVal // Should be 5 - but there is no output
// echo 'Made it inside if statement' --- This line outputs correctly
}
else{
echo 'Error accessing MySQL query';
}

You need to call a mysqli_fetch_XXX function to get the resulting data from the query.
if($result = mysqli_query($db, $accessQuery)){
$row = mysqli_fetch_assoc($result);
$oldVal = $row['Available'];
echo $oldVal // Should be 5 - but $oldVal causes an error when I try to output
}
else{
echo 'Error accessing MySQL query: ' . mysqli_error($db);
}

$accessQuery = "SELECT Available FROM inventory WHERE Item = '" . $item . "'";
if($res = mysqli_query($db, $accessQuery)){
$row = mysqli_fetch_array($res);
$oldVal = $row['Available'];
echo $oldVal;
}
else{
echo 'Error accessing MySQL query';
}

Related

i have issue with my database mySQL select from table

Dears
Please help me in this matter.
I have issue with my MySQL database.
It is working fine if I'm doing inserting records to the table. However, if I'm doing selecting and fetching, the result is 0 despite of the table actually have records.
$sql2 = 'SELECT * FROM `users`';
$result2 = $conn->query($sql2);
echo $result2->num_rows;
if ($result2->num_rows > 0) {
// output data of each row
while($row = $result2->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
please help me guys I tried every thing I almost give up.
thanks,
Maybe you can try this code
<?php
try {
$conn = new PDO('mysql:host=localhost;dbname=contoh', "root", "root");
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql2 = 'SELECT * FROM `user_ranks`';
$result2 = $conn->query($sql2);
while($row = $result2->fetch()) {
$id = $row['id'];
$username = $row['username'];
$password = $row['password'];
$rank = $row['rank'];
}
}
catch (PDOException $e) {
print "connection or query have a problem: " . $e->getMessage() . "<br/>";
die();
}

Display ratio as decimal between two PHP variables

I log stats for my Minecraft server and display player's in-game stats on my site. I log kills and deaths already, but now I'm trying to get a functioning kill/death ratio.
I am trying to display the kills/deaths in a decimal ratio format (Example: 3789 kills - 5711 deaths would give you a K/DR of 0.663)
elseif ($_GET['task'] == 'stats') {
$get_player = $_GET['player'];
$get_db = 'engine';
$result = mysql_query("SELECT * FROM $get_db WHERE name = '" . mysql_real_escape_string($get_player) . "'", $link);
while($data = mysql_fetch_array($result)) {
echo '{"task":"viewstats","kills":"'; echo $data['kills'];
echo '","deaths":"'; echo $data['deaths'];
echo '","joins":"'; echo $data['joins'];
echo '","quits":"'; echo $data['quits'];
echo '","kicked":"'; echo $data['kicked'];
echo '"}';
}
}
I call upon them in a table like this:
<td><?php echo empty($stats) ? "--" : substr($stats->kills, 0, 50); ?></td>
<td><?php echo empty($stats) ? "--" : substr($stats->deaths, 0, 50); ?></td>
The above PHP code is an API file and the MySQL is already enabled in it - I only posted a snippet of the API though.
You can do this:
echo json_encode(array(
'task' => 'viewstats',
'kills' => $data['kills'],
'deaths' => $data['deaths'],
'joins'=> $data['joins'],
'quits' => $data['quits'],
'kicked' => $data['kicked'],
// then ratio
'ratio' => $data['kills'] / $data['deaths'],
));
//**Make sure this Function is declared at the top of your script.**
function MySQLi_quickConnect()
{
$host = 'somewebsite.db.120327161.hostedresource.com'; //or 'http://localhost'
$username = '<YOUR USERNAME>';
$password = '<YOUR PASSWORD>';
$database = '<YOUR DATABASES NAME>';
$db = new MySQLi($host,$username,$password,$database);
$error_message = $db->connect_error;
if($error_message != NULL){die("Error:" . $error_message . "<br>" . "Occured in function
MySQLi_quickConnect");}
return $db;
}
//Replace your code with this:
elseif($_GET['task'] == 'stats') {
$get_player = $_GET['player'];
$get_db = 'engine';
$mysqli = MySQLi_quickConnect();
$query = ('SELECT kills, deaths, FROM ? WHERE name = ? ');
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param("ss", $get_db, $get_player);
$stmt->execute();
$stmt->bind_result($kills, $deaths);
}
while ($stmt->fetch()) {
$kdr = $kills/$deaths;
echo "You have a K/DR of " . $kdr . "<br>";
}
$stmt->close();
}
Note: Verify your Database connection, table names, and $_Get variables.

Changing from Google maps api v2 to v3

I've been using Google geocoding v3 for about 6 months but all of a sudden it's stopped working (I get a 610 error). It's only stopped in the last week or so.
Then I came across this (see the pink box at the top of the page!): https://developers.google.com/maps/documentation/geocoding/v2/
I've read through all the documentation and not sure where to start!
I'm hoping it's a small change as it's taken a long time to get this far, can anyone help?
[See the full site here][1]
UPDATE:
require("database.php");
// Opens a connection to a MySQL server
$con = mysql_connect("localhost", $username, $password);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("teamwork_poh", $con);
$company = get_the_title();
$address = get_field('address_line_1');
$city = get_field('town_/_city');
$post_code = get_field('post_code');
$link = get_permalink();
$type = get_field('kind_of_organisation');
$sql = sprintf("select count('x') as cnt from markers where `name` = '%s'", mysql_real_escape_string($company));
$row_dup = mysql_fetch_assoc(mysql_query($sql,$con));
if ($row_dup['cnt'] == 0) {
mysql_query("INSERT INTO markers (`name`, `address`, `lat`, `lng`, `type`, `link`) VALUES ('".$company."', '".$address.", ".$city.", ".$post_code."', '0.0', '0.0', '".$type."', '".$link."')");
}
wp_reset_query();
require("database.php");
define("MAPS_HOST", "maps.googleapis.com");
define("KEY", "(my key)");
// Opens a connection to a MySQL server
$connection = mysql_connect("localhost", $username, $password);
if (!$connection) {
die("Not connected : " . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die("Can\'t use db : " . mysql_error());
}
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
if (!$result) {
die("Invalid query: " . mysql_error());
}
//Initialize delay in geocode speed
$delay=0;
$base_url = "http://" . MAPS_HOST . "/maps/api/geocode/json?address=";
while ($row = #mysql_fetch_assoc($result)) {
if (!($row['lat'] * 1)) {
$geocode_pending = true;
while ($geocode_pending){
$address = $row["address"];
$id = $row["id"];
$request_url = $base_url . "" . urlencode($address) ."&sensor=false";
sleep(0.1);
$json = file_get_contents($request_url);
$json_decoded = json_decode($json);
$status = $json_decoded->status;
if (strcmp($json_decoded->status, "OK") == 0) {
$geocode_pending = false;
$lat = $json_decoded->results[0]->geometry->location->lat;
$lng = $json_decoded->results[0]->geometry->location->lng;
// echo 'here';
$query = sprintf("UPDATE markers " .
" SET lat = '%s', lng = '%s' " .
" WHERE id = '%s' LIMIT 1;",
mysql_real_escape_string($lat),
mysql_real_escape_string($lng),
mysql_real_escape_string($id));
$update_result = mysql_query($query);
echo $id;
if (!$update_result) {
die("Invalid query: " . mysql_error());
}
}
else {
// failure to geocode
$geocode_pending = false;
echo "Address " . $address . " failed to geocode. ";
echo "Received status " . $status . "\n";
}
// usleep($delay);
}
}
}
As you are storing the coordinates in database it would be best to geocode when you insert new record.
ie
require("dbinfo.php");//Your database parameters
//Connect to database
$dbh = new PDO("mysql:host=$host;dbname=$database", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
//Prepare query
$name = "%".$company."%";//Wildcard for PDO paramerter
$countSql = "SELECT COUNT(*) FROM markers WHERE `name` LIKE ?";
$countStmt = $dbh->prepare($countSql);
// Assign parameter
$countStmt->bindParam(1,$name);
//Execute query
$countStmt->execute();
// check the row count
if ($countStmt->fetchColumn() == 0) { #1 EDIT changed >0 to ==0
echo "No row matched the query."; //EDIT From Row
$q =$address.','.$city.','.$post_code.',UK';
echo "\n";
$base_url = "http://maps.googleapis.com/maps/api/geocode/xml?address=";
$request_url = $base_url.urlencode($q)."&sensor=false";
$xml = simplexml_load_file($request_url) or die("url not loading");
if($xml->status=="OK"){#2
// Successful geocode
$lat = $xml->result->geometry->location->lat;
$lng = $xml->result->geometry->location->lng;
$insertSql ="INSERT INTO markers (`name`, `address`, `lat`, `lng`, `type`, `link`) VALUES (?,?,?,?,?,?)";
$insertStmt = $dbh->prepare($insertSql);
// Assign parameter
$insertStmt->bindParam(1,$company);
$insertStmt->bindParam(2,$address);
$insertStmt->bindParam(3,$lat);
$insertStmt->bindParam(4,$lng);
$insertStmt->bindParam(5,$type);
$insertStmt->bindParam(6,$link);
//Execute query
$insertStmt->execute();
} #2
else{
"No rows inserted.";
}#2
} #1
else {#1
echo "Rows matched the query."; //EDIT From No row
} #1
}// End try
catch(PDOException $e) {
echo "I'm sorry I'm afraid you can't do that.". $e->getMessage() ;// Remove or modify after testing
file_put_contents('PDOErrors.txt',date('[Y-m-d H:i:s]').", myFile.php, ". $e->getMessage()."\r\n", FILE_APPEND);
}
I have converted your code to PDO as it is advisable to stop using mysql_functions as these a deprecated.
I have left you to implement how you will deal with geocoding not returning coordinates. You can also check and deal with the following status codes
OVER_QUERY_LIMIT
ZERO_RESULTS
REQUEST_DENIED
INVALID_REQUEST
See pastebin For status code implementation
Going by our earlier comments, there are just a couple of changes required that should get you back on your feet.
These are, changing the address for v3 geocoding
define("MAPS_HOST", "maps.googleapis.com");
$base_url = "http://" . MAPS_HOST . "/maps/api/geocode/xml?";
$request_url = $base_url . "address=" . urlencode($address) . "&sensor=false";
And secondly changing the path in the returned xml file for setting lat/long
$coordinates = $xml->Response->Placemark->Point->coordinates;
$coordinatesSplit = split(",", $coordinates);
// Format: Longitude, Latitude, Altitude
$lat = $coordinatesSplit[1];
$lng = $coordinatesSplit[0];
Can be completely replaced with
$lat = $xml->result->geometry->location->lat;
$lng = $xml->result->geometry->location->lng;
The next piece about stopping it from going over geocoding limits. What you need to do is set a simple check before you run through the geocoding.
while ($row = #mysql_fetch_assoc($result)) {
if (!($row['lat'] * 1)) {// add this line
$geocode_pending = true;
while ($geocode_pending){
//do geocoding stuff
}
}
}// add this close
}

how to check if a file already exists in database?

trying to check to see if the file already exist but it doesn't work LINE 6
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
if (file_exists($_FILES['userfile']['name']))
{
echo $_FILES['userfile"]["name'] . " already exists. ";
}else{
$fp= fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
//include 'library/config.php';
//include 'library/opendb.php';
$query = "INSERT INTO upload (name, size, type, content )
VALUES ('$fileName', '$fileSize', '$fileType', '$content')";
mysql_query($query) or die('Error, query failed');
//include 'library/closedb.php';
echo "<br>File $fileName uploaded<br>";
}
}
$_FILES['userfile"]["name']
Make sure your opening quotes match the closing ones. Example valid strings are "this" and 'this', for example.
echo $_FILES['userfile']['name'] . " already exists. ";
echo $_FILES["userfile"]["name"] . " already exists. ";
// etc.

Storing database structure

Is there some tool that can store for me the database structure, say in some xml file or something like that.
And later from the code it can generate for me the sql query for this database creation ?
Currently I am working with MySQL , but it probably does not matter .
Just I not want to maintain my self all those things.
In my experience I have used MySQL Workbench to take care of issues like this. If you download Workbench (assuming you don't have it already) from http://wb.mysql.com/ you will have the option to "Create an EER diagram from an existing database." This will create an EER diagram which is a good visual presentation of the database with which you are working. The .mwb file that you can then save can be loaded and then "forward engineered" into local/external database.
Mysqldump is another alternative to use at the command line. It will, by default, dump out the entire schema structure and contained data. However, if you are just looking for database structure including views and routines and you do not care about the data itself then you need to throw some extra parameters into the command.
In my experience Mysqldump is quick and easy whereas EER diagrams are easier to share with others and then forward engineer back onto other DBs from the Workbench application.
EDIT
You should note that just because you export the database create table queries to a .sql file or .mwb file that you can't just copy and paste the text into another platform (Microsoft SQL, Oracle, etc) and expect it to work. Syntax across different versions of SQL is (obviously) different.
THE FOLLOWING ANSWER USES PHP, I am keeping it here for future users.
I wrote code specifically to do that (in PHP):
$db = mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());
$allTables = Array
(
//put all table names in this array
);
foreach($allTables as $tbl){
define($tbl, $tbl);
}
$clm = '$columns';
$inds = '$indexes';
$query = "SHOW TABLES IN {$dbname}";
$tables = array();
$result = mysql_query($query) or die("ERROR ONE:".mysql_error());
while($row = mysql_fetch_array($result)){
$tables[] = $row["Tables_in_{$dbname}"];
}
//TO GET ARRAY FOR TABLE DISPLAY:
$cols = array();
foreach($tables as $tbl){
// echo "<br/>".
$query = "SHOW COLUMNS FROM $tbl";
$cols[$tbl] = array();
$result = mysql_query($query) or die("ERROR ONE:".mysql_error());
while($row = mysql_fetch_array($result)){
$cols[$tbl][] = array('Field'=>$row['Field'],
'Type'=>$row['Type'],
'Null'=>$row['Null'],
'Default'=>$row['Default'],
'Extra'=>$row['Extra'],
);
}
}
$index = array();
$query = "SELECT * FROM information_schema.statistics
WHERE TABLE_SCHEMA = '{$dbname}';
";
$result = mysql_query($query) or die("ERROR ONE:".mysql_error());
while($row = mysql_fetch_array($result)){
$index[$row['TABLE_NAME']][] = array('INDEX_NAME'=>$row['INDEX_NAME'],
'COLUMN_NAME'=>$row['COLUMN_NAME'],
'INDEX_TYPE'=>$row['INDEX_TYPE'],
'INDEX_NAME'=>$row['INDEX_NAME'],
'SEQ_IN_INDEX'=>$row['SEQ_IN_INDEX'],
);
}
//echo "<pre>";print_r($index);
//exit;
//TO GET THE ARRAY VARIABLE
echo "<pre>
<?php
$clm = Array (";
foreach ($cols as $key=>$tbl){
echo "
$key => Array (";
foreach($tbl as $col){
echo "
Array ( ";
foreach($col as $k=>$val){
echo "
'$k' => \"$val\",";
}
echo "
),";
}
echo "
),";
}
echo "
);";
echo "</pre>";
echo "<pre>
$inds = Array (";
foreach ($index as $key=>$tbl){
echo "
$key => Array (";
foreach($tbl as $col){
echo "
Array ( ";
foreach($col as $k=>$val){
echo "
'$k' => \"$val\",";
}
echo "
),";
}
echo "
),";
}
echo "
);
?>";
echo "</pre>";
Paste the result to this in a php file (called currentDB.php).
Then in another file is where the creation happens with the file you created:
define('BY_COL', 'column');
define('BY_IND', 'index');
$allTables = Array
(
//put all table names in this array
);
foreach($allTables as $tbl){
define($tbl, $tbl);
}
include_once 'currentDB.php';
$query = "SHOW TABLES IN $dbname";
$tables = array();
$result = mysql_query($query) or die("ERROR ONE:".mysql_error());
while($row = mysql_fetch_array($result)){
$tables[] = $row["Tables_in_$dbname"];
}
$checkTables = checkTables($tables);
echo "THE FOLLOWING TABLES <b>ARE</b> IN THE DB: <br />
<pre>";print_r(array_diff($allTables,$checkTables));echo "</pre><br />";
if($checkTables){
echo "THE FOLLOWING TABLES <b>ARE NOT</b> IN THE DB: <br />".
// "<pre>";print_r($checkTables);echo "</pre><br />";
"";
createTables($checkTables);
$query = "SHOW TABLES IN $dbname";
$tables = array();
$result = mysql_query($query) or die("ERROR ONE:".mysql_error());
while($row = mysql_fetch_array($result)){
$tables[] = $row["Tables_in_$dbname"];
}
}
//TO GET ARRAY FOR TABLE DISPLAY:
$cols = array();
foreach($tables as $tbl){
// echo "<br/>".
$query = "SHOW COLUMNS FROM $tbl";
$cols[$tbl] = array();
$result = mysql_query($query) or die("ERROR ONE:".mysql_error());
while($row = mysql_fetch_array($result)){
$cols[$tbl][] = array('Field'=>$row['Field'],
'Type'=>$row['Type'],
'Null'=>$row['Null'],
'Default'=>$row['Default'],
'Extra'=>$row['Extra'],
);
}
}
$checkTables = checkCols($cols);
if($checkTables){
echo "THE FOLLOWING COLS <b>ARE DIFFERENT</b> IN THE DB: <br />".
// "<pre>";print_r($checkTables);echo "</pre><br />".
"";
alterTable($checkTables);
}
$index = array();
$query = "SELECT * FROM information_schema.statistics
WHERE TABLE_SCHEMA = '$dbname';
";
$result = mysql_query($query) or die("ERROR ONE:".mysql_error());
while($row = mysql_fetch_array($result)){
$index[$row['TABLE_NAME']][] = array('INDEX_NAME'=>$row['INDEX_NAME'],
'COLUMN_NAME'=>$row['COLUMN_NAME'],
'INDEX_TYPE'=>$row['INDEX_TYPE'],
'INDEX_NAME'=>$row['INDEX_NAME'],
'SEQ_IN_INDEX'=>$row['SEQ_IN_INDEX'],
);
}
$checkTables = checkIndexes($index);
if($checkTables){
echo "THE FOLLOWING INDEXES <b>ARE DIFFERENT</b> IN THE DB: <br />".
// "<pre>";print_r($checkTables);echo "</pre><br />".
"";
alterTable($checkTables,BY_IND);
}
//echo "<pre>";print_r($indexes);echo "</pre><br />";
function checkTables($array){
$tbls = $GLOBALS['allTables'];
$diff = array_diff($tbls,$array);
if($diff){
return $diff;
}
return array();
}
function checkCols($array){
$cols = $GLOBALS['columns'];
$diff = array_diff_no_cast($cols,$array);
if($diff){
// echo "HI<br />";
return $diff;
}
return array();
}
function checkIndexes($array){
$ind = $GLOBALS['indexes'];
$diff = array_diff_no_cast($ind,$array);
if($diff){
// echo "HI<br />";
return $diff;
}
return array();
}
function createTables($tables){
$cols = $GLOBALS['columns'];
$ind = $GLOBALS['indexes'];
foreach($tables as $t){
$thisCols = (isset($cols[$t])?$cols[$t]:array());
$thisInd = (isset($ind[$t])?fromIndex($ind[$t]):array());
$create = "CREATE TABLE `$t` (\n";
foreach($thisCols as $k=>$c){
// echo "<pre>$k\n{$c['Default']}</pre>";
if($c['Default']=='CURRENT_TIMESTAMP'){
// echo "IN HERE";
$c['Extra'] = " ON UPDATE CURRENT_TIMESTAMP";
}
$create .= "`{$c['Field']}` {$c['Type']} ".
(($c['Null']=='NO')?'NOT NULL':'')." ".
((strlen($c['Default'])>0)?"DEFAULT ".
(is_quoted($c['Default'])?"'{$c['Default']}'":"{$c['Default']}"):'').
"{$c['Extra']}";
if(count($thisCols)!==($k+1)){
$create .= ",\n";
}
else
$create .= "\n";
}
$i = 0;
foreach($thisInd as $k=>$c){
if($i == 0){
$create .= ",\n";
}
if($c['INDEX_NAME']=='PRIMARY'){
$create .= "PRIMARY ";
}
else{
$iName = explode("_",$c['INDEX_NAME']);
if(array_search("UNIQUE",$iName)){
$create .= "UNIQUE ";
}
}
$create .= "KEY ".
(($c['INDEX_NAME']=='PRIMARY')?'':"`{$c['INDEX_NAME']}`")." ({$c['COLUMN_NAME']})";
if(count($thisInd)!==($i+1)){
$create .= ",\n";
}
else
$create .= "\n";
// echo "<pre>";print_r($c);echo "</pre>";
$i++;
}
$create .= ");";
// echo "<pre>$create</pre>";
mysql_query($create) or die("ERROR CREATE:".mysql_error());
echo "CREATED $t<br />";
}
// die;
}
function fromIndex($ind){
$return = array();
foreach($ind as $i){
$return[$i['INDEX_NAME']]['INDEX_NAME'] = $i['INDEX_NAME'];
// echo $i['COLUMN_NAME']." -- <br/>".
$return[$i['INDEX_NAME']]['COLUMN_NAME'] = (isset($return[$i['INDEX_NAME']]['COLUMN_NAME'])?"{$return[$i['INDEX_NAME']]['COLUMN_NAME']}, `{$i['COLUMN_NAME']}`":"`{$i['COLUMN_NAME']}`");
}
// echo "<pre>";print_r($return);echo "</pre>";
// die;
return $return;
}
function alterTable($table, $type = BY_COL){
// echo "<u>";
switch ($type){
case BY_COL:
// echo BY_COL;
$tbls = $GLOBALS['cols'];
$realTbls = $GLOBALS['columns'];
// echo "<pre>";print_r($table);echo"</pre>";
// die;
foreach($table as $k=>$t){
// echo
// $query = "SHOW COLUMNS FROM $k";
// echo "<br />";
foreach($t as $ky=>$col){
// echo
if($ky == 0){
$after = 'FIRST';
}
else {
$after = "AFTER `{$realTbls[$k][$ky-1]['Field']}`";
}
$primary = false;
if($col['Default']=='CURRENT_TIMETAMP'){
$col['Extra'] .= " ON UPDATE CURRENT_TIMESTAMP";
}
if($col['Extra'] == 'auto_increment'){
$query2 = "ALTER TABLE `$k` ADD PRIMARY KEY ( `{$col['Field']}` )";
$query3 = "ALTER TABLE `$k` CHANGE COLUMN `{$col['Field']}`
`{$col['Field']}` {$col['Type']} ".($col['Null']=='YES'?'NULL':'NOT NULL').
((!empty($col['Default']))? ' DEFAULT '.(is_quoted($col['Default'])?"'{$col['Default']}'":$col['Default']):'').
" {$col['Extra']}".
" $after;";
$primary = true;
$col['Extra'] = "";
}
// echo
$query = "ALTER TABLE `$k` ".(field_in_array($tbls[$k],$col['Field'])?"CHANGE COLUMN `{$col['Field']}`":"ADD COLUMN").
" `{$col['Field']}` {$col['Type']} ".($col['Null']=='YES'?'NULL':'NOT NULL').
((!empty($col['Default']))? ' DEFAULT '.(is_quoted($col['Default'])?"'{$col['Default']}'":$col['Default']):'').
" {$col['Extra']}".
" $after;";
// echo "<br/>";
mysql_query($query) or die("ERROR CREATE: $query".mysql_error());
if($primary){
mysql_query($query2) or die("ERROR CREATE: $query2".mysql_error());
mysql_query($query3) or die("ERROR CREATE: $query3".mysql_error());
}
echo "ADDED $k: {$col['Field']}";
echo "<br />";
}
// if($k == 'sessions'){
// echo "<pre>$ky:\n";print_r($tbls[$k]);die;
// }
}
break;
case BY_IND:
// echo BY_IND;
$tbls = $GLOBALS['index'];
foreach($table as $k=>$t){
$addTbls= fromIndex($table[$k]);
$thisInd = (isset($tbls[$k])?fromIndex($tbls[$k]):array());
// echo "<pre>$k:\n";print_r($addTbls);
foreach($addTbls as $added){
$beg = "INDEX";
if($added['INDEX_NAME']=='PRIMARY'){
$beg = "PRIMARY KEY";
$added['INDEX_NAME'] = '';
}
else{
$iName = explode("_",$added['INDEX_NAME']);
if(array_search("UNIQUE",$iName)){
$beg = "UNIQUE ".$beg;
}
}
// echo
$query = "ALTER TABLE `$k` ".(field_in_array($thisInd,$added['INDEX_NAME'],'INDEX_NAME')?"DROP INDEX `{$added['INDEX_NAME']}`, ":'')."ADD $beg `{$added['INDEX_NAME']}` ({$added['COLUMN_NAME']})";
mysql_query($query) or die("ERROR CREATE:".mysql_error());
echo "ADDED $k: {$added['INDEX_NAME']}";
echo "<br />";
}
}
// die;
break;
}
// echo "</u><br />";
}
function is_quoted($str){
if(is_numeric($str))
return false;
if($str == 'CURRENT_TIMESTAMP')
return false;
return true;
}
function field_in_array($arr, $field, $type = 'Field'){
foreach($arr as $val){
// echo "HERE: $field, $type";
// print_r($val);echo "<br/>";
if($val[$type]==$field){
// echo "HI";
return true;
}
}
return false;
}
##################################
# FUNCTION - multidim diff #
##################################
function array_diff_no_cast(&$ar1, &$ar2) {
$diff = Array();
foreach ($ar1 as $key => $val1) {
foreach($val1 as $k=>$val2){
if (!isset($ar2[$key]) || array_search($val2, $ar2[$key]) === false) {
$diff[$key][$k] = $val2;
}
}
}
return $diff;
}
You can export your database with Mysqldump. The web page has all the details on how to use it.
If you want the SQL to create the table, you can use:
SHOW CREATE TABLE tblname
If you have data, foreign keys, stored procedures and views in your database then the MySQL Workbench can forward reverse all that for you.
For MySQL and others, you might want to try the DESCRIBE TABLE.
You might want to look into the mysqldump utility. It will create a copy of your database in SQL format. (Note to avoid a problem I ran into: Be sure to run it with --routines if you want to also capture your stored functions and procedures!)
A typical command would look something like this:
mysqldump --routines -Q --opt -p -u username databasename >savefile.sql
Also, for large databases, these files can get quite large. You might also want to consider gzipping them or otherwise compressing them on the fly, using something like:
mysqldump --routines -Q --opt -p -u username databasename | gzip >savefile.sql.gz
use phpMyAdmin u can export your structure to XML,SQL,CSV and many other by using export option