SQL Query doesn't print varchar/text column - php

I got a little problem here with my SQL query...
I debugged where the problem resides and realized that the varchar/text column seemed to stop my php function.
Here is my code:
$queryTest = mysqli_query($link, "SELECT dos_nom,dos_id FROM dossier");
while($dataTest = mysqli_fetch_assoc($queryTest)) {
if($dataTest['dos_id'] == $myparameter) {
$toreturn.= '<option class="text-'.$dataTest['dos_id'].'" value="'.$dataTest['dos_nom'].'" selected>'.$dataTest['dos_nom'].'</option>';
}
}
The problem is in the value $dataTest['dos_nom']. Without which my query works (it prints the page normally), but I don't know why. With it, it doesn't work (it prints the top of the page, and nothing from/after my php function)...
To be precise, i use it in an ajax function.
Thanks in advance!
EDIT: I tried to print only 1 row from 'dos-nom', it works! But i when try to print out more than 1 row, the function stops!
My code:
$queryTest2 = mysqli_query($link, "SELECT * FROM dossier");
while($dataTest2 = mysqli_fetch_assoc($queryTest2))
{
$test[0] = $dataTest2['dos_nom'];
}
if($dataTest['dos_id'] == $dos_id)
{
$toreturn.= '<option class="text-'.$dataTest['dos_id'].'" >'.$test[0].'</option>';
}
It prints only the last line this way. If i put a WHERE in the query it will stop the function, so i don't know what to do!
ANSWER:
É / À were in my database, i replaced them by E and A, problem solved!

try to use addslashes() function like
addslashes($dataTest['dos_nom'])
maybe the value contains some backslash or some junk characters which may be breaking your code

I see nothing wrong with your code, except the logic - you only output when option is selected.
So as you said (it prints nothing)
Let's try print something:
$queryTest = mysqli_query($link, "SELECT dos_nom,dos_id FROM dossier");
while($dataTest = mysqli_fetch_assoc($queryTest)) {
$selected = ($dataTest['dos_id'] == $myparameter)?' selected ':' ';
$toreturn.= '<option class="text-'.$dataTest['dos_id'].'" value="'.$dataTest['dos_nom'].'" '.$selected.'>'.$dataTest['dos_nom'].'</option>';
}

Related

PHP variable is not working with WHERE clause

My query is not working when I use the variable in the WHERE clause. I have tried everything. I echo the variable $res, it shows me the perfect value, when I use the variable in the query the query is not fetching anything thus mysqli_num_rows is giving me the zero value, but when I give the value that the variable contains statically the query executes perfectly. I have used the same kind of code many times and it worked perfectly, but now in this part of module it is not working.
Code:
$res = $_GET['res']; // I have tried both post and get
echo $res; //here it echos the value = mahanta
$query = "SELECT * FROM `seller` WHERE `restaurant` = '$res'"; // Here it contains the problem I have tried everything. Note: restaurant name is same as it is in the database $res contains a value and also when I give the value of $res i.e. mahanta in the query it is then working.
$z = mysqli_query($conn, $query);
$row2 = mysqli_fetch_array($z);
echo var_dump($row2); // It is giving me null
$num = mysqli_num_rows($z); // Gives zero
if ($num > 0) {
while ($row2 = mysqli_fetch_array($z)) {
$no = $row2['orders'];
$id = $res . $no;
}
}
else {
echo "none selected";
}
As discussed in the comment. By printing the query var_dump($query), you will get the exact syntax that you are sending to your database to query.
Debugging Tip: You can also test by pasting the var_dump($query) value in your database and you will see the results if your query is okay.
So update your query syntax and print the query will help you.
$query = "SELECT * FROM `seller` WHERE `restaurant` = '$res'";
var_dump($query);
Hope this will help you and for newbies in future, how to test your queries.
Suggestion: Also see how to write a mysql query syntax for better understanding php variables inside mysql query
The problem is the way you're using $res in your query. Use .$res instead. In PHP (native or framework), injecting variables into queries need a proper syntax.

Print a Conditioned COUNT query with PHP

I need some help with PHP, i wanna print a value from a COUNT(*) query but it's conditioned, my code:
<?php
require ('../login/conexion.php');
session_start();
if(!isset($_SESSION["id_usuario"])){
header("location: ../login/");
}
//I wanna do this
$consulta_OD = '';
function query_()
{
global $conexion, $consulta_OD;
$sql = 'SELECT COUNT(*) as total from gok_registro WHERE estado=3';
return $conexion->query($sql);
}
$consulta_OD = query_OD();
$costo_OD = $consulta_OD->fetch_assoc();
echo $costo_OD['total'];
?>
By the way, the connection to a BD is good since my code works, without the lines after the "//i wanna do this" comment. The query also works in the console.
The last line is to print the query in another part of the document, any help?
Your SQL request looks good.
But:
the function query_ is never call
the function query_OD not exist
global $consulta_OD; is not used in the function query_ so useless
If you rename query_ by query_OD your code should work

Can't get dropdown to populate from MySQL database

