PHP & sqlsrv - create array from results, without knowing column names? - php

Using the below, I echo a JSON array of the results. But this requires that I identify the column names which I'd like to return from the SQL query:
$new_sql = "SELECT TOP 200 * FROM STracker ORDER BY [ID] DESC";
$check_statement = sqlsrv_query($conn, $new_sql);
$data = array();
while($row = sqlsrv_fetch_array($check_statement, SQLSRV_FETCH_ASSOC)) {
$data['data'][] = array(
'id' => $row['ID'],
's_reference' => $row['s_reference'],
'reference' => $row['reference'],
'customer_name' => $row['customer_name']
);
}
Is there any way to create that array information, but return all of the columns returned by the query dynamically? So by using SELECT * FROM, all of the column data is returned in the array but without me needing to write out all of these individually? (the below)
'id' => $row['ID'],
's_reference' => $row['s_reference'],
'reference' => $row['reference'],
'customer_name' => $row['customer_name']
Ok I forgot to add that I'd tried this:
$data['data'][] = array($row);
Which is clearly wrong, and after using the following, it works perfectly!
$data['data'][] = $row;

Related

Insert jQuery repeater row in PHP database

I have 1 row having 5 form fields. User can add/remove rows. Its repeatable row.
Now i want to store these fields into database with PDO php.
For normal values i am using this code but i am confused for repeater field.
$data = array(
'bill_no' => trim($_REQUEST['bill_no']),
'from_name' => trim($_REQUEST['from_name']),
'to_name' => trim($_REQUEST['to_name']),
'date' => trim($_REQUEST['date_bill']),
'mr_or_ms' => trim($_REQUEST['mr_or_ms']),
);
if($crud->InsertData("bill",$data)) {
header("Location: add-bill.php");
}
Insert Function:
public function InsertData($table,$fields) {
$field = array_keys($fields);
$single_field = implode(",", $field);
$val = implode("','", $fields);
try {
$query = $this->db->prepare("INSERT INTO ".$table."(".$single_field.") VALUES('".$val."')");
$query->execute();
return true;
} catch(PDOException $e) {
echo "unable to insert data";
}
}
Please help me to insert fields. Thanks
Change the names of your form fields, add [] to the end to get PHP arrays. For example change bill_no to bill_no[]. Something like this:
foreach($_REQUEST['bill_no'] as $row_number => $row_content){
$data = array(
'bill_no' => trim($_REQUEST['bill_no'][$row_number]),
'from_name' => trim($_REQUEST['from_name'][$row_number]),
'to_name' => trim($_REQUEST['to_name'][$row_number]),
'date' => trim($_REQUEST['date_bill'][$row_number]),
'mr_or_ms' => trim($_REQUEST['mr_or_ms'][$row_number]),
);
$crud->InsertData("bill",$data);
}
This assumes the browser is not mixing up the order of the fields, so maybe it's better to add unique names to the form fields when adding rows.
Also, there's no input data validation at all, please ensure you are escaping all data properly.
I did it with this method.
$total=count($_POST['description']);
for($i=0; $i<$total; $i++){
$data1 = array(
'bill_no' => trim($_POST['bill_no']),
'description' => trim($_POST['description'][$i]),
'nos' => trim($_POST['nos'][$i]),
'nos_day' => trim($_POST['nos_day'][$i]),
'pay' => trim($_POST['pay'][$i]),
'weekly_off' => trim($_POST['weekly'][$i]),
'hra' => trim($_POST['hra'][$i]),
'rs' => trim($_POST['rs'][$i]),
'ps' => trim($_POST['ps'][$i]),
);
$crud->InsertData("bill_details",$data1);
}

MySQL - number of bound variables does not match number of tokens

Can't figure out why this code isn't working:
$update_SQL = $db->prepare($SQL_update);
$update_SQL->execute([$SQL_values]);
And these are dumps of the two strings being inserted into those statements:
$SQL_update = UPDATE laptops SET asset_tag = :asset_tag WHERE id = :id
$SQL_values = 'asset_tag' => 5544, 'id' => 23
You missed : in your code:-
$update_SQL = $db->prepare($SQL_update);
$update_SQL->execute([':asset_tag' => 5544, ':id' => 23]);
So actually what you have to do is:-
$SQL_values =[':asset_tag' => 5544, ':id' => 23]; // create array like this
$update_SQL = $db->prepare($SQL_update);
$update_SQL->execute($SQL_values); // pass that array
Or
$SQL_values =['asset_tag' => 5544, 'id' => 23]; // create array like this
$update_SQL = $db->prepare($SQL_update);
$update_SQL->execute($SQL_values); // pass that array
Note:- execute won't accept a string, it must be an array.

PHP MySQL: decrypt a column value from a MySQL row that was encrypted upon insertion and parse to JSON

