mysql_field_name to the new mysqli - php

I have a way to get the name of the columns of a table. It works fine but now I want to update to the new mysqli ? (I tried the mysqli_fetch_field but I don't know how to apply to this case and I am not sure if it is the wright option)
How to do the same with mysqli ? :
$sql = "SELECT * from myTable";
$result = mysql_query($sql,$con);
$id = mysql_field_name($result, 0);
$a = mysql_field_name($result, 1);
echo $id;
echo $a;

This is the way to implement this missing function:
function mysqli_field_name($result, $field_offset)
{
$properties = mysqli_fetch_field_direct($result, $field_offset);
return is_object($properties) ? $properties->name : null;
}

I'm not sure if there is a better way to do that, but I checked that this works to get just the name of the columns and is the new mysqli :
$result = mysqli_query($con, 'SELECT * FROM myTable');
while ($property = mysqli_fetch_field($result)) {
echo $property->name;
}

You can replace the function mysql_field_name to mysqli_fetch_field_directand use it like the following:
$colObj = mysqli_fetch_field_direct($result,$i);
$col = $colObj->name;
echo "<br/>Coluna: ".$col;

This is another easy way to print each field's name, table, and max length
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";
if ($result=mysqli_query($con,$sql))
{
// Get field information for all fields
while ($fieldinfo=mysqli_fetch_field($result))
{
printf("Name: %s\n",$fieldinfo->name);
printf("Table: %s\n",$fieldinfo->table);
printf("max. Len: %d\n",$fieldinfo->max_length);
}
// Free result set
mysqli_free_result($result);
}

$sql = "SELECT * FROM myTable LIMIT 10";
$ressult = $con->query($sql);
$rows = $result->fetch_all(MYSQLI_ASSOC);
$fields = array_keys($rows[0] ?? []);
echo json_encode($fields);
Can return empty array if query returned no rows.

Related

How to return more mysql rows in function?

I want to make a function in PHP to return a list of mysql results. But i want to enter my own tekst also.
When i echo i get the results but i want to return the value.
function Get() {
$sql = mysqli_query($link, "SELECT * FROM blabla");
$value4 = 'certain';
while($approw = mysqli_fetch_array($sql)){
$value= 'Fun '. $approw['value1'].' '.$approw['value2'].' '.$approw['value3'].'percent '.$value4.'<br />' ;
}
return $value.' Powered by Hisenseb';
}
?>
In the while the results can change anytime
How can i do this? Can anyone tell me how? Thanks in advance.
Pass a mysqli::connect() object to the Get() function as an argument, and for example, select a array as the return value where you store the result set from the sql query and the text you want. Try it:
function Get(mysqli $connect)
{
$ret = [];
$value4 = 'certain';
if ($res = $connect->query("SELECT * FROM blabla")) {
$row = $res->fetch_all(MYSQLI_ASSOC);
$ret['mytext'] = 'Fun '. $row['value1'].' '.$row['value2'].' '.$row['value3'].'percent '.$value4.'<br />' ;
$ret['result-set'] = $row;
}
$connect->close();
return count($ret) > 0 ? $ret : false;
}
Now just call the function:
$conn = new mysqli("localhost","user","password","database");
$result = Get($conn);
$sql = $result['result-set'];
$mytext = $result['mytext'];
// You can then get the data from the sql table using the column names of your table:
$column1 = $sql['column1']; //Now in $column1 you have the value from the SQL table from column column1.

fetch multiple rows of same id in different variable

I have two rows contaning data of same id.
It has different adresses in different rows for the same id.
I want to fetch both the adress in different variable in php.
How can i do this? Please help!
Below is the code:
foreach($row_address as $address)
{
echo "<br> Address :" .$address;
$info=Array();
$data=explode(' ', $address );
$info[1]=$data[0];
$info[2]=$data[1];
$info[3]=$data[2];
echo "City :".$info[1];
echo "Country :".$info[2];
echo "Pin Code :".$info[3];
}
function hoteladdresstable($id)
{
global $conn;
/*$sql2 = "select AddressLine from hoteladdress where Hotel_Id= " .$id;
$result2 = mysql_query($sql2,$conn);
$row2 = mysql_fetch_assoc($result2,MYSQL_NUM);
return $row2;*/
$query = "select AddressLine from hoteladdress where Hotel_Id = " .$id;
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result))
{
$d[] = $row['AddressLine'];
}
return $d;
}
It gives me both the address of the same id in one variable only.
I want them in two different variables.
You are already getting an array of addresses in $d.
What you can do is:
$d = array();
while ($row = mysql_fetch_assoc($result)) {
$d[$row['Address_ID']] = $row['AddressLine'];
}
extract($d, EXTR_PREFIX_ALL, 'ad');
If you have address ids 2 and 4, you will get two variables
$ad_2 and $ad_4
You should use parameterized queries. Use PHP's PDO:
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$STH = $DBH->prepare('select AddressLine from hoteladdress where Hotel_Id = :id');
$STH->bindParam(':name', $id);
$STH->execute();
$d = array();
while($row = $STH->fetch()) {
$d[] = $row['AddressLine'];
}
http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
Don't want your queries getting injected with attacks.
I suggest you to use mysqli instead.
$data = array();
while($row = mysqli_fetch_assoc($result)){
$data[] = $row;
}
return $data;
and then
foreach($data as $oneRow){
echo $oneRow['AddressLine']; //and all other stuff that you want.
}
you can verify it:
print_r($data);

