PHP sessions work by default with my configuration, if I just go session_start() and try the standard session increment test it works.
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 0;
} else {
$_SESSION['count']++;
}
However I want to use a MySQL table for session storage. I've put together my sessions.php file with all the functions, copied them right out of a book like a n00b, and the functions work (affect the database) if I call them like regular functions, but using the standard test above does not work. It sets the session for just the page load, and no change in the database. I put a line in each function to log each call, and the log reflects that the functions are being called by session_start().
Here's what my code looks like:
session_module_name("user");
session_set_save_handler("session_open", "session_close",
"session_read", "session_write", "session_remove", "session_gc");
session_start();
session_open, etc, being the name of my functions. I've even tried another set of functions out of an o'rly example, and got the same results.
Any ideas why? session_register() also yields the same results.
EDIT: here are the actual functions, I apologize for the length, but I log everything in dev.
function session_db(){
return("my_db_name");
}
function session_table(){
return("sessions_table");
}
function session_log($message){
if($file = fopen($application["siteroot"] . 'log/session.txt', "a")){
fwrite($file, date("Y-m-d H:i:s ") . $message . "\n");
fclose($file);
}
}
function session_open($path, $name){
session_log("session_open");
return(true);
}
function session_close(){
session_log("session_close");
return(true);
}
function session_read($id){
session_log("session_read");
if(!mysql_select_db(session_db())){
session_log("session_read select database error: " . mysql_error());
return(false);
}
$sql = "select * from " . session_table() . " where id='" . $id . "'";
if(!$result = mysql_query($sql)){
session_log("MySQL error: " . mysql_error() . " with SQL: " . $sql);
return(false);
}
if(mysql_num_rows($result)){
session_log("MySQL query returned " . mysql_num_rows($result) . "rows.");
$row = mysql_fetch_assoc($result);
session_log("session_read returned " . $row["data"]);
return($row["data"]);
}
else{
session_log("session_read found zero rows with SQL: " . $sql);
return("");
}
}
function session_write($id, $data){
session_log("session_write");
if(!mysql_select_db(session_db())){
session_log("session_write select database error: " . mysql_error());
return(false);
}
$sql = "update " . session_table() . " set data = '" . addslashes($data) . "', time=null";
if(isset($PHP_AUTH_USER)){
$sql .= ", user='" . addslashes($PHP_AUTH_USER) . "'";
}
$sql .= " where id='" . $id . "'";
if(!$result = mysql_query($sql)){
session_log("session_write error " . mysql_error() . " with SQL: " . $sql);
return(false);
}
if(mysql_affected_rows()){
session_log("session_write update affected " . mysql_affected_rows() . " rows with SQL: " . $sql);
return(true);
}
session_log("session_write updated zero rows with SQL: " .$sql);
$sql = "insert into " . session_table() . "(data,id) values('" . addslashes($data) . "','" . $id . "')";
if(!$result = mysql_query($sql)){
session_log("session_write error " . mysql_error() . "with SQL: " . $sql);
return(false);
}
else{
session_log("mysql_write inserted with SQL: " . $sql);
return(true);
}
}
function session_remove($id){
session_log("session_remove");
if(!mysql_select_db(session_db())){
session_log("session_remove select database error: " . mysql_error());
return(false);
}
$sql = "delete " . session_table() . " where id='" . $id . "'";
if($result = mysql_query($sql)){
session_log("MySQL query delete worked");
return(true);
}
else{
session_log("MySQL update error: " . mysql_error() . " with SQL: " . $sql);
return(false);
}
}
function session_gc($life){
session_log("session_gc");
if(!mysql_select_db(session_db())){
session_log("session_gc select database error: " . mysql_error());
return(false);
}
$sql = "delete " . session_table() . " where time < '" . date("YmdHis", time() - $life) . "'";
print("session_gc sql: " . $sql);
if($result = mysql_query($sql)){
session_log("session_gc deleted " . mysql_affected_rows() . " rows.");
return(true);
}
else{
session_log("session_gc error: " . mysql_error() . " with SQL: " . $sql);
return(false);
}
}
I don't think you need the call to session_module_name, try commenting it out and see what happens.
There are a couple of things...
We might need to see, at the very least, the actual functions.
You probably want to register a shutdown function, your writes are probably being called too late to save to the database.
register_shutdown_function('session_write_close');
Just to clarify, the reason for the above is that the write and close functions are normally called after objects are destroyed. This call will ensure that these are made before object destruction.
Related
There does not seem to be a repeat of this question and I feel this should be a simple fix.
I have tested the stored procedure and when adding the parameters it works fine,
I have also tested a simple SQL statement which also works as expected.
However, when I try to pass my variables into the statement, I get a "Zero results using SQL:" I have also tried to do this as just a prepared statement or as just pure SQL with my variables, but again it never stores anything in the database.
The debug output shows what I am trying to pass, but nothing goes into the database
Here is the full code
require_once (getcwd() . "/lib/dataLib.php");
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
if (isset($_POST['btnSubmit']))
{
$projectName = $_POST['projectName'];
$projectDescription = $_POST['projectDescription'];
$projectLink = $_POST['projectLink'];
addItemToDatabase($projectName, $projectDescription, $projectLink);
}
}
/********************************
* addItemToDatabase
*******************************/
function addItemToDatabase($name, $description, $link)
{
$projectLinkSanSpace = str_replace(' ', '', $link);
$projectLinkAsLink = "<a href='project/" . $projectLinkSanSpace . "'>" . $link . "</a>";
databaseConnection('programWork');
$conn = new mysqli(DBF_SERVER, DBF_USER, DBF_PASSWORD, DBF_NAME);
if ($conn -> connect_error)
{
die("Connection Failed!: " . $conn ->connect_error);
}
/*$sql = 'insert into projectList (
*projectName,
*projectDescription,
*projectPage,
*projectSource)
*Values ("Stuff", "Things", "Yeah", "Yeah")'; */
$sql = "call insertItemIntoWork($name, $description, $projectLinkAsLink, $projectLinkAsLink)";
$result = $conn->query($sql);
displayResult($result, $sql);
}
some notes on the code,
I am using a lib to call external functions which I did not copy/paste here, as I do not think they are relevant to the question. I also did not include the HTML bits which is just the form which should be fairly straight forward, and should work since the debug displayResults() shows values.
Bottom line question is, is there something procedural that I am screwing up here. I do not have to call a function I suppose but is this a situation where the variables are set after the query is ran?
UPDATE
I added an error handler per Jay below:
$echoSuccess = true;
$msg = "The query completed successfully";
if ($conn->query($sql) === TRUE)
{
if ($echoSuccess)
{
echo "<span class='errMsg'>" . $msg . " successful.</span><br />";
}
} else
{
echo "<strong>Error when: " . $msg . "</strong> using SQL: " . $sql . "<br />" . $conn->error;
//displayResult($result, $sql)
}
Saying there are errors in my SQL.
I think I can work those out and on account of that I do not think this question needs further answering, but rather illustrates the need of error handlers
So,
Thank you Jay Blanchard for pointing me in the right direction, turns out the spaces in my input were causing issues entering items into the database.
To fix this I had to add quotes around my parameters, though this seems like an odd requirement (perhaps I am missing something)
But it works now as expected.
Here are the alterations:
error_reporting(E_ALL); ini_set('display_errors', 1);
include "lib/style.php";
require_once (getcwd() . "/lib/coleSterlingLib.php");
//require_once (getcwd() . "/lib/jsFormInteraction.js");
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
if (isset($_POST['btnSubmit']))
{
$projectName = $_POST['projectName'];
$projectName = "'" . $projectName . "'";
$projectDescription = $_POST['projectDescription'];
$projectDescription = "'" . $projectDescription . "'";
$projectLink = $_POST['projectLink'];
$projectLink = "'" . $projectLink . "'";
addItemToDatabase($projectName, $projectDescription, $projectLink);
}
}
Note the $projectName = "'" . $projectName . "'";
Everything else stayed roughly the same
function addItemToDatabase($name, $description, $link)
{
$projectLinkSanSpace = str_replace(' ', '', $link);
$projectLinkAsLink = "<a href='project/" . $projectLinkSanSpace . "'>" . $link . "</a>";
databaseConnection('programWork');
$conn = new mysqli(DBF_SERVER, DBF_USER, DBF_PASSWORD, DBF_NAME);
if ($conn->connect_error)
{
die("Connection Failed!: " . $conn->connect_error);
}
//$sql = 'insert into projectList (projectName, projectDescription, projectPage, projectSource) Values ("Stuff", "Things", "Yeah", "Yeah")';
$sql = "call insertItemIntoWork($name, $description, $link, $link)";
//$result = $conn->query($sql);
$echoSuccess = true;
$msg = "The query completed successfully";
if ($conn->query($sql) === TRUE)
{
if ($echoSuccess)
{
echo "<span class='errMsg'>" . $msg . " successful.</span><br />";
}
} else
{
echo "<strong>Error when: " . $msg . "</strong> using SQL: " . $sql . "
<br />" . $conn->error;
//displayResult($result, $sql)
}
}
I've got a simple form to delete users from the DB -
<form role="form" class="delete_user" method="post" action="/user_delete.php?id='+ID+'"><button type="submit" class="tiny button" name="delete" value="1"><span class="glyphicon glyphicon-trash"></span></button></form>
The PHP -
if(isset($_POST['delete'])){
$db->query("DELETE FROM " . TABLES_PREFIX . "users WHERE id = " . $id);
$db->query("DELETE FROM " . TABLES_PREFIX . "posts_following WHERE user_id = " . $id);
echo '<script>console.log("User deleted? I suppose?")</script>';
} else {
Leave(FORUM_URL.'users.php');
}
The jquery -
$('[name="delete"]').click(function(){
var Q = confirm('Delete '+NAME+'?');
if ( Q === true ) {
$.post('/user_delete.php?id='+ID, function(data, status){
console.log('Data: '+data);
console.log('status: '+status);
});
}
Everything works, however, I'm confused as to how to verify that the user was truly deleted from the DB. Sure, I can use .done() or if (status===200) but I'm not sure if that means the user was actually deleted of just that user_delete.php page was successfully accessed.
Assuming you're using mysqli for this
if(isset($_POST['delete'])){
$response = ['success' => true];
$db->query("DELETE FROM " . TABLES_PREFIX . "users WHERE id = " . (int)$id);
if($db->affected_rows) {
$db->query("DELETE FROM " . TABLES_PREFIX . "posts_following WHERE user_id = " . (int)$id);
} else {
$response['success'] = false;
}
echo json_encode($response);
}
What we're doing is checking affected_rows to see if the query was successful. We're then returning a JSON object so your AJAX request can parse it and see if it was successful. I also cast your user ID so it's less vulnerable to SQL injection. You'll probably want to perform some sort of permissions check to make sure the caller is authorized to delete the user.
Something like this should work:
if(isset($_POST['delete'])){
$db->query("DELETE FROM " . TABLES_PREFIX . "users WHERE id = " . $id);
$db->query("DELETE FROM " . TABLES_PREFIX . "posts_following WHERE user_id = " . $id);
$response = $db->query("SELECT id FROM " . TABLES_PREFIX . "users WHERE id = " . $id . " LIMIT 1");
if(mysql_fetch_array($result)){
echo '<script>console.log("User deleted successfully")</script>';
} else {
Leave(FORUM_URL.'users.php');
}
You can use try catch statement. If any commands inside try block fails, the code will jump to 'catch' block and throw an error message with what happened.
try
{
if(isset($_POST['delete']))
{ // Sets PDO to throw an expcetion if anythig goes wrong on DB operation
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->query("DELETE FROM " . TABLES_PREFIX . "users WHERE id = " . $id);
$db->query("DELETE FROM " . TABLES_PREFIX . "posts_following WHERE user_id = " . $id);
echo '<script>console.log("user deleted successfully")</script>';
}
else
{
Leave(FORUM_URL.'users.php');
}
}
catch (Exception $e) {
echo '<script>console.log("user delete fail. Err:' + $e->getMessage() + ' ")</script>';
}
I'm working on a page, where users post their betting picks. In MySQL I have the table bets (id, event, pick, odds, stake, analysis, status, profit).
I would like to check if 'status' is empty in MySQL, but the if() statement is not working. If it's empty, it should output all the bets from a user. The code posted is in a for loop.
So what is wrong with the if() statement? And is there any better way to do this?
$result = queryMysql("SELECT * FROM bets WHERE user='$user'");
$row = mysqli_fetch_array($result);
if ('' !== $row['status']) {
echo "Status: " . $status . "</div>" .
"Published by: " . $user . "<br>" .
"PICK: " . $pick . "<br>" .
"Odds: " . $odds . "<br>" .
"Stake: " . $stake . "<br>" .
nl2br($analysis) ;
}
You are using identical comparison, which would check for type & value both. === or !== as this involves comparing the type as well as the value.
Instead try -
if (!empty($row['status'])) { // assuming status would hold only strings (not false/0 etc)
Or
if ($row['status'] != '') {
Use mysqli_num_rows(). If its greater then 0 then we can say that query containing result so we can further proceed.
$result = queryMysql("SELECT * FROM bets WHERE user='$user'");
if(mysqli_num_rows($result) > 0)
{
$row = mysqli_fetch_array($result);
if ($row['status'] != "") {
echo "Status: " . $status . "</div>" .
"Published by: " . $user . "<br>" .
"PICK: " . $pick . "<br>" .
"Odds: " . $odds . "<br>" .
"Stake: " . $stake . "<br>" .
nl2br($analysis) ;
}
}
For status check you can use any of below method
if ($row['status'] != "") { }
OR
if (!empty($row['status'])) { }
If it's empty, it should output all the bets from a user. The code posted is in a for loop.
Since you are checking if it's empty, your if statement should be the other way round:
if ($row['status'] == '') {
Alternatively, you can use mysqli_num_rows() get the number of rows:
Returns the number of rows in the result set.
$result = queryMysql("SELECT * FROM bets WHERE user='$user'");
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_array($result);
echo "Status: " . $status . "</div>" .
"Published by: " . $user . "<br>" .
"PICK: " . $pick . "<br>" .
"Odds: " . $odds . "<br>" .
"Stake: " . $stake . "<br>" .
nl2br($analysis) ;
}
Also, there isn't such function called queryMysql():
$result = queryMysql("SELECT * FROM bets WHERE user='$user'");
It should be mysqli_query(). For mysqli_query(), the connection parameter is needed.
$result = mysqli_query($conn, "SELECT * FROM bets WHERE user='$user'");
The below php database query (from phpMyAdmin) only brings back one value (the first one or the oldest) into amcharts:
<?php
class custom_class2
{
var $charts; // reference to the calling object.
function customfunction2($content,$conf)
{
global $TSFE;
$TSFE->set_no_cache();
// do whatever you want here
// db connection
mysql_connect("hostname", "username", "password");
mysql_select_db("database name");
//db abfrage
$query = "
SELECT
YEAR(datetime) AS dy,
MONTH(datetime) -1 AS dm,
DAY(datetime) AS dd,
HOUR(datetime) AS th,
MINUTE(datetime) AS tm,
temp,
hum,
pressure
FROM stock1
ORDER BY datetime
";
// NEW: Variable definition
$zeilenzaehler = 1;
// output of the rows
$result = mysql_query($query) OR die("Error: $query <br>" . mysql_error());
while ($row = mysql_fetch_array($result))
{
// return
if ($zeilenzaehler != 1)
{
$content.= ",";
}
$content.= "{date: new Date(" . $row['dy'] . "," . $row['dm'] . "," . $row['dd'] . "," . $row['th'] . "," . $row ['tm'] . "),t:" . $row['temp'] . ",h:" . $row['hum'] . ",p:" . $row['pressure'] . "}";
return $content;
// Variable now on 2
$zeilenzaehler = 2;
}
}
}
?>
Everything else looks like its working fine. Many thanks for the help
You return the first found result in your while-loop. That is why you have just one result. Also as mysql_* functions are depreceted consider switching to
mysqli_* or PDO.
I am adding code from your request:
<?php
class custom_class2
{
var $charts; // reference to the calling object.
function customfunction2($content,$conf)
{
global $TSFE;
$TSFE->set_no_cache();
// do whatever you want here
// db connection
$mysqli = new mysqli("hostname", "username", "password", "database name");
if ($mysqli->connect_error) {
// your error handling here
}
//db abfrage
$query = "
SELECT
YEAR(datetime) AS dy,
MONTH(datetime) -1 AS dm,
DAY(datetime) AS dd,
HOUR(datetime) AS th,
MINUTE(datetime) AS tm,
temp,
hum,
pressure
FROM stock1
ORDER BY datetime
";
// NEW: Variable definition
$zeilenzaehler = 1;
// output of the rows
$result = $mysqli->query($query);
if (FALSE === $result) {
// you can put different error handling here
echo 'Error: ' . $query . ' ' . $mysql->error);
die();
}
$total = array();
while (NULL !== ($row = $result->fetch_array()))
{
// return
if ($zeilenzaehler != 1)
{
$content.= ",";
}
$content.= "{date: new Date(" . $row['dy'] . "," . $row['dm'] . "," . $row['dd'] . "," . $row['th'] . "," . $row ['tm'] . "),t:" . $row['temp'] . ",h:" . $row['hum'] . ",p:" . $row['pressure'] . "}";
// return $content;
// if you not return the first result you can gather results in array, so array will contain every row in result, $total[0], $total[1]...:
// $total[] = $content; or:
$total[] = "{date: new Date(" . $row['dy'] . "," . $row['dm'] . "," . $row['dd'] . "," . $row['th'] . "," . $row ['tm'] . "),t:" . $row['temp'] . ",h:" . $row['hum'] . ",p:" . $row['pressure'] . "}";
// Variable now on 2
$zeilenzaehler = 2;
}
$result->free();
return $total; // return all rows
}
}
?>
Trying to pull data out of a basic phpmyadmin database.
The code below pulls the data correctly (Commented out section verify).
I can write it to the screen and display it. (Not needed just testing)
Trying to insert it into another database however and it fails.
I've discovered that the while loops for inserting do not run. Although I can not find out why.
It's a basic localhost database (Testing right now) So the connect data is just temporary.
Any assistance is greatly appreciated
Thanks.
<?php
/*
Connect to database
*/
$webhost = 'localhost';
$webusername = 'root';
$webpassword = '';
$webdbname = 'transfertest';
$webcon = mysqli_connect($webhost, $webusername, $webpassword, $webdbname);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
/*
*
*/
$questions = mysqli_query($webcon, "SELECT * FROM questions");
$scenarios = mysqli_query($webcon, "SELECT * FROM scenarios");
$results = mysqli_query($webcon, "SELECT * FROM results");
$employees = mysqli_query($webcon, "SELECT * FROM employees");
/*
* These while loops display the content being pulled from the database correctly.
while ($row = mysqli_fetch_array($questions)) {
echo $row['questionID'] . " : " . $row['question'] . " : " . $row['answers'];
echo "</br>";
}
while ($row = mysqli_fetch_array($scenarios)) {
echo $row['scenarioID'] . " : " . $row['scenarioTitle'] . " : " . $row['scenarioInformation'];
echo "</br>";
}
while ($row = mysqli_fetch_array($results)) {
echo $row['employeeID'] . " : " . $row['scenarioID'] . " : " . $row['questionID'] . " : " . $row['answers'] . " : " . $row['correct'];
echo "</br>";
}
while ($row = mysqli_fetch_array($employees)) {
echo $row['employeeID'] . " : " . $row['firstName'] . " : " . $row['lastName'] . " : " . $row['email'] . " : " . $row['password'];
echo "</br>";
}
*/
/* //////////////////////////////////////////////////////////////////////////
Connect to database
*/
$mobhost = 'localhost';
$mobusername = 'root';
$mobpassword = '';
$mobdbname = 'exampletransfer';
$mobcon = mysqli_connect($mobhost, $mobusername, $mobpassword, $mobdbname);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
/*
*
*/
while ($row = mysqli_fetch_array($questions)) {
mysqli_query($mobcon, "INSERT INTO questions (questionID, question, answers) VALUES (" . $row['questionID'] . ", " . $row['question'] . ", " . $row['answers'] . ")");
}
while ($row = mysqli_fetch_array($scenarios)) {
mysqli_query($mobcon, "INSERT INTO scenarios (scenarioID, scenarioTitle, scenarioInformation) VALUES (" . $row['scenariosID'] . ", " . $row['scenarioTitle'] . ", " . $row['scenarioInformation'] . ")");
}
while ($row = mysqli_fetch_array($results)) {
mysqli_query($mobcon, "INSERT INTO results (employeeID, scenarioID, questionID, answers, correct) VALUES (" . $row['employeesID'] . ", " . $row['scenariosID'] . ", " . $row['questionID'] . ", " . $row['answers'] . ", " . $row['correct'] . ")");
}
while ($row = mysqli_fetch_array($employees)) {
mysqli_query($mobcon, "INSERT INTO employees (employeeID, firstName, lastName, email, password) VALUES (" . $row['employeesID'] . ", " . $row['firstName'] . ", " . $row['lastName'] . ", " . $row['email'] . ", " . $row['password'] . ")");
}
/*
Close Connections
*/
mysqli_close($webcon);
mysqli_close($mobcon);
/*
* Error code:
Notice: Undefined index: scenariosID on line 75
Notice: Undefined index: employeesID on line 78
Notice: Undefined index: scenariosID on line 78
Notice: Undefined index: employeesID on line 81
*/
?>
The problem is that you close your $webcon connection and then you try to read from it ^^
You try to do this... Thats not possible ;)
Prepare query mysqli_query($webcon, "SELECT * FROM questions");
Close connection <<< after that i cant read data
Read data
Try this please.
<?php
/**
* Connect to database
*/
$webhost = 'localhost';
$webusername = 'root';
$webpassword = '';
$webdbname = 'transfertest';
$webcon = mysqli_connect($webhost, $webusername, $webpassword, $webdbname);
if (mysqli_connect_errno())
{
echo 'Failed to connect to MySQL: ' . mysqli_connect_error();
}
/**
* Queries for reading
*/
$questions = mysqli_query($webcon, 'SELECT * FROM `questions`');
$scenarios = mysqli_query($webcon, 'SELECT * FROM `scenarios`');
$results = mysqli_query($webcon, 'SELECT * FROM `results`');
$employees = mysqli_query($webcon, 'SELECT * FROM `employees`');
/**
* Connect to database
*/
$mobhost = 'localhost';
$mobusername = 'root';
$mobpassword = '';
$mobdbname = 'exampletransfer';
$mobcon = mysqli_connect($mobhost, $mobusername, $mobpassword, $mobdbname);
if (mysqli_connect_errno())
{
echo 'Failed to connect to MySQL: ' . mysqli_connect_error();
}
/**
* Insert data from old database
*/
// questions
while ($row = mysqli_fetch_array($questions))
{
// escape your strings
foreach($row as $key => $val)
{
$row[$key] = mysqli_real_escape_string($mobcon, $row[$key]);
}
mysqli_query($mobcon, "INSERT INTO `questions` (`questionID`, `question`, `answers`) VALUES ('" . $row['questionID'] . "', '" . $row['question'] . "', '" . $row['answers'] . "');");
}
// scenarios
while ($row = mysqli_fetch_array($scenarios))
{
// escape your strings
foreach($row as $key => $val)
{
$row[$key] = mysqli_real_escape_string($mobcon, $row[$key]);
}
mysqli_query($mobcon, "INSERT INTO `scenarios` (`scenarioID`, `scenarioTitle`, `scenarioInformation`) VALUES ('" . $row['scenariosID'] . "', '" . $row['scenarioTitle'] . "', '" . $row['scenarioInformation'] . "');");
}
// results
while ($row = mysqli_fetch_array($results))
{
// escape your strings
foreach($row as $key => $val)
{
$row[$key] = mysqli_real_escape_string($mobcon, $row[$key]);
}
mysqli_query($mobcon, "INSERT INTO `results` (`employeeID`, `scenarioID`, `questionID`, `answers`, `correct`) VALUES ('" . $row['employeesID'] . "', '" . $row['scenariosID'] . "', '" . $row['questionID'] . "', '" . $row['answers'] . "', '" . $row['correct'] . "');");
}
// employees
while ($row = mysqli_fetch_array($employees))
{
// escape your strings
foreach($row as $key => $val)
{
$row[$key] = mysqli_real_escape_string($mobcon, $row[$key]);
}
mysqli_query($mobcon, "INSERT INTO `employees` (`employeeID`, `firstName`, `lastName`, `email`, `password`) VALUES ('" . $row['employeesID'] . "', '" . $row['firstName'] . "', '" . $row['lastName'] . "', '" . $row['email'] . "', '" . $row['password'] . "');");
}
/*
Close Connections
*/
mysqli_close($mobcon);
mysqli_close($webcon);
Pending it's on the same server and using the same username and password:
// Create a new MySQL database connection
if (!$con = mysql_connect('localhost', $username, $password)) {
die('An error occurred while connecting to the MySQL server!<br/>' . mysql_error());
}
if (!mysql_select_db($database)) {
die('An error occurred while connecting to the database!<br/>' . mysql_error());
}
// Create an array of MySQL queries to run
$sql = array(
'DROP TABLE IF EXISTS `exampletransfer.questions`;',
'CREATE TABLE `exampletransfer.questions` SELECT * FROM `transfertest.questions`'
);
// Run the MySQL queries
if (sizeof($sql) > 0) {
foreach ($sql as $query) {
if (!mysql_query($query)) {
die('A MySQL error has occurred!<br/>' . mysql_error());
}
}
}
If using MySQLi instead of MySQL:
// Create a new MySQL database connection
if (!$con = new mysqli('localhost', $username, $password, $database)) {
die('An error occurred while connecting to the MySQL server!<br/>' . $con->connect_error);
}
// Create an array of MySQL queries to run
$sql = array(
'DROP TABLE IF EXISTS `exampletransfer.questions`;',
'CREATE TABLE `exampletransfer.questions` SELECT * FROM `transfertest.questions`'
);
// Run the MySQL queries
if (sizeof($sql) > 0) {
foreach ($sql as $query) {
if (!$con->query($query)) {
die('A MySQL error has occurred!<br/>' . $con->error);
}
}
}
$con->close();