Ive been studying "the missing manual" by brett m. Its out of date. I.ve been replacing mysql func. Thats not the problem. I run an if statement to match a sql command using preg match. Before the if I set a var to true. If preg match returns a match, var is then changed to false. If does not run. Script executes to mysqli_fetch. Please help.
$return_rows=true;
If(preg_match("/^\s*(CREATE|INSERT|UPDATE|DELETE|DROP)/i", $query_text))
{
$return_rows=false;
}
If($return_rows)
{
While($row=mysqli_fetch_row($result)){ echo $row[0]; }
}
else{ echo "query processed"; }
mysqli_close($u);
Just cover the SELECT query. cause SELECT is the main query of requesting data from database.
if( strtolower( substr( trim( $query_str ) ) , 0, 6) == "select"){
// SELECT query is being requested
while($row=mysqli_fetch_row($result)){ echo $row[0]; }
else{ echo "query processed"; }
mysqli_close($u);
Now, you can continue your works without any problems
Instead of using an if to only update your $return_rows in one of the cases, assign the regex match result directly:
$return_rows = !preg_match("/^\s*(CREATE|INSERT|UPDATE|DELETE|DROP)/i", $query_text);
The ! here is a negation. You might want to use a more appropriate variable name instead.
Then use your if check to fetch rows, or print a message else:
if ($return_rows) {
// fetch rows
}
else {
// no fetching
}
Also consider using PDO instead of mysqli. It's way less circuitous with parameter binding.
Related
What I want to achieve : if a user pass a PHP parameter to the server, it will return the same parameter value back to the user, instead of returning the value from the database itself.
while($row = mysqli_fetch_assoc($result)){
$classId = $row['classId'];
if($obj['classId'] != ""){
$classId = $obj['classId'];
}
...
}
For some reason, I found out that the $classId still using the $row['classId'] value, even if the user had inserted the classId parameter. It seems that the PHP has ignored/skipped the if statement.
if($obj['classId'] != ""){..} //SKIPPED?
The code works fine right now and I do get the return of the same parameter value. Only one user out of hundreds got this issue and I assumed that the he/she had sent the parameter when the server was busy.
Questions:
1.Can if-statement being ignored/skipped for some reason?
2.How to make the if-statement more reliable even if the server in a high-traffic?
Excuse me for posting here. I don't find the right keywords for googling myself.
Thank you.
You could try having your if statement more strict.
if($obj['classId'] != ""){
$classId = $obj['classId'];
} else {
$classId = $row['classId'];
}
I'd also recommend using isset instead of checking for an empty string.
if(isset($obj['classId'])) { }
I am really trying to wrap my head around this and failing miserably. What I want to do it build a MySQL query based on the URL parameters passed by the URL. I am trying to create a re usable dynamic script that can do what it needs to do based on the URL parameter.
This is what I have come up with, and it appears that it does what it is supposed to do (no errors or anything) but nothing actually gets inserted in the database. I know somewhere I have made a dumb mistake (or thought something out wrong) so hopefully one of you guys can point me in the right direction.
Thanks!
//List all possible variables you can expect the script to receive.
$expectedVars = array('name', 'email', 'score', 'age', 'date');
// This is used for the second part of the query (WHERE, VALUES, ETC)
$fields = array('uName','uEmail','uScore','uAge','uDate');
// Make sure some fields are actually populated....
foreach ($expectedVars as $Var)
{
if (!empty($_GET[$Var]))
{
$fields[] = sprintf("'%s' = '%s'", $Var, mysql_real_escape_string($_GET[$Var]));
}
}
if (count($fields) > 0)
{
// Construct the WHERE Clause
$whereClause = "VALUES " . implode(",",$fields);
//Create the SQL query itself
$sql = ("INSERT INTO $mysql_table ($fields) . $whereClause ");
echo "1"; //It worked
mysql_close($con);
}
else
{
// Return 0 if query failed.
echo "0";
}
?>
You missed mysql_query($sql):
if(!mysql_query($sql)){
//die(mysql_error());
}
Please consider to use PDO or My SQLi using parametrize query because mysl_* function depreciated.
Your SQL is all wrong. You're using the field = value syntax for an INSERT, then you're concatenating an array as if it were a string ($fields), and you're missing a couple of parentheses around the values.
a couple of things: i've found for php <-> mysql its important to see what's going into mysql and experiement directly with those queries in phpmyadmin when i get stuck.
1 - in my code I output mysql_error() when the query fails or when a debug flag is set. this usually explains the sql issue in a way that can point me to a misspelled field name etc...
2 - this way i can feed that mysql query directly into phpmyadmin and tweak it until it gives me the results i want. (while i'm there i can also use explain to see if i need to optimize the table)
specifics in your code. unlike C languages sprintf is implied. here's how i'd write your code:
// List all possible variables you can expect the script to receive.
$expectedvars = array('name', 'email', 'score', 'age', 'date');
// This is used for the second part of the query (WHERE, VALUES, ETC)
// $fields = array('uName','uEmail','uScore','uAge','uDate');
$fields = array();
// Set only the variables that were populated ...
foreach ($expectedvars as $var) {
if (!empty($_GET[$var])) {
$name = "u" + ucwords($var); // convert var into mysql field names
$fields[] = "{$name} = " . mysql_real_escape_string($_GET[$var]);
}
}
// only set those fields which are passed in, let the rest use the mysql default
if (count($fields) > 0) {
// Create the SQL query itself
$sql = "INSERT INTO {$mysql_table} SET " . implode("," , $fields);
$ret = mysql_query($sql);
if (!$ret) {
var_dump('query_failed: ', $sql, $ret);
echo "0"; // Query failed
} else {
echo "1"; // It worked
}
} else {
// Return 0 if nothing to do
echo "0";
}
mysql_close($con);
I have the following problem. I am trying to write function that imports data from csv file. In this file in price column if there are sign like '<>' it means that price is in U.S. dollars and it needs to be converted. I understand that this variable is presented as a digit. How it could be converted to string? Or why the statement doesn't work at all? As always here is the source code.
$str='<>';
if( $variant['price'] ==$variant['price'].$str)
{
$sql = mysql_query("SELECT rate_to FROM s_currencies WHERE id=1 LIMIT 0, 30 ");
$course= mysql_fetch_row($sql);
//$rate=$course[0];
$variant_price = $item['price']*$course[0];
$variant['price']=$variant_price;
}
Please help!
The code which you have posted will not enter into if condition. Make a check with code.
For eg. if $variant['price'] = '1';
if ('1' == '1<>')
{
}
The above condition will not enter into if statement.
You need to check if that string exists, instead of using your current IF statement. strpos will give you want you need
if(strpos($variant['price'],$str) !== false) // <> is present
{
// run your sql code
}
I'd also suggest getting away from the mysql_* functions as they're deprecated. Look into PDO or mysqli queries, with bound parameters.
$str='<>';
if( stristr($variant['price'],$str){
$sql ="SELECT rate_to FROM s_currencies WHERE id=1 LIMIT 0, 30 ";
$qry = mysql_query($sql);
if ($qry && mysql_num_rows($qry)>0){
$variant['price'] = (str_replace($str,'',$variant['price'])*mysql_result($qry,0,0));
} else {
echo 'error while converting:' . mysql_error();
}
}
I use below php code to send results of MYSQL databse search to AJAX requests...
$query = $db->query("SELECT name FROM search WHERE qurl = '" . $queryString . "'");
if($query) {
while ($result = $query ->fetch_object()) {
echo $result->name;
}
} else { echo 'no results found'; }
but I never get no results found message even there is no results, all I get if there is no result, two empty spaces - I found that using alert(data.length) in AJAX page, result was 2 which means php output has two empty spaces when there is no results...
but when there are results it works fine...
any way of removing these two spaces or why Im not getting no results found message?
if ($query->num_rows > 0) {
while ...
} else {
echo 'no results found';
}
$db->query() only returns false if there was an error performing the query. An empty result set is not an error.
What you are evaluating is if the statement is valid... which it is, and will always return true. To evaluate the results returned, you'll need to evaluate $query->num_rows
I want to use PHP to find out if no matches are found. I tried the following, but "is_resource()" always returns true.
$result = mysql_query('...');
if(is_resource($result)){
// Results are found
}
mysql_num_rows() will do the trick.
if (mysql_num_rows($result)>0) {
//Results are found
}
http://php.net/manual/en/function.mysql-num-rows.php
So $result will always be a resource as long as you have proper access to the database. And mysql_num_rows() assumes that the query itself ran successfully. I'd say try something like this:
if($result === FALSE) // Query failed due to not having proper permissions on the table
die('Invalid query: ' . mysql_error());
else if(mysql_num_rows($result) >0)) // We have more than 1 row returned which means we have data
// INPUT RESULTS PROCESSING HERE
else // No rows were returned therefore there were no matches
echo 'No rows returned';
Hope that helps a little =)
Look here for more information if you need: http://www.php.net/manual/en/function.mysql-query.php
This is what you want: mysql_num_rows()
If the query fails it mysql_query will return false so you can check your code like this:
if ( $stmt = mysql_query("...") )
{
// Do some things
}
else
{
// Do some other things
}
Or you could use mysql_num_rows like the people above have stated.
But you should really be looking into MySQLi it's a built in database class. Learn it and use it. Your life will be so much easier.