mysql real escape on array that contains objects? - php

I have an array that I need to sanitize before putting it in a cell on a mysql database. The code i'm trying seems to work. But as soon as there are characters like ' it throws errors and thats not good. Here's what i've tried, any ideas whats wrong?
function submitLogDb($array,$id,$title)
{
function mysql_real_escape_array($var)
{
foreach($var as $line)
{
mysql_real_escape_string($line['msg']);
}
return $var;
}
$title=mysql_real_escape_string($title);
$array=mysql_real_escape_array($array);
return mysql_query("INSERT INTO logs (text,id,title) VALUES ('".serialize($array)."','$id','$title')");
}
EDIT:
Just incase it helps, heres what some of the objects might look like in the array:
[1]
icon = ""
msg = "this is a test"
name = "Them: "
systemMsg = 0
[2]
icon = ""
msg = "yep it sure is"
name = "You: "
systemMsg = 0

mysql_real_escape_string the output of serialization of the array.
$data_to_insert = mysql_real_escape_string(serialize($array));

Related

How to use string variable that have special character "#" in select query statement mysql php

<?php
include('dbLink2.php');
$quizqr = $_GET['quizQR'];
$recordsID1 = $_GET['recordsID1'];
$recordsID2 = $_GET['recordsID2'];
$m_array1=array();
$m_array=array();
$sql = "SELECT quizQR, recordsID FROM `registertestactivity` WHERE (quizQR = '$quizqr' OR recordsID = '$recordsID1' OR recordsID = '$recordsID2') LIMIT 1";
$result = #mysqli_query($link, $sql) or die();
if (#mysqli_affected_rows($link) > 0) {
while($row = #mysqli_fetch_assoc($result))
{
$m_array[]=$row;
}
} else {
$m_array1 += ["quizQR" => "NoRecords"];
$m_array1 += ["recordsID" => "NoRecords"];
$m_array[0] = $m_array1;
}
echo json_encode($m_array);
#mysqli_free_result($result);
#mysqli_close($link);
?>
Can someone help me out, i have tried the mysqli_real_escape_string and it still doesnt work :(
The $quizqr value has a '#' character in the string and this is the error msg that pops when the ajax call this php:
Because you have a # in the URL you're dealing with a URL Fragment which means that everything past the # is not available in the query string. PHP offers a flag, PHP_URL_FRAGMENT for its parse_url() function which can help you get what you need from the string.
Here is one example using the URL you provided:
$fragment = parse_url($url, PHP_URL_FRAGMENT);
echo $fragment;
$fragmentSection = explode('&', $fragment);
print_r($fragmentSection);
foreach($fragmentSection AS $section) {
if(0 != strpos($section, '=')) {
$sectionParts = explode('=', $section);
$queryParts[$sectionParts[0]] = $sectionParts[1];
}
}
print_r($queryParts);
This ultimately returns two array members which could then be used in your query:
Array
(
[recordsID1] => records_001
[recordsID2] => records_002
)
The best thing to do would be to write a function to which you pass the URL to return the elements you need.
Keep in mind that this is not fool-proof. If the URL is in a different format then what I have done here will have to be modified to work as you would like it to.
Additionally you have been given some warnings and guidance in the comments you should follow to keep your code safe and efficient, so I will not repeat them here.

PHP NSUpdate Update of an TXT String

iam using NSUpdate to update DNS Records from PHP
all things working, but somthing going wrong when i want update/Add TXT Record
adding an Text Record is not so hard like SRV OF SPF
nope :) rlly
The Problem:
trying to add somthing like "This IS an TXT record"
after sending it from PHP to NSUPDATE (works with other Records)
Bind DNS Server get this :
Domain IN TXT "This" "IS" "an" "TXT" "Record"
but this is wrong ! inspected my code, looked arround..it dosent work ..
code :
<?php
if ($txt_true) {
$ttl2 = '36';
// TXT string could be almost anything, just make sure it's quoted.
// $txt_var = str_replace("'", "", $txt_var);
// $txt_var = str_replace('"', "", $txt_var);
//$txt_var = '"'. $txt_var.'"';
$data .= "update add ".$sub.".".$domain.". ".$ttl2." IN TXT ".$txt_var."\n";
}
this going to NSupdate ( data + nsupdate etc...) dotn follow block that is out commented
here:
function dns_update ($id_domain,$mydata) {
global $nsupdate;
if (domain_exists($id_domain)) {
$infos = domain_infos($id_domain);
$domain = $infos['domain'];
$dnsip = $infos['dnsip'];
$key = $infos['key'];
if ($key != '') { $add = ' -y '.$key; }
$data = "server $dnsip\n";
$data .= "zone $domain\n";
$data .= $mydata;
$data .= "\n";
$result = `echo "$data" | $nsupdate$add`;
return $result;
} else {
return false;
}
}
and Quote TXT Record happens from
HTML => INPUT => DO => Wirte DB & Function => NSUPDATE
You need quotes around the text data. If it contains any embedded quotes, they need to be escaped:
$txt_var = str_replace('"', '\"', $txt_var);
$data .= "update add $sub.$domain. $ttl2 IN TXT \"$txt_var\"\n";
Since this string contains double quotes, you should use single quotes in your echo statement:
$result = `echo '$data' | $nsupdate$add`;
However, a much better idea would be to use an API rather than doing this through the command line. See the Net_DNS2 library.

conditional arrays

I'm trying to code an array that displays a certain set of products depending on the gender of the logged in user. The arrays not really the problem but the parts where I'm going to have to check the database then create the conditional statement from the results is the main problem i think.
Here is my code:
<?php
include"config.php" or die "cannot connect to server";
$gender=$_POST['gender'];
$qry ="SELECT * FROM server WHERE gender ='$gender'";
$result = mysql_query($qry);
$productdetails;
$productdetails1["Product1"] = "£8";
$productdetails1["Product2"] = "£6";
$productdetails1["Product3"] = "£5";
$productdetails1["Product4"] = "£6";
$productdetails1["Product5"] = "£4";
$productdetails2["Product6"] = "£8";
$productdetails2["Product7"] = "£6";
$productdetails2["Product8"] = "£5";
$productdetails2["Product9"] = "£6";
$productdetails2["Product10"] = "£4";
if (mysql_num_rows($result) = 1) {
foreach( $productdetails1 as $key => $value){
echo "Product: $key, Price: $value <br />";
}
}
else {
foreach( $productdetails2 as $key => $value) {
echo "Product: $key, Price: $value <br />";
}
}
?>
You if statement is wrong. = is an assignment operator, you should use a comparison operator like == or ===
What happens with the current code?
Some tips:
First try echoing $gender, to make sure it is getting through. It is submitted through post, what happens if nothing is being posted? Where is this coming from? You should try to use get instead. This seems like something you'd give someone a link to therefore post doesn't make sense here. You could always have both, and just get post if it exists otherwise use get otherwise default to 'male' or 'female' depending on your audience.
Next, what is your query outputting? It might be empty at this point if gender is not giving anything back. It seems like you are querying for all rows where gender = whatever was passed, but then your if statement is asking was there anything returned? Then all you are doing is going to the arrays, but you shouldn't be doing that you should be outputting what you got from the DB. Assuming you do actually have products in the table called server you should do something like this:
$products = mysql_query("SELECT * FROM server WHERE gender ='$gender");
while($product = mysql_fetch_array($products)){
echo $product['name'] . " " . $product['price']. " " . $product['gender'];
echo "<br />";
}
On that note. You should really call your table something else, like product not just "server" unless by server you mean a table filled with instances of waiters or computer hardware.

php mysqli object search and sort

Using php 5.3 and mysqli I return a result set from a query that just has usernames, something like
$query_username = "SELECT username FROM some_table WHERE param = 1";
$username = $mysqliObject->query($query_username);
while($row_username = $username->fetch_object()){
print "<br>Username: $row_username->username";
}
All fine, but here is my problem, there are repeated usernames, and I don't know which names are going to be in the query before hand, could be bob, sue, james. Or it could be tom, dick, harry, tom. What I need to do is print out each username and how many times it shows up in this object. For very strange reasons I CANNOT use neat stuff like group by and count(*) in the query(don't ask it is truly weird). So my question is, what is the fastest way to loop through the returned object(or associative array if need be) to get each unique name and how many times it appears. Thanks for your help and I apologize if this is a freshman CS question, I'm self taught and always filling in the gaps!
If you really must do it on the PHP side instead of using a GROUP BY clause:
while($row_username = $username->fetch_object())
{
if(isset($usernames[$row_username['username']]))
{
$usernames[$row_username['username']]++;
}
else
{
$usernames[$row_username['username']] = 1;
}
}
asort($usernames);
// use ksort() to sort by username instead of the count
// print out the usernames
foreach($usernames as $username => $count)
{
echo $username . ", count: " . $count;
}
e.g.
$users = array();
while( false!==($row=$result->fetch_array()) ){
if ( isset($users[$row['username']]) ) {
$users[$row['username']] += 1;
}
else {
$users[$row['username']] = 1;
}
}
asort($users);