I would like to create a simple select drop down, to be populated by a table in my MYSQL database.
Here is my code:
$q = 'SELECT * FROM Shipmethods';
$result = mysqli_query($connection, $q);
echo '<select name="shipmethod">';
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC));
{
echo '<option value="' . $row['shipmethodid'] . '">' . $row['shipmethoddesc'] . '</option>';
}
echo '</select>';
mysqli_free_result($result); // free up the results
}
There is no connection error, no typos in table name or column names. The HTML output shows that a select option exists, but it is empty. I would like to use mysqli for this.
There seem to be countless topics already on this subject, but as far as I can see, my code matches the correct answers of those already answered questions.
Thanks in advance.
Remove ; from this line, rest code seems fine to me, let me know if it works or not --
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC));
To
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
First off, based on the evidence we have, the most likely issue, other than an empty result set, is the issue that swapnesh identified, which is clearly a logic error. I'm providing this illustration, which simulates the problem to make it clear that it is NOT a syntax error to do what was accidently done here. The misplaced semicolon in essence causes the following block to be entered only after the while loop has been exhausted.
Consider this example:
<?php
$r = array(1,2,3,4);
function fetchit(&$r) {
return array_pop($r);
}
while ($val = fetchit($r))
{
echo $val;
}
This would be the intended use. Now what happens if the script has this code instead?
<?php
$r = array(1,2,3,4);
function fetchit(&$r) {
return array_pop($r);
}
while ($val = fetchit($r));
{
echo $val;
}
Trying these you will see that both scripts run without error. Although unnecessary, php does not care if you randomly include an uneeded block somewhere in your script { }, and it also does not care if an if, while, for etc, is followed by a block. It's in fact common practice for people to shorten up code with:
if (//somecondition)
statement;
Many people frown on that practice but it's legal and programmers use it all the time.

Javascript switch not taking passed variable

I have 2 drop downs and I'm using the switch to populate the second after something has been selected in the first. It's mostly just an experiment because the jquery thing i had doing it before seemed really slow. If anyone has a better, faster way of doing this, I'm all ears. But I still want an answer to this because it's just irritating me now.
The first drop downs onchange="chngprog(this)" calls this function
function chngprog(facility)
{
if(facility.id == 'facilityview'){
var select = document.getElementById('programview');
} else {
var select = document.getElementById('program');
}
var testid = facility.value;
switch(testid){
<?php global $__CMS_CONN__;
$sqlqry = "SELECT * FROM facility_db";
$stmt = $__CMS_CONN__->prepare($sqlqry);
$stmt->execute();
$listfacility = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($listfacility as $case)
{
echo "case ".$case['id'].":\n";
echo "select.options = '';";
$boom = explode(";", $case['programs']);
foreach($boom as $program)
{
echo "select.options[select.options.length] = new Option('$program', '$program');\n";
}
echo "break;\n";
}
?>
}
}
The php creates all the cases from the database, as there are 50+, probably not helping the speed factor.
The if statement at the top is to determine which set of drop downs it's looking at, as there are 2 sets that do the same thing, but for different purposes.
The problem is getting the switch to hit a case. I've put alerts around to see what happens, and all the values are right, but it never hits a case unless is specify the number. If i put switch(20) it hits case 20 and adds the options to the second drop down just as it should.
So why isn't the switch evaluating the variable I put in?
Is facility.value a string? Try
var testid = parseInt(facility.value, 10);
Your testid is probably a string and your case statements are expecting integers.
Try:
switch (parseInt(testid)) {
...
You may want to put your values between ', like this:
echo "case '" . $case['id'] . "':\n";
If you don't, you will have to cast the variable to int before comparing with any value (I'm supossing also that id will never return anything different than a number).

Drupal - db_fetch_array returns NULL for every row

I'm using Drupal's db_fetch_array to fetch rows from my db_query. However, every row returned is equal to NULL. Typing the query into PHP myadmin works, so I have no idea whats going on. db_num_rows returns the number of rows as well. Here is the code:
if(count($rebuild_ids))
{
$ids=implode(",",$rebuild_ids);
$type_stmt = "SELECT * from {" . ItemType::$type_table_name . "} where id IN ($ids)";
$new_items=db_query($type_stmt);
if(!$new_items || db_num_rows($new_items) == 0)
{
return;
}
while($row = db_fetch_array($new_items));
{
if ($row!=NULL)
{
echo "I work!"
$game_items[] = $row['id'];
ItemInstance::$nid_to_item_type_code[$row['nid']] = $row['id'];
}
}
}
However, it never gets into the third if statement (i.e. never echos "I work!") Any ideas?
Friendly advice: Drupal has a coding standards http://drupal.org/coding-standards -- it helps to keep them. This error would have been a lot more obvious that way....
Also putting variables in a query is a huge no-no see http://drupal.org/writing-secure-code
$row is not NULL by definition, otherwise it wouldn´t even reach the third if statement.
There is no need to check if $row contains information, the while loop already takes care of that, but if you want to check anyway, use something like empty($row) or count($row) > 0; don´t compare an array with NULL.
The checking is completely unnecessary though...
K figured it out. It was the semicolon after the while loop!

Categories