Error while accessing MySQL resultset - mysql

When I executed this code,
while($row = mysql_fetch_array($res))
there was an error of the following plan:
Warning: mysql_fetch_array() expects parameter 1 to be resource,
boolean given in String of treatment:while($row =
mysql_fetch_array($res))

$res should be an resource , for example
$res = mysql_query("SELECT * FROM table;");
after that only use mysql_fetch_array. Just for information
This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used.

Would be better to use mysqli_query instead of mysql_query. Read this answer and this PHP documentation about differences between them. So I advice you to use mysqli:
$result = mysqli_query($connection, 'SELECT id, name FROM some_table');
if($result){
while($row = mysqli_fetch_assoc($result)){
//extract values from row
$id = $row['id'];
$name = $row['name'];
}
}

Related

SQL to JSON converts my int to string

I have this in my PHP.
$sql="select * from defaulttime";
$result = mysqli_query($db, $sql);
while ($row = mysqli_fetch_array($result)){
$row_set[] = $row;
}
echo trim(json_encode($row_set));
In my SQL some columns are Integer. but in JSON it shows as String.
can someone please tell me what I am doing wrong?
when I run the PHP, I get the below results. (Note Hour and Minute should be Integers)
[{"name":"Test","Hour": "6" ,"Minute":"45"}],
I want it to show string as string and Int as Int.
{"name":"Test","Hour": 6 ,"Minute":45}
You have to use JSON_NUMERIC_CHECK option in order to get numerics value,
look here: https://lornajane.net/posts/2011/php-returning-numeric-values-in-json
echo trim(json_encode($row_set,JSON_NUMERIC_CHECK));
Thanks all,
I got it working by using this code:
$result = mysqli_query($db, $sql);
while ($row = mysqli_fetch_array($result)){
$row_set[] = $row;
}
$json=json_encode($row_set,JSON_NUMERIC_CHECK);
echo $json;

mysqli_affected_rows() always returns -1

In my development environment, all calls to mysqli_affected_rows($link) are unexpectedly returning -1, indicating an error of some sort.
The identical SQL executed from a SQL console works as expected.
To avoid people trying to understand the code, I have written rewritten this question with a very simple test script, as follows:
<?php
// $DB parameters deleted
$link = #mysqli_connect($DBHOSTNAME, $DBUSER, $DBPASSWORD, $DBNAME);
$query = 'UPDATE control SET message = 66476 WHERE controlid = "lastgood"';
$rs = mysqli_query($link, $query);
$nbr = mysqli_affected_rows($link);
echo $nbr;
?>
This script returns -1. Something in my environment is clobbering mysqli_affected_rows().
There is a bug documented at https://bugs.php.net/bug.php?id=67348 with mysqli_affected_rows when operating through a debugger.

mysql_num_rows() expects parameter 1 to be resource, boolean given in C:/db.php

//authentication process starts
$sel = "SELECT * FROM g_admin WHERE loginname='$ln' AND apassword='$pw'";
$res = executeQuery($sel);
echo "kiran ".$res;
if(totalRecords($res) == 0){
echo "Incorrect LoginName/password";
}else{
$rec = getAssoc($res);
$_SESSION['AdminId'] = $rec['Id'];
header("Location: Home.php");
}
//authentication process ends
}
function executeQuery($qry){
return mysql_query($qry) or die ('MySQL Not found // Could Not Connectquery.');
}
function totalRecords($res){
return mysql_num_rows($res) or die ('MySQL Not found // Could Not Connectres.');
}
function getAssoc($res){
return mysql_fetch_assoc($res) or die ('MySQL Not found // Could Not Connectres.');
}
In the above code $res returns 1. But totalRecords($res) thows mysql_num_rows() expects parameter 1 to be resource, boolean given in c:/db.php
newly added functions are in db.php
By using those functions we are executing the code.
executeQuery($qry) is working fine and returns result as 1.
next we are calling totalRecords($res), In this case it throws warning.
Possible Error:
$sel = "SELECT * FROM g_admin WHERE loginname=`'$ln'` AND apassword=`'$pw'`";
When using variables in your query, it should be like this...
$sel = "SELECT * FROM g_admin WHERE loginname='{$ln}' AND apassword='{$pw}'";
or
$sel = "SELECT * FROM g_admin WHERE loginname='".$ln."' AND apassword='".$pw."'";
By the way
Are you using MySql 5.5? because mysql_num_rows extension is deprecated already. better to use count(*) in your query instead or use PDO.

Executing two queries in one perl script

