Using multiple database in one php script - php

This first part work very well in other script of mine. But in this example the script simply skip this part and goes to the end and execute the last query..
I don't know what I'm doing wrong because I do it exactly same yet it doesn't work. This is full script.
for ($i = 1; $i <= $numofservers; $i++)
{
if($servers[$i][1] == $server)
{
$srv = $i;
$connect = mysql_connect($servers[$srv][3], $servers[$srv][4], $servers[$srv][5]) or die('Could not connect: ' . mysql_error());
mysql_select_db($servers[$srv][6]);
}
}
$sql = mysql_query("SELECT * FROM db_users WHERE username = '".$nick."'") or die('Nick na serveru Neexistuje!' . mysql_error());
$sql = mysql_fetch_array($sql);
$balance = $sql['donate_balance'];
$steamid = $sql['steam_id'];
$balance = $balance + $price_sms;
$money = mysql_query("UPDATE db_users SET `donate_balance`='". $balance ."' WHERE steam_id = '".$steam_id."'");
<?php
$db_site_name = ''; // db connection name
$db_site_password = '';
$db_site_username = 'root'; // username of connection
$db_site_ip = '127.0.0.1:3306';
$link = mysql_connect($db_site_ip, $db_site_username, $db_site_password) or die('Could not connect: ' . mysql_error());
mysql_select_db($db_site_name) or die('Not connected<br>');
$serversquery = mysql_query("SELECT * FROM db_servers ORDER BY id");
$numofservers = 0;
while ($servers_array = mysql_fetch_array($serversquery))
{
$numofservers++;
$servers[$numofservers] = array(
$servers_array['id'],
$servers_array['name'],
$servers_array['about'],
$servers_array['server_ip'],
$servers_array['server_username'],
$servers_array['server_password'],
$servers_array['server_name'],
$servers_array['server_admin_rank'],
$servers_array['donate_factor']
);
}
if (isset($_GET["request"])){
$request_sms = ($_GET["request"]);
$status = ($_GET["status"]);
$message = ($_GET["message"]);
$request = mysql_query("UPDATE `sms_confirm` SET `status` = '".$status."' WHERE `sms_id` = '".$request_sms."'");
$findid = mysql_query("SELECT * FROM `sms_confirm` WHERE `sms_id` = '".$request_sms."' LIMIT 1") or die(mysql_error()); ;
$query = mysql_fetch_array($findid);
if ($query['status'] == 'DELIVERED' AND $query['added'] == 'false'){
$price_sms = $query['cena'];
$nick = $query['nick'];
$server = $query['server'];
for ($i = 1; $i <= $numofservers; $i++)
{
if($servers[$i][1] == $server)
{
$srv = $i;
$connect = mysql_connect($servers[$srv][3], $servers[$srv][4], $servers[$srv][5]) or die('Could not connect: ' . mysql_error());
mysql_select_db($servers[$srv][6]);
}
}
$sql = mysql_query("SELECT * FROM db_users WHERE username = '".$nick."'") or die('Nick na serveru Neexistuje!' . mysql_error());
$sql = mysql_fetch_array($sql);
$balance = $sql['donate_balance'];
$steamid = $sql['steam_id'];
$balance = $balance + $price_sms;
$money = mysql_query("UPDATE db_users SET `donate_balance`='". $balance ."' WHERE steam_id = '".$steam_id."'");
$link = mysql_connect($db_site_ip, $db_site_username, $db_site_password) or die('Could not connect: ' . mysql_error());
mysql_select_db($db_site_name) or die('Not connected<br>');
//this executes fine
$request = mysql_query("UPDATE `sms_confirm` SET `added` = 'true' WHERE `sms_id` = '".$request_sms."'");
}
}
//Header("HTTP/1.1 204 NO_CONTENT");
//Header("Content-type: text/plain");
?>

First of all, don't use mysql_* functions. It's deprecated and will be removed.
And if you want to use more than one database connection, you have to pass link to it to every function that will contact with your databases.
Eg, check here (second parameter).
Sample code
$link = mysql_connect($db_site_ip, $db_site_username, $db_site_password);
mysql_select_db($db_site_name, $link);
mysql_query($query, $link);

