mysql_fetch_assoc equivalent for informix - php

I just started to work on informix.( I have been using mysql all my life)
how i substitute mysql_fetch_assoc for informix.
Lets say I want to display one item at a time.normally in mysql i would run a while loop like this:
while($row=mysql_fetch_assoc($sql))
{
echo $row['name'];
echo $row['number'];
}
How do i do that for informix?
$sql="select * employee";
$result=$dbh->dbRequest("$sql")

I would suggest using PDO with the informix driver. The manual has plenty of examples of executing and returning data from queries using PDO.
PDO Informix driver - http://php.net/manual/en/ref.pdo-informix.php
PDO prepare - http://www.php.net/manual/en/pdo.prepare.php
$db = new PDO('informix:DSN=db', '', '');
$query = $db->prepare('SELECT * FROM employee');
$query->execute();
while ($employee = $query->fetchObject()) {
echo $employee->name;
echo $employee->number;
}

This is a basic Perl DBI question, though there isn't a dbRequest method in the DBI, at least not AFAIK.
You should be using something like this, though I'm assuming you have $dbh->{RaiseError} = 1 or are otherwise going to add error checking to the code:
my $sql = "select * from employee";
my $sth = $dbh->prepare($sql);
$sth->execute;
my $hashref;
while ($hash_ref = $sth->fetchrow_hashref())
{
print "$hash_ref->{name}\n";
print "$hash_ref->{number}\n";
}
This is DBMS-neutral; if you're using Perl DBI with MySQL, Informix, Oracle, DB2, ... this is the way you'd write the code.
NB: I edited the tags to add Perl and DBI and MySQL (and dropped the SQL and syntax tags). If I've misinterpreted your question and you're using PHP instead of Perl, then you should have tagged the code with PHP in the first place (and should now retag it). There is no SQL issue worth mentioning here; it is all about how to use SQL in the (formally unidentified) host language.
There's a different answer if the question is PHP, using the PDO system.

Related

Get values from query and return as array

How could I return the values from this query as an array so that I can perform an action with the array?
$sql = mysql_query("SELECT username FROM `users`");
$row = mysql_fetch_array($sql);
How would I get the code to be like the following? Here, the user1 and user2 would be the usernames of the users selected from the above query.
$userarray = array("user1","user2");
Before I point out best practices, you need working code first. So I'll give you a simple solution first.
To run a query with the mysql extension the function is mysql_query, you can't pass the query text directly to mysql_fetch_array. Nextly mysql_fetch_array doesn't do what you think it does. mysql_fetch_array combines the functionality of mysql_fetch_row and mysql_fetch_assoc together by storing the key names of the resulting columns along with their numeric indexes. The mysql_fetch_array function does not return an array with all rows from your query. To get all rows from the query, you need to run mysql_fetch_array in a loop like so:
$sql = "SELECT username FROM `users`";
$result = mysql_query($sql);
if(!$result){echo mysql_error();exit;}
$rows=array();
while($row = mysql_fetch_array($result))
{
$rows[]=$row;
}
print_r($rows);
Nextly, do note that the mysql_* functions are deprecated because the mysql extension in PHP is no longer maintained. This doesn't mean MySQL databases are deprecated, it just means the database adapter called mysql in PHP is old and newer adapters are available that you should be using instead, such as mysqli and PDO.
Next point, it is bad practice to rely upon short tags as it can be disabled by php.ini settings, always use either <?php ... ?> or <?= ... ?> for easy echoing which isn't affected by short tags.
Please read up on some mysqli or PDO simple examples to get started with one or the other. The mysqli extension is specific for MySQL while PDO (PHP Data Objects) is designed as a generic adapter for working with several kinds of databases in a unified way. Make your pick and switch so you're no longer using the deprecated mysql_* functions.
You would need to use a foreach loop to do it:
$userarray = [];
foreach($row as $single)
{
array_push($userarray, $single['username']);
}
and if can, try to use this MySQLi Class, it's very simple to get what you want from the database.
$db = new MysqliDb ('host', 'username', 'password', 'databaseName');
$userarray = $db->getValue('users', 'username', null);

PHP connects but cannot query MYSQL database

