Here I want to assign $part1 and $part2 value into Mysqli query. But what is the problem is $part2 value does not get into query. I could not be able to find what would be the wrong with my code.
$string = 'Enter a domain name' . "\r\n";
socket_write($client, $string, strlen($string)) or die("Could not write output\n");
$str = '';
while ($input = socket_read($client, 1024)) {
$str .= $input;
if (strpos($str, "\n") !== false) {
break 1;
}}
$part = explode(".", $str);
$part1 = $part[0];
$part2= $part[1];
$sql = "SELECT DomainCategory.Name "
. "FROM DomainName_Client, DomainNameType, DomainCategory, OrderDomain_Client "
. "WHERE DomainName_Client.Name='$part1' "
. "AND DomainNameType.Name='$part2' "
. "AND DomainName_Client.TypeID=DomainNameType.ID "
. "AND DomainCategory.ID=DomainName_Client.DomainCategoryID "
. "AND OrderDomain_Client.DomainNameID=DomainName_Client.ID";
$result = $mysqli->query($sql);
$row1 = $result->num_rows;
if ($row1 > 0) {
$row = $result->fetch_array(MYSQLI_NUM);
printf("%s\n", $row[0]);
} else {
echo 'This is not a Registered Domain';
}
Connect with PDO
try
{
$dbh = new PDO("pgsql:host=$host;port=5432;dbname=$db;user=$user;password=$pass");
echo "Connected";
}
catch (Exception $e)
{
echo "Unable to connect: " . $e->getMessage() ."";
}
Prepare your statment:
$sth = $dbh->prepare("SELECT DomainCategory.Name "
. "FROM DomainName_Client, DomainNameType, DomainCategory, OrderDomain_Client "
. "WHERE DomainName_Client.Name='?' "
. "AND DomainNameType.Name='?' "
. "AND DomainName_Client.TypeID=DomainNameType.ID "
. "AND DomainCategory.ID=DomainName_Client.DomainCategoryID "
. "AND OrderDomain_Client.DomainNameID=DomainName_Client.ID");
And Execute:
`enter code here`
$sth->execute(array($part1, $part2));
$red = $sth->fetchAll();
As suggested by Combinu, PDO is the better way to go. However, to go along with your idea, I would concatenate the content of the variables.
$sql = "SELECT DomainCategory.Name "
. "FROM DomainName_Client, DomainNameType, DomainCategory, OrderDomain_Client "
. "WHERE DomainName_Client.Name= ". $part1
. "AND DomainNameType.Name= " . $part2
. "AND DomainName_Client.TypeID=DomainNameType.ID "
. "AND DomainCategory.ID=DomainName_Client.DomainCategoryID "
. "AND OrderDomain_Client.DomainNameID=DomainName_Client.ID";
Use {$part2} and also check that $part2 has value after asignment
$sql = "SELECT DomainCategory.Name "
. "FROM DomainName_Client, DomainNameType, DomainCategory, OrderDomain_Client "
. "WHERE DomainName_Client.Name='{$part1}' "
. "AND DomainNameType.Name='{$part2}' "
. "AND DomainName_Client.TypeID=DomainNameType.ID "
. "AND DomainCategory.ID=DomainName_Client.DomainCategoryID "
. "AND OrderDomain_Client.DomainNameID=DomainName_Client.ID";
Use Join Query rather then simple select Query with where condition
`"SELECT DomainCategory.Name FROM DomainName_Client join DomainNameType on DomainNameType.ID = DomainName_Client.TypeID join DomainCategory on DomainCategory.ID=DomainName_Client.DomainCategoryID join OrderDomain_Client on OrderDomain_Client.DomainNameID=DomainName_Client.ID WHERE DomainName_Client.Name = '".$part1."' AND DomainNameType.Name = '".$part2."'";`
Related
I try to inject some optional SQL to prepared statement with the parameter $and:
public function loadInfoAndStatus($property_id, $property_item_type_id, $and, $returnArray = false)
{
if (!isset($property_id) || empty($property_id)
|| !isset($property_item_type_id) || empty($property_item_type_id)
|| !isset($and) || empty($and)) {
error_log(get_class() . " - " . __FUNCTION__ ." : required params not set or empty");
return false;
}
$sql = " SELECT pi.status, pi.info, pi.property_item_id "
. " FROM ". self::TABLE ." pi "
. " JOIN countries c ON c.country_id = pi.country_id "
. " WHERE pi.property_id = ? "
. " AND property_item_type_id = ? "
. $this->con->real_escape_string($and) // <--- here
. " ORDER BY pi.status "
. " DESC LIMIT 0,1";
$err = "";
if (!$stmt = $this->con->prepare($sql)) {
$err .= "Prepare failed: (" . $this->con->errno . ") " . $this->con->error;
}
...
But if I call the function e.g.
$row2 = Main::getModel("Property/Item")->loadInfoAndStatus(
$id
, $property_item_type_id
, " AND c.iso = 'DE' "
, true
);
Hint: $and can be one of:
" AND c.iso <> 'DE' AND c.european <> 1 "
" AND c.iso <> 'DE' AND c.european = 1 "
" AND c.iso = 'DE' "
Then I get "Prepare failed" but there is no error message.
Resulting SQL:
SELECT pi.status, pi.info, pi.property_item_id FROM property_item pi JOIN countries c ON c.country_id = pi.country_id WHERE pi.property_id = ? AND property_item_type_id = ? AND c.iso = \'DE\' ORDER BY pi.status DESC LIMIT 0,1
It works if I don't use real_escape_string
Do I have to create new functions for each new sql, or is there another way?
You have to list all possible variants in your function.
This is a toilsome task but you have to realize that's the only way.
public function loadInfoAndStatus($property_id, $property_item_type_id, $iso = null, $european = null, $returnArray = false)
{
if (empty($property_id) || empty($property_item_type_id)) {
error_log(get_class() . " - " . __FUNCTION__ ." : required params not set or empty");
return false;
}
$parameters = [$property_id, $property_item_type_id];
$sql = " SELECT pi.status, pi.info, pi.property_item_id "
. " FROM ". self::TABLE ." pi "
. " JOIN countries c ON c.country_id = pi.country_id "
. " WHERE pi.property_id = ? "
. " AND property_item_type_id = ? ";
if ($iso) {
$sql .= " AND c.iso <> ? ";
$parameters[] = $iso;
}
if ($european === true) {
$sql .= " AND c.european == 1 ";
} elseif ($european === false) {
$sql .= " AND c.european <> 1 ";
}
$sql .= " ORDER BY pi.status ";
$sql .= " DESC LIMIT 0,1";
$stmt = $this->con->prepare($sql);
$stmt->bind_param(str_repeat("s", count($parameters)), ...$parameters);
$stmt->execute();
I also removed some cargo cult code from your method, in case you are interested why
Do you really need to check for both isset() and empty() at the same time?
PHP error reporting
I solved the problem by using a whitelist method:
public function loadInfoAndStatus($property_id, $property_item_type_id, $and = "", $returnArray = false)
{
if (empty($property_id) || empty($property_item_type_id) || empty($and)) {
error_log(get_class() . " - " . __FUNCTION__ ." : required params not set or empty");
return false;
}
if (!$this->isSqlInWhitelist($and, array(
"AND c.iso = 'DE'"
,"AND c.iso <> 'DE' AND c.european = 1"
,"AND c.iso <> 'DE' AND c.european <> 1"
))) {
error_log(get_class() . " - " . __FUNCTION__ ." : sql is not in whitelist.");
return false;
}
$sql = " SELECT pi.status, pi.info, pi.property_item_id "
. " FROM ". self::TABLE ." pi "
. " JOIN countries c ON c.country_id = pi.country_id "
. " WHERE pi.property_id = ? "
. " AND property_item_type_id = ? "
. $and
. " ORDER BY pi.status "
. " DESC LIMIT 0,1";
$stmt = $this->con->prepare($sql);
...
...
protected function isSqlInWhitelist($sql, $whitelist)
{
if (!empty($sql)) {
if (!in_array(trim($sql), $whitelist)) { return false; }
}
return true;
}
I have a grid that loads fine until I try to apply a filter then i get the following error.
Fatal error: Uncaught Error: Call to a member function fetch_assoc() on bool in
// build the query.
$result = $conn->query($query) or die("SQL Error 1: " . mysqli_error());
$sql = "SELECT FOUND_ROWS() AS `found_rows`;";
$rows = $conn->query($sql);
$rows = mysqli_fetch_assoc($rows);
$total_rows = $rows['found_rows'];
$query = "SELECT SQL_CALC_FOUND_ROWS profile_pic_url, username, full_name, biography, edge_followed_by, edge_follow FROM owner ORDER BY edge_followed_by DESC LIMIT $start, $total_rows".$where." ";
}
}
$result = $conn->query($query) ;
$sql = "SELECT FOUND_ROWS() AS `found_rows`;";
$rows = $conn->query($sql);
$rows = mysqli_fetch_assoc($rows);
$total_rows = $rows['found_rows'];
$orders = null;
// get data and store in a json array
while($row = $result->fetch_assoc()) {
#kryptur - this is where $where is defined
// filter data.
if (isset($_GET['filterscount']))
{
$filterscount = $_GET['filterscount'];
if ($filterscount > 0)
{
$where = " WHERE (";
$tmpdatafield = "";
$tmpfilteroperator = "";
for ($i=0; $i < $filterscount; $i++)
{
// get the filter's value.
$filtervalue = $_GET["filtervalue" . $i];
// get the filter's condition.
$filtercondition = $_GET["filtercondition" . $i];
// get the filter's column.
$filterdatafield = $_GET["filterdatafield" . $i];
// get the filter's operator.
$filteroperator = $_GET["filteroperator" . $i];
if ($tmpdatafield == "")
{
$tmpdatafield = $filterdatafield;
}
else if ($tmpdatafield <> $filterdatafield)
{
$where .= ")AND(";
}
else if ($tmpdatafield == $filterdatafield)
{
if ($tmpfilteroperator == 0)
{
$where .= " AND ";
}
else $where .= " OR ";
}
// build the "WHERE" clause depending on the filter's condition, value and datafield.
switch($filtercondition)
{
case "CONTAINS":
$where .= " " . $filterdatafield . " LIKE '%" . $filtervalue ."%'";
break;
case "DOES_NOT_CONTAIN":
$where .= " " . $filterdatafield . " NOT LIKE '%" . $filtervalue ."%'";
break;
case "GREATER_THAN":
$where .= " " . $filterdatafield . " > '" . $filtervalue ."'";
break;
case "LESS_THAN":
$where .= " " . $filterdatafield . " < '" . $filtervalue ."'";
break;
case "GREATER_THAN_OR_EQUAL":
$where .= " " . $filterdatafield . " >= '" . $filtervalue ."'";
break;
case "LESS_THAN_OR_EQUAL":
$where .= " " . $filterdatafield . " <= '" . $filtervalue ."'";
break;
}
if ($i == $filterscount - 1)
{
$where .= ")";
}
$tmpfilteroperator = $filteroperator;
$tmpdatafield = $filterdatafield;
}
So What Im trying to do is have the user add a code to a form, and fill the form out, A to add to the table, D to delete, U to update... The delete isnt working, neither is the insert, is it my logic? also I want to print the table only once, and sometimes it does it twice... any advice?
$Code=$_POST["Code"];
if ($Code == "A")
{
$sql = "INSERT INTO movieDATA values ('$idno', '$Name', '$Genre', '$Starring', '$Year', '$BoxOffice')";
$result= mysqli_query($link,$sql) or die(mysqli_error($link));
$showresult = mysqli_query($link,"SELECT * from movieDATA") or die("Invalid query: " . mysqli_error($link));
while ($row = mysqli_fetch_array($showresult))
{
echo ("<br> ID = ". $row["IDNO"] . "<br> NAME = " . $row["Name"] . "<br>");
echo("Genre = " . $row["Genre"] . "<br> Starring = " . $row["Starring"] . "<br>");
echo("Year = " . $row["Year"] . "<br> Box Office = " . $row["BoxOffice"] . "<br>");
}
}
elseif ($Code == "D")
{
$sql = "DELETE FROM movieDATA WHERE IDNO = '$idno'";
$result= mysqli_query($link,$sql) or die(mysqli_error($link));
$showresult = mysqli_query($link,"SELECT * from movieDATA") or die("Invalid query: " . mysqli_error($link));
while ($row = mysqli_fetch_array($showresult))
{
echo ("<br> ID = ". $row["IDNO"] . "<br> NAME = " . $row["Name"] . "<br>");
echo("Genre = " . $row["Genre"] . "<br> Starring = " . $row["Starring"] . "<br>");
echo("Year = " . $row["Year"] . "<br> Box Office = " . $row["BoxOffice"] . "<br>");
}
}
elseif ($Code == "U")
{
$sql = "UPDATE movieDATA SET Name = '$Name', Genre = '$Genre', Starring = '$Starring', Year = '$Year', BoxOffice = '$BoxOffice' where IDNO = '$idno'";
$result= mysqli_query($link,$sql) or die(mysqli_error($link));
$showresult = mysqli_query($link,"SELECT * from movieDATA") or die("Invalid query: " . mysqli_error($link));
while ($row = mysqli_fetch_array($showresult))
{
echo ("<br> ID = ". $row["IDNO"] . "<br> NAME = " . $row["Name"] . "<br>");
echo("Genre = " . $row["Genre"] . "<br> Starring = " . $row["Starring"] . "<br>");
echo("Year = " . $row["Year"] . "<br> Box Office = " . $row["BoxOffice"] . "<br>");
}
}
?>
I am trying to make ONE dynamic function for count in mysql:
functions.php:
function countEntries($table, $where = '', $what = '')
{
if (!empty($where) && isset($what)) {
$q = "SELECT COUNT(*) FROM " . $table . " WHERE " . $where . " = '" . $what . "' LIMIT 1";
} else{
$q = "SELECT COUNT(*) FROM " . $table . " LIMIT 1";
}
$record = query($q);
$total = fetchrow($record);
return $total[0];
}
HTML Code:
<?php echo countEntries("news", "category", "1"); ?>
<?php echo countEntries("post", "type", "Sports"); ?>
But still got blank page without any error!!!
You can try this out.
function countEntries($table, $where = '', $what = '')
{
if (!empty($where) && isset($what)) {
$q = "SELECT COUNT(*) AS count FROM " . $table . " WHERE " . $where . " = '" . $what . "' LIMIT 1";
} else{
$q = "SELECT COUNT(*) AS count FROM " . $table . " LIMIT 1";
}
$record = query($q);
$total = fetchrow($record);
return $total['count'];
}
Here you give an alias to the count(*) and use that to access the returned result as $total['count'].
Hope it helps.
First things you forgot to close else past,second just add this line "ini_set("display_errors", 1);" at the top of your php.this will shows the error in your php.
Your code:
function countEntries($table, $where = '', $what = '')
{
if (!empty($where) && isset($what)) {
$q = "SELECT COUNT(*) FROM " . $table . " WHERE " . $where . " = '" . $what . "' LIMIT 1";
} else
$q = "SELECT COUNT(*) FROM " . $table . " LIMIT 1";
}
$record = query($q);
$total = fetchrow($record);
return $total[0];
}
my code:
function countEntries($table, $where = '', $what = '')
{
if (!empty($where) && isset($what)) {
$q = "SELECT COUNT(*) AS count FROM " . $table . " WHERE " . $where . " = '" . $what . "' LIMIT 1";
} else{
$q = "SELECT COUNT(*) AS count FROM " . $table . " LIMIT 1";
}
$record = query($q);
$total = fetchrow($record);
return $total['count'];
}
Thanks guys, Its working well now:
function countEntries($table, $where, $what)
{
if (!empty($where) && isset($what)) {
$q = "SELECT COUNT(*) FROM " . $table . " WHERE " . $where . " = '" . $what . "' LIMIT 1";
} else
$q = "SELECT COUNT(*) FROM " . $table . " LIMIT 1";
$record = mysql_query($q);
$total = mysql_fetch_array($record);
return $total[0];
}
echo countEntries('news', "type", "sport");
I am working on an update query where the values should only update when the value is not null or empty. Now it updates everything regardless the value. Please help me out with this one.
$query = "UPDATE bundels
SET batchkosten = CASE WHEN ". $_POST['batchkosten'] . " IS NOT NULL
THEN ". $_POST['batchkosten'] . "
ELSE batchkosten
END CASE,
CASE WHEN ". $_POST['maandelijkse_kosten'] . " IS NOT NULL
THEN ". $_POST['maandelijkse_kosten'] . "
ELSE maandelijkse_kosten
END CASE,
CASE WHEN ". $_POST['aanmeldkosten'] . " IS NOT NULL
THEN ". $_POST['aanmeldkosten'] . "
ELSE aanmeldkosten
END CASE,
CASE WHEN ". $_POST['transactiekosten'] . " IS NOT NULL
THEN ". $_POST['transactiekosten'] . "
ELSE transactiekosten
END CASE,
CASE WHEN ". $_POST['referral'] . " IS NOT NULL
THEN ". $_POST['referral'] . "
ELSE referral
END CASE,
CASE WHEN ". $_POST['actief'] . " IS NOT NULL
THEN ". $_POST['actief'] . "
ELSE actief
END CASE
WHERE bundel_id = ". $_POST['bundel_id'] . "";
$result = mysql_query($query, $db) or die ('FOUT: werkt niet');
header ("Location: vergelijker_bewerken.php");
} else {
$bundels = mysql_query("SELECT bundels.psp_id, psp.psp_id, psp_naam, bundels.bundel_id, batchkosten, maandelijkse_kosten, aanmeldkosten, transactiekosten, referral, actief from bundels
JOIN psp
ON psp.psp_id = bundels.psp_ID");
}
Use Prepared Statements to escape user input and avoid SQL syntax errors and SQL injections.
You can use a case
UPDATE bundels
SET batchkosten = case when ? is not null and length(?) > 0
then ?
else batchkosten
end,
...
Your current query translates to (which should throw an error actually)
UPDATE bundels
SET batchkosten = CASE WHEN ? length(?) > 0
THEN ?
ELSE batchkosten
END
WHERE bundel_id = ?
But use instead:
SET batchkosten = CASE WHEN ? is not null and length(?) > 0
you can write script some like this maybe:
$query = "Update bundels SET ";
$columns = array( "batchkosten",
"maandelijkse_kosten",
"aanmeldkosten",
"transactiekosten",
"referral",
"actief");
foreach($columns as $column){
if(isset($_POST[$column]) && !empty($_POST[$column])){
$query .= $column . " = " $_POST[$column] . " ";
}
}
$query .= " WHERE bundel_id = " . $_POST['bundel_id'];
Change the query to this
$query= "UPDATE bundels SET
batchkosten = ' ". $_POST['batchkosten'] . " ',
maandelijkse_kosten = ' ". $_POST['maandelijkse_kosten'] . " ',
aanmeldkosten = ' ". $_POST['aanmeldkosten'] . " ',
transactiekosten = ' ". $_POST['transactiekosten'] . " ',
referral = ' ". $_POST['referral'] . " ',
actief = ' ". $_POST['actief'] . " '
WHERE bundel_id = ". $_POST['bundel_id'] . " ".
"and your_attribut is not null and your_attribut != ''";
Don't forget to change "your_attribut".