JSON decode to MySQL working on localhost but not Online Server - php

My code is as follows, I have changed the values of the Mysql login.
$json_url = "https://www.bitstamp.net/api/ticker/";
$json_data = file_get_contents($json_url);
$json_feed = json_decode($json_data);
$bitstamp_btc_low = $json_feed->low;
$bitstamp_btc_high = $json_feed->high;
$bitstamp_btc_ask = $json_feed->ask;
$bitstamp_btc_volume = $json_feed->volume;
$timestamp = date('Y-m-d H:i:s');
$connection = mysqli_connect("localhost",'username','password','database');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($connection,
"INSERT INTO `database` (Timestamp, Low, High,
Ask, Volume)
VALUES ('$timestamp', '$bitstamp_btc_low',
'$bitstamp_btc_high', '$bitstamp_btc_ask',
'$bitstamp_btc_volume')");
mysqli_close($connection);
When I execute the code on my localhost server it works fine, inserts the data in to the database, in the format i require and its great. When i upload it to my server though, it does not. The only column it enters data into is the '$timestamp' column. (I have set an independent request for the date, away from the default Mysql entry.) So it makes me believe that this information is being received from the script. Its just the low, high, ask and volume that is returning a 0 value.
I have contacted the API provider and they have confirmed that my host IP has not been black listed and all is well.
Im baffled as to why this is not working online, but it is offline, and just to confirm, even though its not entering the data into the cells, it is creating a new row just with 0 values.
I have just run through the error log and i am getting these errors PHP Notice: Trying to get property of non-object in /home/wpdhcskl/public_html/cron-jobs/cron_bitstamp.php on line #
# being the lines with;
$bitstamp_btc_low = $json_feed->low;
$bitstamp_btc_high = $json_feed->high;
$bitstamp_btc_ask = $json_feed->ask;
$bitstamp_btc_volume = $json_feed->volume;
Many thanks