I am querying a mysql database with php but cannot get it to work on my iMac. In particular, php is unable to connect to the mysql DB. It connects to mysql and selects the DB but then fails. See code below:
if (!mysql_connect($db_host, $db_user, $db_pwd)){
die("I cannot connect to database");
}
if (!mysql_select_db($database)){
die("I cannot select database");
}
$sql = "SELECT FROM ${table} ORDER BY $sql_orderBy";
$result = mysql_query($sql);
if (!$result) {
die("I cannot execute query to show fields from Table: {$table}. Query failed.");
}
For reference, I installed apache/mysql/php with macports. The same php code works on my laptop (same installations), and the query works when I invoke it from within mysql on both computers. All variables are declared. Something with the system config is my best guess, but I even went through a uninstall/install.
Any help would be appreciated!
Your issue is ${table} . This should be {$table} or better still, ".$table."
You also need to say what you are SELECTING:
So:
$sql = "SELECT * FROM ".$table." ORDER BY ".$sql_orderBy;
You can discover issues by using Mysql_error() at the end of the query, for example:
mysql_query($sqlString) or die("line: ".__LINE__.":".mysql_error());
this will output a clear error message regarding your SQL statement. This is not for production and public situations but for development.
Also:
MySQL is deprecated and is no longer supported by PHP or the wider community, it is VERY strongly recommended you take up MySQLi or PDO and use these methods as they are much stronger, less flawed and more efficient delivery of results. They will also be supported in future updates and developments whereas MySQL will not.

MySQL DB query compare to PHP variable

