Python mysqldb data - php

I have a php form which saves these values to the database:
id
rand (a randomly generated string)
x_val
y_val
I am calling these values back from database in a python program using mysqldb:
import MySQLdb
db = MySQLdb.connect("localhost","root","","test" )
cursor = db.cursor()
sql = "SELECT id,rand,x_val,y_val FROM table"
try:
cursor.execute(sql)
results = cursor.fetchall()
results = {}
for row in results:
results[row[1]] = [row[0], row[2], row[3]]
rand = row[1]
x_val = row[2]
y_val = row[3]
except:
print "Error: unable to fecth data"
db.close()
UPDATE: It gives the Error -> Error: unable to fecth data
In this piece (as you can see) i want rand (i.e. row[1]) to serve as the identifier for the row. However, I am not able to find a way about how to use this as an identifier since rand = row[1] is called after the sql variable. In this example, I have used a static '63kfjf' rand value, which is just to show you the working. Is there a way?

After selecting your datas from DB, you can create a dictionnary with "rand" value as key:
Something like this:
dicResults = {}
for row in results:
dicResults[row[1]] = [row[0], row[2], row[3]]

I think you're trying to randomly select a row? If that is correct, this will work.
Change rand to an auto incrementing integer.
SELECT MAX(rand) FROM table; to determine the highest 'random'
value.
Generate a random value between 0 and MAX(rand)
SELECT * FROM table WHERE rand = $randomGeneratedValue;

Related

PHP calculation returns NAN

I'm trying to perform some calculation on Data retrieved from database ,
but evertime I run this code I get NAN as output.
function calculateNPS()
{
$queryTotal = "SELECT count(*) as total FROM message";
$resullTotal = mysqli_query($link ,$queryTotal);
$queryYes= "SELECT count(visit) as yes FROM message WHERE visit='Yes'";
$resultYes = mysqli_query($link ,$queryYes);
$queryNo = "SELECT *count(visit) as no FROM message WHERE visit='No'";
$resultNo = mysqli_query($link ,$queryNo);
$yescount = mysqli_fetch_assoc($resultTotal);
$nocount=mysqli_fetch_assoc($resultNo);
$totalcount=mysqli_fetch_assoc($resultYes);
$nps = ((float)($yescount['yes'])/(float)($totalcount['total'])*100)-((float)($nocount['no'])/(float)($totalcount['total'])*100);
echo $nps;
}
I hope thats just a test-script, because there are a lot of issues you could fall into ;-)
but your problem: i guess its just a typing-mistake. you name the result-var "resullTotal", below you are requesting another var called "resultTotal" ;-)
Some numeric operations can result in a value represented by the constant NAN. This result represents an undefined or unrepresentable value in floating-point calculations. So it seems you have some problems with the values in the $nps calculation.
I would suggest that you try outputting/inspecting all the params, like $yescount or $yescount['yes'] to make sure you have valid data to start with. Then break your expression into shorter operations until you find the issue.
For instance, mysqli_fetch_assoc returns an associative array that corresponds to the fetched row or NULL if there are no more rows.
Also, in your queries you use $link but I can't see where it's coming from.

PHP wpdb get_var query returning zero

I have the following code, which is adding some data to a database via server side API. The field order_number should be created via $OrderNumberNext, which is calculated by a count(*)+1 as order_num variable.
However, checking the database after this is done shows that this only ever calculates as 0 (zero). Should I be using a different function call for this?
function addChartToSet($chartId, $setId){
$chartWithId = $this->db->get_var($this->db->prepare("select id from chords where chord_id=%s",$chartId));
$setWithId = $this->db->get_var($this->db->prepare("select id from sets where set_id=%s",$setId));
$orderNumberNext = $this->db->get_var($this->db->prepare("select count(*)+1 as `order_num` from `chords_inside_sets` where `set_id`=%s",$setId));
$this->db->query($this->db->prepare("update sets set `last_updated_time`=NOW() where `set_id`=%s",$setId));
$this->db->query($this->db->prepare("insert into `chords_inside_sets` set `chord_id`=%s , `set_id`=%s, `order_number`= %s",$chartWithId,$setWithId,$orderNumberNext));
return array("last_updated_time"=> $this->getMaxUpdatedTimeForSet($setId), "query"=> $this->db->last_query);
}
You are adding 1 inside the query that fetches the data. It cannot work. Get your count first through the SELECT query, then add one on the next line, like this:
$orderNumberNext = $this->db->get_var($this->db->prepare("select count(*) as `order_num` from `chords_inside_sets` where `set_id`=%s",$setId));
$orderNumberNext++;

PHP function issues with array