You've got a database called database? Okay....
Anyways try putting ` around the field names as sometimes different environmens have different setups...
INSERT INTO `database` (`Timestamp`, `Low`, `High`, `Ask`, `Volume`)
Also you should really escape your values and use something like PDO.

Related

mssql_connect will not connect different DB on same SQL Server

$conn_161 = "192.168.0.161"; //local serwer adress
$user_161 = "ME";
$pass_161 = "what_is_the_password?";
$connect_161 = mssql_connect($conn_161,$user_161,$pass_161);
mssql_select_db ( 'DUKENUKEN3D' , $connect_161 );
//as requested - 1st DB connection and 1st query
$q_duke = "select * from DUKE /*DB1*/";
$r_duke = mssql_query($q_wartownik,$connect_161); //result
$connect_different_db = mssql_connect($conn_161,$user_161,$pass_161);
mssql_select_db ( 'BIGMAN' , $connect_different_db );
//second db and query
$q_bigman = "select * from BIGPEOPLE /*DB2*/";
$r_bigman = mssql_query($q_bigman,$connect_different_db ); //result
Error:
Warning: mssql_query() [function.mssql-query]: message: Invalid object name 'DUKE'.
Yes I know mssql_select_db is old, but I need to use it in this project. As you see I try to connect to same server but select 2 different DB at the same time, and run queries in the same php page (to connect data from 2 different DB). It seems it is not valiable? I even tried to run mssql_select_db just before doing the query to second DB, and then changing it back to first DB.
I understand this is limitation of the library (I will run all queries from LAST selected DB).
Is there a workaroud? Because all I got is to create page inside invisible iframe and there run php page with different db connection - far from good solution.
I would expect that this will work the same as it would if you were running this in a SQL environment directly (e.g. you can try it in SSMS or from the command line).
You can specify the database name when you reference the table in the query: e.g.
select * from db1.dbo.DUKE
This is standard SQL Server behaviour whenever you want to refer to an object which is outside the context of the current database.

MySQL Insert Into PHP Not Working

I am currently looking to run a basic insert query using PHP to submit HTML form data to MySQL database.
Unfortunately however the insert process isnt running.
In my Insert syntax I have tried including $_POST[fieldname], ive tried including variables as below, and ive even played around with different apostrphes but nothing seems to be working.
as a side dish, im also getting truck load of wamp deprication errors which is overwhelming, ive disabled in php.ini and php for apache.ini file and still coming up.
If anyone can advise what is wrong with my insert and anything else id be much thankful.
Ill keep this intro straightfoward.
Person logs in, if they try to get in without login they go back to login page to login.
I connect to database using external config file to save me updating in 50 places when hosting elsewhere.
Config file is working fine so not shown below.
database is called mydb.
Im storing the text field items into variables, then using the variables in the insert query.
unitID is an auto increment field so I leave that blank when running the insert.
Unfortunately nothing is going in to the mysql database.
Thanks in advance.
PS the text fieldnames are all correctly matched up
<?php
//Start the session
session_start();
//check the user is logged in
if (!(isset($_SESSION['Username']) )) {
header ("Location: LoginPage.php?i=1");
exit();
}
//Connect to the database
include 'config.php';
$UserName = $_SESSION['Username'];
$UserIdentification = $_SESSION['UserID'];
if(isset($_GET['i'])){
if($_GET['i'] == '1'){
$tblName="sightings";
//Form Values into store
$loco =$_POST['txtloco'];
$where =$_POST['txtwhere'];
$when =$_POST['txtdate'];
$time =$_POST['txttime'];
$origin =$_POST['txtorigin'];
$dest =$_POST['txtdest'];
$headcode =$_POST['txtheadcode'];
$sql= "INSERT INTO sightings (unitID, Class, Sighted, Date, Time, Origin, Destination, Headcode, UserID) VALUES ('','$loco', '$where', '$when', '$time', '$origin', '$dest', '$headcode', '$UserIdentification')";
mysql_select_db('mydb');
$result=mysql_query($sql, $db);
if($result){
$allocationsuccess = "Save Successful";
header ('Refresh: 2; url= create.php');
}
else {
$allocationsuccess = "The submission failed :(";
}
}
}
?>
"unitID is an auto increment field so I leave that blank when running
the insert"
That's not how it works. You have to omit it completely from the INSERT statement. The code thinks you're trying to set that field to a blank string, which is not allowed.
$sql= "INSERT INTO sightings (Class, Sighted, Date, Time, Origin, Destination, Headcode, UserID) VALUES ('$loco', '$where', '$when', '$time', '$origin', '$dest', '$headcode', '$UserIdentification')";
should fix that particular issue. MySQL will generate a value automatically for the field and insert it for you when it creates the row.
If your code had been logging the message produced by mysql_error() whenever mysql_query() returns false then you'd have seen an error being generated by your query, which might have given you a clue as to what was happening.
P.S. As mentioned in the comments, you need to re-write your code with a newer mysql code library and better techniques including parameterisation, to avoid the various vulnerabilities you're currently exposed to.

Target machine actively refuses mysqli database connection

I'm in the process of implementing a system for database table replication. I'm aware of the latter MySQL technique but I couldn't get it working. What I have now is essentially a preliminary implementation.
This is the code I have thus far.
//This is where DBHandler is defined
$documentRoot=$_SERVER['DOCUMENT_ROOT'];
require_once($documentRoot."/Classes/DBHandler.php");
$src_controller = new DBHandler();
$query = "SELECT * FROM table";
$temp = $src_controller->select($query);
//Convert temporary database contents into usable result
while($rowObject=mysql_fetch_object($temp)){
$result[]=$rowObject;
}
//Create database handler to handle database
$dest_controller = new mysqli("ip address", "user", "password", "database name");
if($mysqli->connect_errno){
$errorMessage = sprintf("'%s'", $mysqli->connect_error);
echo $errorMessage;
}
else{
$dest_controller->query("DELETE * FROM table");
//Processing of data goes here
foreach($result as $item){
//Create query to insert individual records
$start = "INSERT INTO table(field1, field2...) VALUES (";
$end = sprintf("'%s', %d, %d, %f, %f)", field1, field2...);
$start .= $end;
//Database handler uses $start to insert record
$dest_controller->query($start);
}
$dest_controller->close();
}
The database being read from is on a different server from the one being written to. I tried checking the host for the target database with the command "SHOW VARIABLES WHERE Variable_name = 'hostname'" and wound up with a site that just gives a "sorry, wrong page or we've moved" page. What's more is that the port number I see in the URL doesn't match up with what the "SHOW VARIABLES WHERE Variable_name = 'port'" command gives me. The latter command says 3306.
I'm not really sure what to do. We use cPanel X to connect to the database and there's an option to allow select IPs remote access to this database. I'm positive I granted access to the right addresses but this accomplished nothing.
Is this some kind of issue with the host or did I not use the right IP address for connection when I created the mysqli object?
If the MySQL port open on that server? Check with this:
telnet yoursever.address.com 3306
If telnet doesn't connect, then the port is blocked and you will need your hosting provider to open it up.

remote server CRON file does not add data to the table

im trying to write a query to insert data to my remote database table from a CRON file in my remote server. db connection happens through webservice and all that is working fine but the database does not get filled. following is the code that i have written, will anyone of you be able to find why it does not get write to the database table
$link = DbConnection::getInstance('TDC')->connectMysql()
$attributeKey = "12345";
$query_new = "INSERT INTO redtable (message) VALUES ('$attributeKey')";
$result = mysql_query($query_new, $link);

mysql server has gone away in result of storing API response in php

i am experiencing mysql server has gone away in response of storing API result in mysql database through php code is follow,
$api_response = sendmsg($group_detail['cell_no'], $SMS); //function to execute API
//update sms sent record
$sql = "INSERT INTO sms_sent_record (record_id, api_response)
VALUES (NULL, '$api_response')";
$result = mysql_query($sql) or die('Error, updating sms & group count
in sms_sent_count failed : ' . mysql_error());
i have tried many other options such as storing api response in array and then store it in mysql table, but in any way it throws the same error. The other code in function after this error will not executed by server.
i think it is due to delay in api response and timeout problem in mysql.
Is there any way to avoid this error and storing result in proper way.
Does it work if you omit the sendmsg and do:
$api_response = 'test';//sendmsg($group_detail['cell_no'], $SMS); //function to execute API
If so, does sendmsg() use some sort of mysql connection at any time?
If it does, you may want to store the link from when you connected to the database the first time and reuse it.
$link=mysql_connect();
..
..
mysql_query($sql,$link);
There are lots of reasons for the gone away message but I suspect your problem is that you open the connection to your DB before the API call (to send an SMS ?) and the API call causes the server to terminal your connection before the INSERT is run
Try moving your open db connection to just before the INSERT statement :
$api_response = sendmsg($group_detail['cell_no'], $SMS); //function to execute API
// open connection here
$sql = "INSERT INTO sms_sent_record (record_id, api_response)
VALUES (NULL, '$api_response')";
$result = mysql_query($sql) or die('Error, updating sms & group count
in sms_sent_count failed : ' . mysql_error());
Check your value set for wait_timeout this is
The number of seconds the server waits for activity on a
noninteractive connection before closing it.
If you have this value set very low the server will timeout your connection between opening your connection and running your query.

Categories