Combine data from array into one variable

I'm trying to combine several results from an array into one variable.
$sqlNameForCode = "Select dim_InvoiceRef from dimensions"." Where dim_FileRef = '".$addRow[$FieldName]."'";
$qryNameForCode = mysql_Query($sqlNameForCode);
While($arrNameForCode = mysql_fetch_array($qryNameForCode)) {
$addRow[$FieldName] = $arrNameForCode['dim_InvoiceRef'];
}
I need the variable $addRow[$FieldName] to contain all the fields taken from the array. However because it's within the While loop only the last field is ever left in the variable.
Example, the query pulls the following results
Apple
Banana
Orange
I need echo $addRow[$FieldName] to show Apple Banana Orange, at the moment it just equals Orange.
Any help would be great thanks!
You need to make it into an array
While($arrNameForCode = mysql_fetch_array($qryNameForCode)) {
$addRow[$FieldName][] = $arrNameForCode['dim_InvoiceRef']; //notice the extra braces
}
echo implode(' ', $addRow[$FieldName]); //prints the values in the array separated by a space
Or directly assign it to a string
$addRow[$FieldName] = "";//defaults
While($arrNameForCode = mysql_fetch_array($qryNameForCode)) {
$addRow[$FieldName] .= $arrNameForCode['dim_InvoiceRef']; //string concatenation
}
echo $addRow[$FieldName];
Here's a MySQL-based solution that you might find easier:
$sql = "SELECT GROUP_CONCAT(dim_InvoiceRef SEPARATOR ' ') FROM dimensions WHERE dim_FileRef = '".$field."'";
$query = mysql_query($sql);
$result = mysql_fetch_row($query);
echo $result[0]; // Should show 'Apple Orange Banana' etc.
I took the liberty of renaming some variables in your example to make it easier to understand. Unless you need to do different things with the same data later on in the program, this should work.

Categories