Related

Comparison for in SQL row selection not working?

This is the code that is not working:
$query = "SELECT * FROM $table WHERE text_id > '$last_id'"; //SELECT NEW MESSAGES
$result = mysqli_query($connection,$query);
if ($result && mysqli_num_rows($result) > 0)
{
//THIS SHOULD NOT BE RUNNING
}
I've verified over and over in phpMyAdmin and the text_id in the table and $last_id are both the integer value '1'. That being said, the condition equates to true every time the code runs.
Am I messing this code up, or is my thinking improper?
Here is entire script:
<?php
session_start();
$alias = $_SESSION['username'];
$host = 'localhost';
$user = '*';
$pass = '*';
$database = 'vethergen_db_accounts';
$table = 'table_messages';
$last_id_table = 'table_chat_sync';
$connection = mysqli_connect($host, $user, $pass) or die ("Unable to connect!");
mysqli_select_db($connection,$database) or die ("Unable to select database!");
$last_id_query = "SELECT alias FROM $last_id_table WHERE alias = '$alias'";
$last_id_result = mysqli_query($connection,$last_id_query);
$last_id_rows = mysqli_fetch_array($last_id_result);
if ($last_id_rows['alias'] === $alias)
{
$last_id = $last_id_rows['last_id'];
$query = "SELECT * FROM $table WHERE text_id > '$last_id'"; //SELECT NEW MESSAGES
$result = mysqli_query($connection,$query);
if ($result && mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
if ($row['alias'] === "Vether")
{
echo '<p id = "chat_text">'.'<b>'.$row['alias'].'</b>'.': '.$row['text']."</p>";
echo '<p id = "time_stamp">'.$row['time'].'</p>';
echo '<p id = "chat_number">'.$row['text_id'].'</p>';
}
else
{
echo '<p id = "chat_text">'.'<b class = "bold_green">'.$row['alias'].'</b>'.': '.$row['text']."</p>";
echo '<p id = "time_stamp">'.$row['time'].'</p>';
echo '<p id = "chat_number">'.$row['text_id'].'</p>';
}
echo '<hr class = "chat_line"></hr>';
$last_row_id = $row['text_id'];
}
}
//UPDATE LAST SYNC ID
$update_query = "UPDATE $last_id_table SET last_id = '$last_row_id' WHERE alias = '$alias'";
mysqli_query($connection,$update_query);
}
else
{
$update_query = "INSERT INTO $last_id_table (alias, last_id) VALUES('$alias','-1')";
mysqli_query($connection,$update_query);
}
?>
You should change ;
WHERE text_id > '$last_id'
to
WHERE text_id > $last_id
text_id column is integer and can't be compared like string.

Not getting correct value in return