i'm a newbie on perl scripting and i found a problem while trying to execute two sqls, here you have the code, for sure not the best one.
use DBI;
use DBD::mysql;
use Socket;
use strict;
use warnings;
# CONFIG VARIABLES
my $platform = 'mysql';
my $database = 'database_name';
my $host = 'hostname';
my $port = '3306';
my $user ='user';
my $pw ='password';
# DATA SOURCE NAME
my $dsn = "dbi:mysql:$database:$host:3306";
# PERL DBI CONNECT
my $dbh = DBI->connect($dsn,$user,$pw,{RaiseError=>1,PrintError=>1}) or die "Could not connect to database: $DBI::errstr";
# READ THE LASTID OF THE DATABASE
my $queryID = "SELECT event.id from snorby.event order by event.id desc limit 1";
my $lastid = $dbh->selectrow_array($queryID);
#HIGH
while ( 1 == 1 )
{
my $query = "SELECT event.id, inet_ntoa(iphdr.ip_src) as 'src', tcp_sport, inet_ntoa(iphdr.ip_dst) as 'dst', tcp_dport, signature.sig_name, event.timestamp, unhex(data.data_payload) from snorby.event join snorby.signature on signature.sig_id = event.signature join snorby.iphdr on event.cid=iphdr.cid and event.sid=iphdr.sid join snorby.data on event.cid=data.cid and event.sid=data.sid join snorby.tcphdr on event.cid=tcphdr.cid and event.sid=tcphdr.sid where event.id > $lastid and signature.sig_priority = '1' order by event.id";
my $sth = $dbh->prepare($query);
$sth->execute() or die "SQL Error: $DBI::errstr\n";
# BIND TABLE COLUMNS TO VARIABLES
my($eventid,$src,$sport,$dst,$dport,$signature,$timestamp,$payload);
$sth->bind_columns(undef, \$eventid, \$src, \$sport, \$dst, \$dport, \$signature, \$timestamp, \$payload);
# LOOP THROUGH RESULTS
while($sth->fetch) {
my $src_temp = inet_aton($src);
my $dst_temp = inet_aton($dst);
print "IT WORKS!";
}
So, if i comment this part of the code
# READ THE LASTID OF THE DATABASE
my $queryID = "SELECT event.id from snorby.event order by event.id desc limit 1";
my $lastid = $dbh->selectrow_array($queryID);
Everything works fine, but when i try to execute first this one, script stops responding exactly on this line:
while($sth->fetch) {
I tried to debug the code, look for tutorials, read a lot of pages and cannot figure where is the problem :(
Regards.
**** UPDATE ********
I think i found the problem after some more debug but not the solution. On the second sql named $query i passed the variable $lastid that i get on the first sql, see:
my $query = "SELECT stuff from table join things where event.id > **$lastid** and blablabla
If i change the $lastid for, as an example, 13330506, everything works, so seems to be that there is an issue about how this variable is passed. The strange thing is that when i print the $query with $lastid inside the content of $lastid is correct, the number appears... strange, at least for me.
If you read the documentation http://search.cpan.org/dist/DBI/DBI.pm
you'll see there is no ->fetch function, but there are various fetch methods:
#row_ary = $sth->fetchrow_array;
$ary_ref = $sth->fetchrow_arrayref;
$hash_ref = $sth->fetchrow_hashref;
$ary_ref = $sth->fetchall_arrayref;
$ary_ref = $sth->fetchall_arrayref( $slice, $max_rows );
$hash_ref = $sth->fetchall_hashref( $key_field );
Each one returns a reference you should store in variable for later use, for example:
while ( #row = $sth->fetchrow_array ) { ... }
while (my $data = $sth->fetchrow_hashref) { ... }
Then, you can use #row or $data inside the loop to retrieve the data you need.

MySQL concatenation and Illegal mix of collations error

I keep getting an error using MySQL 5.5.27 when trying to concatenate some values. I've searched and seen a bunch of charset answers (which admittedly is a TAD over my head), but I've converted all my tables to Charset utf8-unicode-ci and still get the error.
Surely there is a way to concatenate these values, but I just don't know how. I'm an Oracle guy that is relatively new to MySQL.
Here is the SQL line:
concat(pl.last_name,'-',format(money,0))
I get:
#1270 - Illegal mix of collations (latin1_swedish_ci,IMPLICIT), (utf8_unicode_ci,COERCIBLE), (utf8_unicode_ci,COERCIBLE) for operation 'concat'
Any ideas?
If money is indeed a number inside a VARCHAR you could use cast.
Try this:
concat_ws(pl.last_name,'-',cast(money AS unsigned)); // This is with decimals.
concat(`pl.last_name,'-',substring_index(money,',',1)) // Without decimals. If you use . i.e. the American currency notation you can substitute , with an .
Edit
Your should first try: concat(pl.last_name,'-',format(money,0));
This a very basic php code you could use.
<?php
function selecting_data(){
$host = "host";
$user = "username";
$password = "password";
$database = "database";
$charset = "utf8";
$link = mysqli_connect($host, $user, $password, $database);
mysqli_set_charset($charset, $link);
IF (!$link) {
echo('Unable to connect to the database!');
} ELSE {
$query = "SELECT lastname, format(money,0) FROM mytable"; //Select query
$result = mysqli_query($link, $query);
while ($rows = mysqli_fetch_array($result, MYSQLI_BOTH)){
echo $rows['lastname']."<br>".$rows['money'] ;
}
}
mysqli_close($link);
}
?>
<html>
<head><title>title</title></head>
<body>
<?PHP echo selecting_data(); ?>
</body>
</html>