How to select table user in yii2?

i have a trouble, when select table user in yii2 , data no show up
$sqlGetuser = "select * from user ";
$sqlquery = Yii::$app->db->createCommand($sqlGetuser)->query();
foreach($sqlquery as $row){
// echo $row;
// echo "saya";
echo $row['username'];
}
The error is in this line:
$sqlquery = Yii::$app->db->createCommand($sqlGetuser)->query();
query() returns yii\db\DataReader. To return array of rows use queryAll():
$rows = Yii::$app->db->createCommand($sqlGetuser)->queryAll();
If you want to use query(), you need to read data differently:
$command = $connection->createCommand('SELECT * FROM "user"');
$reader = $command->query();
while ($row = $reader->read()) {
$rows[] = $row;
}
// equivalent to:
foreach ($reader as $row) {
$rows[] = $row;
}
// equivalent to:
$rows = $reader->readAll();
See more in official docs.
Also quote table name as adviced since it's reserved word.

mysql select * or desired parameters in php function

I have a function which selects the * values from a particular table, I need to configure that if I pass * in parameter then it selects all or the selected parameters.
My function is as follows:
public function select($tablename){
$select = mysql_query("SELECT * FROM $tablename");
if(!$select){
echo "cant select table mane";
}
while ($row = mysql_fetch_array($select)){
print_r($row);
}
}
How can I pass the dynamic colum name in place of *
public function select($tablename,$column=NULL){
if($column == null) {
$select = mysql_query("SELECT * FROM $tablename");
} else {
$select = mysql_query("SELECT ".$column." FROM $tablename");
}
call it using select("abcd_table","id,name"); OR for all just select("abcd_table");
By Alex
Avoid mysql, it is deprecated. Use mysqli or PDO instead
That's even easier:
public function select( $tablename , $columnName = array() ){
$columnName = $columnName ? implode( ',' , $columnName ) : '*';
$select = mysql_query( 'SELECT ' . $columnName . ' FROM ' . $tableName );
if(!$select){
echo "cant select table mane";
}
while ($row = mysql_fetch_array($select)){
print_r($row);
}
}
Add one more parameter $columnname type array in your function.
public function select($tablename,$columnname = array()){
if(count($columnname)){
$columnname = implode(",",$columnname);
$select = mysql_query("SELECT {$columnname} FROM $tablename");
}
else{
$select = mysql_query("SELECT * FROM $tablename");
}
#code continue
}
Calling will be like below
To select all fields,
select($tablename);
To select some fields,
select($tablename,array('field','field2'));
Note: Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
public function select($tablename, $selectrow){
$select = mysql_query("SELECT $selectrow FROM $tablename");
if(!$select){
echo "cant select table mane";
}
while ($row = mysql_fetch_array($select)){
print_r($row);
}
}
try this modified function
public function select($tablename,$array_fields){
if(!empty($array_fields)){
$fieldstr = implode(',',$array_fields);
$fieldstr = trim($fieldstr,',');
}else{
$fieldstr = '*';
}
$select = mysql_query("SELECT $fieldstr FROM $tablename");
if(!$select){
echo "cant select table mane";
}
while ($row = mysql_fetch_array($select)){
print_r($row);
}
}
public function select($tablename,$column="*"){
$select = mysql_query("SELECT $column FROM $tablename");
if(!$select){
echo "cant select table mane";
}
while ($row = mysql_fetch_array($select)){
print_r($row);
}
}
call like select("table","*") or
call like select("table","col1,col2")

PHP: Making this grabbing from db easier/simpler way?

Is there any method i could do this easier:
$query = mysql_query("SELECT full_name FROM users WHERE id = '$show[uID]'");
$row = mysql_fetch_array($query);
echo $row["full_name"] . " ";
as i only need to grab the full_name, then i make a var for the fetch_array and so, is there any way to make this simpler and echo? There was something about list(), but im not sure..
Ignoring possible security breaches and the usefulness of a DAL (see #deceze's answer), I recommend the use of mysql_result() instead of mysql_fetch_assoc() (or *_array() or whatever):
$query = mysql_query("SELECT full_name FROM users WHERE id = '$show[uID]'");
$fullName = mysql_result($query, 0);
echo $fullName . " ";
Not easier per se but should be more in line with the intention of the query (fetch one field in one row).
The only way to abstract this any more and thereby make the actual call shorter is by using a DAL and/or ORM like Doctrine or Propel, which you should anyway.
May be not easier, but more securely:
$id = mysql_real_escape_string($show['uID']);
$query = mysql_query("SELECT `full_name` FROM `users` WHERE id = '".$id."'");
$row = mysql_fetch_array($query);
echo $row['full_name'];
Oh you can to make id with intval:
$id = intval($id);
This could make further DB-questions easier;
function mysql_fetch_scalar($res)
{
$arr = mysql_fetch_array($res);
return $arr[0];
}
$query = mysql_query("SELECT full_name FROM users WHERE id = '".intval($show[uID])."'");
$fullname = mysql_fetch_scalar($query);
echo $fullname . " ";
Sure.
Moreover, you should - to make a function out of these repetitive API functions calls.
Something as simple, as this
function dbgetvar($query){
$res = mysql_query($query);
if (!$res) {
trigger_error("dbget: ".mysql_error()." in ".$query);
return FALSE;
}
$row = mysql_fetch_row($res);
if (!$row) return "";
return $row[0];
}
have this function in your config file and use every time you want a value from database:
echo dbgetval("SELECT full_name FROM users WHERE id = '$show[uID]'");
(I hope you have $show[uID] escaped)
Of course there can be also 2 similar functions, to return a row or a rowset. Or just one but with additional parameter. Or you can combine them into class...
You can make it even escape variables for you:
function dbgetvar(){
$args = func_get_args();
$query = array_shift($args);
foreach ($args as $key => $val) {
$args[$key] = "'".mysql_real_escape_string($val)."'";
}
$query = vsprintf($query, $args);
if (!$query) return false;
$res = mysql_query($query);
if (!$res) {
trigger_error("dbget: ".mysql_error()." in ".$query);
return FALSE;
}
$row = mysql_fetch_row($res);
if (!$row) return "";
return $row[0];
}
echo dbgetvar("SELECT full_name FROM users WHERE id = %s",$show['uID']);
That's what you have to do. You could wrap that in a helper function if you're using it a fair bit, but then you'd probably want to cache the answer you get - I don't suppose the name changes all that often...
function echoName($user_id) {
$id = mysql_real_escape_string($user_id);
$query = mysql_query("SELECT full_name FROM users WHERE id = '$id'");
$row = mysql_fetch_array($query);
echo $row["full_name"] . " ";
}
// ...
echoName($show['uID']);

Categories