Everything is working, all I want is to decrypt the db column containing the credit card number from the database with the following example:
$decp = $crypt->decrypt($encp);
the row in question is:
'Number' => $row['cardNumber'],
the entire code is:
// get the cards
$jsonresult = $conn->query("SELECT nameOnCard, cardNumber, cardType, cardDate, ccvCode
FROM cy_user_credit_cards
WHERE accountNumber='$accountNumber'");
$creditCard = [];
while ($row = mysqli_fetch_assoc($jsonresult)) {
array_push($creditCard, [
'Name' => $row['nameOnCard'],
'Number' => $row['cardNumber'],
'Type' => $row['cardType'],
'Date' => $row['cardDate'],
'ccv' => $row['ccvCode']
]);
}
// Convert the Array to a JSON String and echo it
$ccJSON = json_encode($creditCard);
echo $ccJSON;
$conn->close();
I think you would want to do something like this:
// get the cards
$jsonresult = $conn->query("SELECT nameOnCard, cardNumber, cardType, cardDate, ccvCode
FROM cy_user_credit_cards
WHERE accountNumber='$accountNumber'");
$creditCard = [];
while ($row = mysqli_fetch_assoc($jsonresult)) {
array_push($creditCard, [
'Name' => $row['nameOnCard'],
'Number' => $crypt->decrypt($row['cardNumber']),
'Type' => $row['cardType'],
'Date' => $row['cardDate'],
'ccv' => $row['ccvCode']
]);
}
// Convert the Array to a JSON String and echo it
$ccJSON = json_encode($creditCard);
echo $ccJSON;
$conn->close();
Keep in mind, You really do not want to store all of these credit card details in your database if it is not absolutely necessary. I would urge you to look elsewhere to handle credit card payments.
You can decrypt the string upon pushing your data into the array like so:
array_push($creditCard, [
'Name' => $row['nameOnCard'],
'Number' => $crypt->decrypt($row['cardNumber']),
'Type' => $row['cardType'],
'Date' => $row['cardDate'],
'ccv' => $row['ccvCode']
]);

MySQL returns null values for certain rows

I am having a problem with MySQL and PHP. I'm trying to create something that gets values from a database, encode it in JSON and then print it. I have that down, but there's something that is keeping from one certain row in the database from displaying. It always returns NULL except for the id value I set. Here's my code, am I doing something wrong?
$srv = mysql_query("SELECT * FROM `players` WHERE `name` LIKE '%" . mysql_real_escape_string($_GET['q']) . "%'");
while ($record = mysql_fetch_array($srv)) {
$playerInfo = array('id' => $playerarray['id'], 'name' => $playerarray['name'], 'server' => $playerarray['server']);
echo(json_encode($playerInfo));
}
If you want to take a look at it, it's hosted here. The funny thing is, this page uses the exact same code, but doesn't return null. Any ideas?
Edit:
Here's what is in $playerInfo (when I use geekygamer14)
array (size=3)
'id' => null
'name' => null
'server' => null
It seems that whatever rows that have verified set to 1 (integer), it gives NULL.
You're using variable $record in your loop, though this doesn't show in your generated array. Instead you're using a variable named $playerarray. I assume the code should be:
while ($record = mysql_fetch_array($srv)) {
$playerInfo = array('id' => $record['id'], 'name' => $record['name'], 'server' => $record['server']);
echo(json_encode($playerInfo));
}
Note: Consider using an alternative to mysql-functions, for example mysqli. Mysql-functions are deprecated.
Change this
$srv = mysql_query("SELECT * FROM `players` WHERE `name` LIKE '%" . mysql_real_escape_string($_GET['q']) . "%'");
while ($record = mysql_fetch_array($srv)) {
$playerInfo = array('id' => $playerarray['id'], 'name' => $playerarray['name'], 'server' => $playerarray['server']);
echo(json_encode($playerInfo));
}
to this
$srv = mysql_query("SELECT * FROM `players` WHERE `name` LIKE '%" . mysql_real_escape_string($_GET['q']) . "%'");
while ($record = mysql_fetch_array($srv)) {
$playerInfo = array('id' => $record['id'], 'name' => $record['name'], 'server' => $record['server']);
echo(json_encode($playerInfo));
}
Your variables name $playerarray['id'] is wrong this is write $record['id']. Your data is in $record because of loop so you should use $record instead of $playerarray.

passing query fields n rows to array

I'm trying to fetch all rows to an array variable
array that i want is like this
$data1 = array('fields'=>array(
array(
'id' => 1,
'nama_file' => "sunset.jpg",
'judul' => "Sunset",
'isi' => "Matahari terbenam indah sekali",
),
array(
'id' => 2,
'nama_file' => "water_lilies.jpg",
'judul' => "Bunga Lilly",
'isi' => "Bunga lilly air sangat indah",
),)
And I've done this:
$q = $this->db->query('select id, nama_file, judul, isi from tfoto where dihapus ="T" ');
$data1=array('fields');
foreach($q->result() as $row) {
$data1['fields']=array('id'=>$row->id,'nama_file'=>$row->nama_file,'judul'=>$row->judul, 'isi'=>$row->isi);
}
test output:
<?php
foreach($fields as $field){
echo $field['nama_file'];
.
.
.
};?>
and I got Message: Illegal string offset 'nama_file';'judul'; etc.
I am a newbie to MySQL/PHP, so forgive me if this is a very basic question. I tried looking all over but I could not find an answer to it.
This line:
$data1['fields']=array('id'=>$row->id,'nama_file'=>$row->nama_file,'judul'=>$row->judul, 'isi'=>$row->isi);
Should be:
$data1['fields'][] = array('id'=>$row->id,'nama_file'=>$row->nama_file,'judul'=>$row->judul, 'isi'=>$row->isi);
Because you have to append new arrays to $data1 and not replacing it.

Categories