I have a postgres table with four columns labelled dstart which is date data type,
dend which is also a date data type, dcontract which is a date data type and id which is a integer. I am trying to run a php code to get the data using an array and use it in the body of my application. But when I test the array and try to echo some values... My browser just displays the word array... Is there anyway I can be able to retrieve the data or fix this code? Please see code below
<?php
function getLiveDate($campid)
{
global $conn,$agencies;
$return=array(
'livedate'=>'',
'campid'=>'',
'enddate'=>'',
'dateContract'=>'',
);
$sql = "SELECT id, dcontract, dstart, dend
FROM campaigns
WHERE id = '".$campid."' ORDER BY dstart DESC LIMIT 1";
$r = pg_query($conn,$sql);
if ($r)
{
$d = pg_fetch_array($r);
if (!empty($d))
{
$return['livedate'] = $d['dstart'];
$return['campid'] = $d['id'];
$return['enddate'] = $d['dend'];
$return['dateContract'] = $d['dcontract'];
}
}
#pg_free_result($r);
return $return;
}
I am pretty sure, your array $d is "multi-dimensional" and pg_fetch_array() returns an array of arrays, because the result of SQL queries in general may contain multiple rows. You limited it to one row, but you certainly get the correct values by assinging $return['livedata'] = $d[0]['dstart']; or $return['livedata'] = $d['dstart'][0]; and so on (I am not familiar with that particularly function for I usually use MySQL instead of Postgre).
Besides, try echoing your data by means of print_r() instead of echo.
The $return variable is an array, if you want shows the content, you must use print_r or var_dump not echo.

MySQL SELECT query works in PHPmyadmin, not in PHP

So, Im having a lot of trouble with executing a query in PHP. It executes well in phpmyadmin and gives me a neat list of results.
Here is the query I inserted into phpmyadmin:
SELECT RIGHT(`Pair`, LOCATE('_', REVERSE(`Pair`))-1)
FROM `poloniex`
WHERE LEFT(`Pair`, 3) = 'BTC';
For example an entry in the Column Pair: BTC_NXT
The query should return NXT (everything right of the "_").
Now, when switching over to php while I haven't edited the query at all, I don't get any result.
The dbconnection is already established; no problems on that front.
$query_get_pairs = "SELECT RIGHT(`Pair`,LOCATE('_',REVERSE(`Pair`))-1) FROM `poloniex` WHERE LEFT(`Pair`, 3) = 'BTC'";
$result_get_pairs = mysqli_query($dbc,$query_get_pairs);
var_dump($result_get_pairs) returns an empty array.
Summary:
poloniex is the table name.
Pair is the column name which
contains values like "BTC_NXT". The query should give me NXT.
You are not fetching anything, your code should be like:
$query_get_pairs = "SELECT RIGHT(Pair,LOCATE('_',REVERSE(Pair))-1) FROM poloniex WHERE LEFT(Pair, 3) = 'BTC'";
$result_get_pairs = mysqli_query($query_get_pairs);
$myResult = mysqli_fetch_assoc($result_get_pairs);
var_dump($myResult);

mysql_insert_id() returns 0

I know there are a lot of topics with the same title. But mostly it's the query that's been inserted in the wrong place. But I think I placed it right.
So the problem is, that I still get 0 even when the data is inserted in the db.
Does someone knows an answer where I could be wrong?
here's my code:
mysql_query('SET NAMES utf8');
$this->arr_kolommen = $arr_kolommen;
$this->arr_waardes = $arr_waardes;
$this->tabel = $tabel;
$aantal = count($this->arr_kolommen);
//$sql="INSERT INTO `tbl_photo_lijst_zoekcriteria` ( `PLZ_FOTO` , `PLZ_ZOEKCRITERIA`,`PLZ_CATEGORIE`)VALUES ('$foto', '$zoekje','$afdeling');";
$insert = "INSERT INTO ".$this->tabel." ";
$kolommen = "(";
$waardes = " VALUES(";
for($i=0;$i<$aantal;$i++)
{
$kolommen .=$this->arr_kolommen[$i].",";
$waardes .="'".$this->arr_waardes[$i]."',";
}
$kolommen = substr($kolommen,0,-1).")";
$waardes = substr($waardes,0,-1).")";
$insert .=$kolommen.$waardes;
$result = mysql_query($insert,$this->db) or die ($this->sendErrorToMail(str_replace(" ","",str_replace("\r\n","\n",$insert))."\n\n".str_replace(" ","",str_replace("\r\n","\n",mysql_error()))));
$waarde = mysql_insert_id();
Thanks a lot in advance, because I have been breaking my head for this one for almost already a whole day. (and probably it's something small and stupid)
According to the manual mysql_insert_id returns:
The ID generated for an AUTO_INCREMENT column by the previous query on
success, 0 if the previous query does not generate an AUTO_INCREMENT
value, or FALSE if no MySQL connection was established.
Since it does not give you false and not the correct number it indicates that the queried table didn't generate an auto-increment value.
There are two possibilities I can think of:
Your table doesn't have an auto_increment field
Since you doesn't provide the link to the mysql_insert_id() but using a link with mysql_query() it might not be the correct table that's queried when retrieving the last inserted id.
Solution:
Make sure it has an auto_increment field
Provide the link aswell: $waarde = mysql_insert_id($this->db);
It is possible that your INSERT query was not successful - e.g., maybe you were trying to insert duplicate data on a column whose data must be unique?
If the id is indeed set to auto increment and still get '0' as your response do a column and value count i experienced this only later on I noticed a number of my column count did not match values count.
Codeigniter has an odd behaviourd when calling mysql_insert_id(). The function returns 0 after the first call. So calling it twice will return 0.
Use a variable instead of calling the function more times:
$id = mysql_insert_id();

Categories