The idea of the task is to allow the user to add and withdraw "money" to and from their account. The problem is I can add money, but I can't withdraw it
$funds = $_POST['funds'];
$withdraw_or_add = $_POST['list'];
if($withdraw_or_add == "add")
{
$sql = "UPDATE users SET userFunds = '".$funds."' WHERE userId = 1";
}
else
{
$info = mysql_query("SELECT * FROM users WHERE userId = '1'");
$info = mysql_fetch_assoc($info);
$new_fund = $info['userFunds'] - $funds;
$sql = "UPDATE users SET userFunds = '".$new_fund."' WHERE userId = 1";
}
mysql_select_db('details_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
mysql_close($conn);
So for example, let's say $fund = 5 and $info['userFunds'] = 20 then the variable $new_fund should be 15. But instead it equals -5. If anyone can help it would be much appreciated.
Firstly page of top you put used db connection related code :
$conn = mysql_connect('localhost', 'user', 'pass');
mysql_select_db('details_db');
and then bellow and removed mysql_select_db('details_db'); line after mysql_
$funds = $_POST['funds'];
$withdraw_or_add = $_POST['list'];
if($withdraw_or_add == "add")
{
$sql = "UPDATE users SET userFunds = '".$funds."' WHERE userId = 1";
}
else
{
$info = mysql_query("SELECT * FROM users WHERE userId = '1'");
$info = mysql_fetch_assoc($info);
$new_fund = $info['userFunds'] - $funds;
$sql = "UPDATE users SET userFunds = '".$new_fund."' WHERE userId = 1";
}
//mysql_select_db('details_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
mysql_close($conn);
Note: Please stop using mysql_* functions. mysql_* extensions have been removed in PHP 7. Please used PDO and MySQLi.

php mysql trying to use empty to only add a new record in table if a primary key exists in a different table

I am trying to only allow a submission via the form only if a party_id exists in a table using empty, here is my code at the moment it is still allowing everything through even if there is no party_id.
Any help would be great.
if($_SERVER["REQUEST_METHOD"]== "POST") {
$party_id = (int)$_POST["partyid"];
$name = $_POST["name"];
$date = $_POST["date"];
$length = (int)$_POST["length"];
$sql = "SELECT * FROM `party` WHERE `party_id`='" . $party_id . "'";
$res = mysqli_query($link, $sql);
if(empty($party_id)) { #Were any records found?
print '<p>No Parties with that ID found! please press the back button to select another party</p>';
} else {
$record = mysqli_fetch_assoc($res);
$party_name = $record["party_name"];
$price = $record["price"];
$cost = $price * $length;
$bookable = true;
$sql2 = "SELECT * FROM `reservations`" or die("Unable to connect to database");
A simpler way might be to just check if the query returned any results like this.
if($_SERVER["REQUEST_METHOD"]== "POST") {
$party_id = (int)$_POST["partyid"];
$name = $_POST["name"];
$date = $_POST["date"];
$length = (int)$_POST["length"];
$sql = "SELECT * FROM `party` WHERE `party_id`='$party_id'";
$res = mysqli_query($link, $sql);
if ( mysqli_num_rows($res ) == 0 ) {
print '<p>No Parties with that ID found! please press the back button to select another party</p>';
} else {
$record = mysqli_fetch_assoc($res);
$party_name = $record["party_name"];
$price = $record["price"];
$cost = $price * $length;
$bookable = true;
$sql2 = "SELECT * FROM `reservations`" or die("Unable to connect to database");

Cannot dynamically access updated versions of my mySQL database from within my flash game

I've created a game using Actionscript 3. In this game I save scores to an online mySQL database. I access this database from within my flash game by calling php scripts that I have written using the URLLoader class.
I load all the players scores so that they can be viewed at the begining of the game and then save as levels are completed.
My issue is that once I save a score and then reload all the scores at the main menu, I retrieve the scores that were loaded at the beginning of the game and none of the updated ones. I am only able to view the updated scores if I restart my game.
Here is the actionscript code for loading my score. This is called once when the main menu initialises.
getScoresRequest = new URLRequest("http://localhost/GetScores.php");
getScoresRequest.method = URLRequestMethod.GET;
getScoresLoader = new URLLoader();
getScoresVariables = new URLVariables();
getScoresVariables.email = Globals.email;
getScoresRequest.data = getScoresVariables;
getScoresLoader.dataFormat = URLLoaderDataFormat.TEXT;
getScoresLoader.addEventListener(Event.COMPLETE, completeHandler);
getScoresLoader.load(getScoresRequest);
private function completeHandler(e:Event):void
{
var xmlData:XML = new XML(e.target.data);
}
I then use this xmlData to display my scores.
Here is my php for loading my scores:
<?php
$email = $_REQUEST["email"];
$dbh=mysql_connect ("**********", "*****", "*******")
or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db ("*******",$dbh);
$query = "SELECT * FROM Scores WHERE email = '$email'";
$result = mysql_query($query, $dbh);
$xml_output = "<Scores>\n";
for($x = 0; $x < mysql_num_rows($result); $x++)
{
$row = mysql_fetch_assoc($result);
$xml_output .= "\t<Entry>\n";
$xml_output .= "\t\t<Level>" . $row['level'] . "</Level>\n";
$xml_output .= "\t\t<Score>" . $row['score'] . "</Score>\n";
$xml_output .= "\t</Entry>\n";
}
$xml_output .= "</Scores>";
echo $xml_output;
mysql_close($dbh);
?>
My actionscript for saving scores is very similar to loaded with the exeption of the loader.dataFormat is set to Variables instead of Text. If anyone would like me to post this I can do.
Here is the php for saving:
<?php
$email = $_REQUEST["email"];
$level = $_REQUEST["level"];
$score = $_REQUEST["score"];
$dbh=mysql_connect ("******", "********", "********")
or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db ("********",$dbh);
$query = "SELECT * FROM Scores WHERE email = '$email' AND level = '$level'";
$result = mysql_query($query, $dbh);
$row = mysql_num_rows($result);
$returnVars = array();
if($row > 0)
{
for($x = 0; $x < 1; $x++)
{
$currentRow = mysql_fetch_assoc($result);
if((int)$score > (int)$currentRow['score'])
{
$returnVars['prevHighScore'] = $currentRow['score'];
$updateQuery = "UPDATE Scores SET score = '$score' WHERE email = '$email' AND level = '$level'";
$result = mysql_query($updateQuery, $dbh);
$returnVars['newHighScore'] = $score;
$returnVars['type'] = "Score Updated";
}
else
{
$returnVars['prevHighScore'] = $currentRow['score'];
$returnVars['newHighScore'] = '0';
$returnVars['type'] = "Score Not Updated";
}
}
}
else
{
$insertQuery = "INSERT INTO Scores(email, level, score) VALUES('$email', '$level', $score)";
$result = mysql_query($insertQuery, $dbh);
$returnVars['newHighScore'] = $score;
$returnVars['prevHighScore'] = "0";
}
$returnVars['rows'] = $row;
$returnString = http_build_query($returnVars);
echo $returnString ;
mysql_close($dbh);
?>
My database is definitely updating as I'm able to view the contents.
If anyone has any ideas it would be greatly appreciated.
Shamelessly adding my own comment as answer
Try adding a random value to your url. Like:
http://localhost/GetScores.php?_rand=0.12324343213
and regenerate this value everytime you access your source.

SQL won't work? It doesn't come up with errors either

I have PHP function which checks to see if variables are set and then adds them onto my SQL query. However I am don't seem to be getting any results back?
$where_array = array();
if (array_key_exists("location", $_GET)) {
$location = addslashes($_GET['location']);
$where_array[] = "`mainID` = '".$location."'";
}
if (array_key_exists("gender", $_GET)) {
$gender = addslashes($_GET["gender"]);
$where_array[] = "`gender` = '".$gender."'";
}
if (array_key_exists("hair", $_GET)) {
$hair = addslashes($_GET["hair"]);
$where_array[] = "`hair` = '".$hair."'";
}
if (array_key_exists("area", $_GET)) {
$area = addslashes($_GET["area"]);
$where_array[] = "`locationID` = '".$area."'";
}
$where_expr = '';
if ($where_array) {
$where_expr = "WHERE " . implode(" AND ", $where_array);
}
$sql = "SELECT `postID` FROM `posts` ". $where_expr;
$dbi = new db();
$result = $dbi->query($sql);
$r = mysql_fetch_row($result);
I'm trying to call the data after in a list like so:
$dbi = new db();
$offset = ($currentpage - 1) * $rowsperpage;
// get the info from the db
$sql .= " ORDER BY `time` DESC LIMIT $offset, $rowsperpage";
$result = $dbi->query($sql);
// while there are rows to be fetched...
while ($row = mysql_fetch_object($result)){
// echo data
echo $row['text'];
} // end while
Anyone got any ideas why I am not retrieving any data?
while ($row = mysql_fetch_object($result)){
// echo data
echo $row->text;
} // end while
I forgot it wasn't coming from an array!

Categories