I am very new to PHP and only have a class from a year ago where I touched MySQL.
I am trying to add a check in some existing code to query a db table for a value, and if that value is = to 1, change a variable in the code. Seems simple enough but it's not working out. I am getting 0 results from my query, even though the query works as expected in Sequel Pro.
I am modeling my syntax after the existing query even though I don't fully understand the prepare and execute functions, because I don't want to create a new db connection to make it easier on myself. I'll give the snippets that matter, I think.
My question: Why is this not returning results, when it works fine in the database directly? The query should return 2 results, in the form of Integers, which I want to compare to another integer, $friend_uid.
$dbObj = new sdb("mysql:host=".DB_HOST.";dbname=".DB_NAME, DB_USERNAME, DB_PASSWORD);
$dbObj->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$newStatus = 'REQUEST_PENDING';
$botquery = "SELECT `KAP_USER_MAIN.UID` FROM `KAP_USER_MAIN` WHERE `KAP_USER_MAIN.IS_BOT` = 1";
$botstatement = $dbObj->prepare($botquery, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$botstatement->execute();
$posts[]= "sql error " . mysql_error();
if(!$botstatement){
$posts[] = "failed bot query: " . mysql_error();
}
$num_rows = mysql_num_rows($botstatement);
if ($num_rows == false) {
$num_rows = 0;
}
$posts[] = "$num_rows rows";
while($row = mysql_fetch_array($botstatement)) {
if($row[0]['UID'] == $friend_uid){
$newStatus = 'FRIENDS';
}
}
$statement->execute(array(':uid'=>$uid,':friend_uid'=>$friend_uid,':status'=>$newStatus));
Here is an example of a query from the existing code that works just fine, which I am modeling after:
$query = "SELECT kits.TOTAL_UNIT,kum.ENERGY,kum.NAME,kum.LEVEL FROM KAP_USER_MAIN kum,KNP_INVENTORY_TRANSACTION_SUMMARY kits WHERE kits.UID = :uid AND kits.INV_ID = '10004' and kum.UID = :uid";
$statement = $dbObj->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$statement->execute(array(':uid'=>$uid));
$res = $statement->fetchAll(PDO::FETCH_ASSOC);
$sender_name = $res[0]['NAME'];
DON'T MIX PDO AND MYSQL FUNCTIONS
Looking more closely at the code, it looks like you are mixing PDO and mysql functions.
That's not valid. Don't mix calls to the two separate interface libraries.
The mysql_fetch_array function cannot be used to fetch from a PDO statement. Use the appropriate PDO fetch functions/methods.
There are three separate and distinct MySQL interface libraries in PHP.
There's the older (and now deprecated) mysql interface, all the functions from that interface start with mysql_.
There's the improved mysqli interface. The procedural style functions all begin with mysqli_.
And thirdly, there's the more database independent PDO interface.
Do not mix calls of these three separate interface libraries, because mixing calls won't work.
It looks like you're getting a connection with PDO, preparing a statement with PDO... but you are calling the msyql_error, mysql_num_rows and mysql_fetch_array functions. Replace those calls to the mysql_ functions with the appropriate PDO functions.
DOT CHARACTER IN COLUMN NAME?
It's very strange to include a dot character in a column name. (It's not invalid to do that, but something like that wouldn't fly in our shop.)
SELECT `KAP_USER_MAIN.UID` FROM `KAP_USER_MAIN` WHERE `KAP_USER_MAIN.IS_BOT` = 1
^ ^
But I'm suspicious that the column names are actually UID and IS_BOT, and that what you intended was:
SELECT `KAP_USER_MAIN`.`UID` FROM `KAP_USER_MAIN` WHERE `KAP_USER_MAIN`.`IS_BOT` = 1
^ ^ ^ ^
Each identifier (the column name and the table name) can be escaped separately. The dot character between the table name and the column name should not be escaped, because that's part of the SQL text, not part of the identifier.
We typically use a short table alias in our queries, so a typical query would look like this:
SELECT m.UID FROM `KAP_USER_MAIN` m WHERE m.IS_BOT` = 1
Or, for a query equivalent to the original query (with the dot character as part of the column name), like this:
SELECT m.`KAP_USER_MAIN.UID` FROM `KAP_USER_MAIN` m WHERE m.`KAP_USER_MAIN.IS_BOT` = 1
(That's not invalid, to include a dot character in a column name, but it is an unusual pattern, one that we don't see very often. I think that's because that pattern leads to more potential problems than whatever problem it was intended to solve.)
If the query works the way it is in your code, then that dot character must be part of the column name.

mysql_real_escape_string and PDO no connection in mvc pattern

I have created my own mvc pattern based on the codeigniter framework style. My problem now is that i want to prevent from SQL injection, and for that purpose i would like to use mysql_real_escape_string(). But for when i use it, it keeps erroring since it apparently don't have a the "link/source" to the database?
I get the php error:
Warning: mysql_real_escape_string(): Can't connect to local MySQL
server through socket '/var/lib/mysql/mysql.sock' (2) in
/hsphere/local/home/../dev/simple_blog/models/users_model.php on line
8
Warning: mysql_real_escape_string(): A link to the server could not be
established in
/hsphere/local/home/../dev/simple_blog/models/users_model.php on line
8
I don't quite understand why though, since i can get stuff in and out of my DB but for some reason i can't protect it???
Here is my function giving the error
public function getUserByName($username){
$username = mysql_real_escape_string($username);
$sql = "SELECT * FROM ".$this->db_table." WHERE username='".$username."' LIMIT 1";
$q = $this->db->query($sql);
if($q->rowCount() > 0){
foreach($q->fetch() as $key => $row){
$data[$key] = $row;
}
return $data;
}
}
As you can see I use mysql_real_escape_string() at the top, and then later on, do query stuff. Anyone know why this don't work and if yes, how would i fix it?
NOTE: Im not a shark to PDO, and $this->db is the PDO class.
To use mysql_real_escape_string you'll need to connect to the database server first, using the MySQL Functions, which you probably don't have done.
You are mixing up two completely different PHP extensions: mysql and PDO!
Also, you don't need to escape strings, when using PDO prepared statements, that's done via PDO for you.
An example using PDO:
$userDataStmt = $this->database->prepare('SELECT * FROM ' . $this->db_table . ' WHERE username = :username LIMIT 1');
$userDataStmt->bindValue(':username', $username);
$userDataStmt->execute();
if(!$userDataStmt->rowCount() <= 0)
{
$result = $userDataStmt->fetchAll();
}
Don't do this. PDO will escape for you if you use prepared statements:
$stmt = $this->db->prepare("SELECT * FROM ".$this->db_table." WHERE username=:user LIMIT 1";
$stmt->bind(':user', $username);
$stmt->execute();
PDO uses (I believe) the mysqli library behind the scenes. mysql_escape_real_string uses the mysql library (note the lack of an i). Both libraries have completely independent connection pools, so unless you establish a throw-away link with mysql_connect(), you cannot use mysql_real_escape_string anyways, as it requires an active DB connection.
The PDO version is PDO::quote(). See http://php.net/manual/en/pdo.quote.php
So in your case it would be
$username = $this->db->quote($username);
However, most recommend using PDO prepared statements for avoiding SQL Injection in PDO. See
http://php.net/manual/en/pdo.prepared-statements.php

How do you connect/retrieve data from a MYSQL database using objects in PHP?

Generally I connect and retrieve data using the standard way (error checking removed for simplicity):
$db = mysql_select_db("dbname", mysql_connect("host","username","passord"));
$items = mysql_query("SELECT * FROM $db");
while($item = mysql_fetch_array($items)) {
my_function($item[rowname]);
}
Where my_function does some useful things witht that particular row.
What is the equivalent code using objects?
Since version 5.1, PHP is shipped with the PDO driver, which gives a class for prepared statements.
$dbh = new PDO("mysql:host=$hostname;dbname=$db", $username, $password); //connect to the database
//each :keyword represents a parameter or value to be bound later
$query= $dbh->prepare('SELECT * FROM users WHERE id = :id AND password = :pass');
# Variables are set here.
$query->bindParam(':id', $id); // this is a pass by reference
$query->bindValue(':pass', $pass); // this is a pass by value
$query->execute(); // query is run
// to get all the data at once
$res = $query->fetchall();
print_r($res);
see PDO driver at php.net
Note that this way (with prepared statements) will automatically escape all that needs to be and is one of the safest ways to execute mysql queries, as long as you use binbParam or bindValue.
There is also the mysqli extension to do a similar task, but I personally find PDO to be cleaner.
What going this whole way around and using all these steps gives you is possibly a better solution than anything else when it comes to PHP.
You can then use $query->fetchobject to retrieve your data as an object.
You can use the mysql_fetch_object()
http://is2.php.net/manual/en/function.mysql-fetch-object.php

Categories