php - check if results contain value - php

I did SQL query.
I would like to check if the results contain the value "xxx".
Is there any php function that support that?
I tried "in_array" but it doesn't work.
$stylesQuery = mysql_query("SELECT styleID FROM itins_styles WHERE (itinID = 5)");
$stylesIndex = mysql_fetch_array($stylesQuery);
if (in_array ("xxx", $stylesIndex ))

You forgot the ; in your mysqli_fetch_array($styleQuery).
$stylesIndex = mysqli_fetch_array($styleQuery);
If your array variable $stylesIndex contains the value xxx then it should work.

Maybe in_array() did work. The function returns true when the item is found and false otherwise. In the OP's code when in_array() returns false, the if-conditional fails suggesting that the search string is not in the array. But, if you know that it should be there, then there might be failure at another point in the code.
As an aside, while mysql is deprecated, and all PHP developers should switch to mysqli, some people don't have that luxury and must work with what their workplace dictates. The problem here is not mysql but rather the need to heed the Manual's recommendations about basic testing. Below is code that mainly derives from the Manual (see here):
<?php
error_reporting(E_ALL);
$result = null;
$res = null;
$link = mysql_connect('localhost', 'root', '')
or die('Could not connect: ' . mysql_error());
mysql_select_db('exp') or exit('Could not select database');
$query = "SELECT * FROM countries WHERE id=0";
$result = mysql_query($query) or exit('Query failed: ' . mysql_error());
$line = mysql_fetch_array( $result, MYSQL_ASSOC );
if (in_array( "US", $line ) ) {
echo "in array\n";
}
var_dump($line);
// Free resultset
mysql_free_result($result);
This code errors out when I run it because my countries table does not contain an id of zero. Consequently, the $result does not contain an array of data -- its value is false. So, in_array() returns false. If I correct the query, then the code runs fine.
Note: having error_reporting() on, can be very helpful when trying to debug code.

Related

can't echo out an int variable

I've tried to use the solutions presented in this question,
to no avail, so I used this:
$stat = "SELECT MAX(employee_id) FROM employees";
$querysult = intval($connection, $stat);
Where employee_id is an int(3) in the database table.
For some reason, the above code actually gets the values from the database, despite there not being a mysqli_query() in sight. But my question is about what I did immediately after, which was
echo "Id: " . $querysult;
and which output nothing but
Id:
and no number. I've also tried casting the number to a string, and concatenating it to an empty string before the echo statement.
For some reason, the above code actually gets the values from the database, despite there not being a mysqli_query() in sight
This of course is quite impossible, unless you are getting something from a previously executed query that uses the same variable names.
I think your main problem is that accessing the value of the query coded using just SELECT MAX(employee_id) will return a column with the name MAX(employee_id) and that is not a valid PHP variable name. So what you have to do is give that column another name that is a valid PHP variables name using this syntax SELECT MAX(employee_id) as max_empid which renames the column to max_empid
I am assuming nothing so I will also include a connection to the database in my answer. You will need to replace the my_user, my_password and my_db values, or ignore the connection if you have already dont that somewhere else. I have also used the Object Oriented approach to MYSQLI, if you are using the proceedural calls, you may have to amend the code accordingly
// connect to your database
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
// build query and use an alias for the `MAX(employee_id)`
// so you can easily use its name in the result set
$sql = "SELECT MAX(employee_id) as max_empid FROM employees";
// Now we must execute this query
$result = $mysqli->query($sql);
// Now we must chech that the query worked
if ( $result === FALSE ) {
echo sprintf( 'Query Failed: %s<br>%s', $sql, $mysqli->error);
exit;
}
// now we must read one of the rows from the result set
// produced by the ->query() command.
// In this case there of course there is only one result row
$row = $result->fetch_object();
echo 'Id: ' . $row->max_empid;
It may be because you are trying to convert a connection to an int value.
Try this
$connection = new mysqli();
$querysult =mysqli_query( $stat);
printf("Select returned %d.\n", $querysult->num_rows);

Fetch array mysql database php

I am trying to fetch data from database, but something is not working.
This is my code:
<?php
$koppla = mysql_connect("localhost","admin","","test");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$get = mysql_query($koppla,SELECT * FROM 123);
while ($test = mysql_fetch_array($get))
{
echo $test['tid'];
}
mysql_close($koppla);
?> `<?php
$koppla = mysql_connect("localhost","admin","","test");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$get = mysql_query($koppla,SELECT * FROM 123);
while ($test = mysql_fetch_array($get))
{
echo $test['tid'];
}
mysql_close($koppla);
?>
I am getting the following error while trying to fetch an array from a MySQL database. What is wrong?
Parse error: syntax error, unexpected '123' (T_LNUMBER) in C:\wamp\www\test.php on line 16
What was wrong
There are at least 3 errors:
Use either mysql_XY or mysqli_XY. NOT both. See MySQL: Choosing an API.TL;DR: Use mysqli_*, because mysql_* is deprecated.
The SELECT statement in line 16 and line 39 has to be in quotes.
The syntax of mysql_query is
mixed mysql_query ( string $query [, resource $link_identifier = NULL ] )
What is correct
So line 16 has to be something like
$get = mysql_query("SELECT * FROM 123", $koppla);
or, when you choose mysqli_query:
$get = mysqli_query($koppla, "SELECT * FROM 123");
Side notes
Table naming: I would not use a table name like 123. I don't know if this is valid SQL, but it feels wrong to not start a table with a character. See SQLite issue with Table Names using numbers? - I know you're using MySQL, but MySQL might have similar problems. And you might want to switch sometimes to another database system.
Optional arguments: You don't need to specify the $link_identifier in mysql_* if you don't have multiple connections.
Style Guide: In PHP, you usually have the curly brace { in the same line as the if. See List of highly-regarded PHP style guides? and especially the Zend and PEAR section. This is also good for SO, because you could avoid a scrollbar in your code which makes reading your question easier.
$get = mysql_query($koppla,SELECT * FROM 123);
should be
$get = mysql_query("SELECT * FROM `123`",$koppla);
You have this in 2 places correct them.
OH well hold on you are using mysql_query()
so it should be
$get = mysql_query("SELECT * FROM `123`",$koppla);
http://in1.php.net/mysql_query
Now going more in the code you are using if (mysqli_connect_errno()) this is for mysqli_connect() you may need to see
http://in1.php.net/manual/en/function.mysql-connect.php as well
$get = mysql_query($koppla,SELECT * FROM 123);
Shell look like this:
$get = mysql_query("SELECT * FROM 123", $koppla);
A query is used to be String; and $koppla shell be the second parameter

Basic PHP/MySQL Error with mysql_fetch_array()

The error I get:
...mysql_fetch_array() expects parameter 1 to be resource, boolean given...
awayid is in the address bar properly. I can print it out just fine, but for some reason the following code gives me the above error.
$result = mysql_query("select * from team where id=" . $_GET['awayid']);
$row = mysql_fetch_array($result);
EDIT Tried the mysql_error(). It seems I forgot to select a database... however, even why I use mysql_select_db('gamelydb'); I still get the mysql error No database selected
Your query is failing... Therefore $result is set to false.
$result = mysql_query("select * from team where id=" . $_GET['awayid']);
var_dump($result); // bool(false)
Call mysql_error() to get the error message for your query:
echo mysql_error();
Your query is failing and returning a boolean FALSE. Try this:
$result = mysql_query("select ...") or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^^---- add this
This will kill the script and show you the exact reason the query is failing.
mysql_query() returns false if the query is unsuccessful, i.e. an error occured. That is why you need to check $result for being false first.
Use mysql_error() to output the error.
You need to be sure there is results from your query :
while ($row = mysql_fetch_array($result)) {
// echo $row[] ... ;
}
First of all, your query is very open to SQL injection attacks. Do not directly insert anything from $_GET or $_POST (or really anywhere) into your query. At the minimum, use mysql_real_escape_string on the variable.
mysql_query is returning false becuase there is something wrong with the query. You can use mysql_error to see what the last reported error is.
if ($result = mysql_query("select * from team where id='" . $_GET['awayid']) . "'") {
$row = mysql_fetch_array($result);
}
else {
echo mysql_error();
}
Anyway...you know that writing a $_GET parameter right into the SQL query is very very bad? Try it with PHP Data Objects.
Did you try and search around first Tory, we answer these questions over and over again, next time please search around.
The reason why this error occurs is because your running a query with mysql_query that fails, because it fails it returns false, you then pass the value of false to mysql_fetch_array, it's like doing mysql_fetch_array(false)
You need to make sure that mysql_query is successful:
try something like this:
if(false !== ($result = mysql_query("select * from team where id=" . $_GET['awayid'])))
{
$row = mysql_fetch_array($result);
}else
{
die("Query has failed: " . mysql_error())
}

call stored procedure using php

i have written a basic stored procedure using mysql
DELIMITER //
CREATE PROCEDURE `sp_sel_test`()
BEGIN
SELECT * FROM category c;
END//
DELIMITER ;
now i m calling it from php
the php code is:
<?php
$txt = $_GET['id'];
$name = $_GET['name'];
$con = mysql_connect("localhost","four","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("fourthes_a", $con);
//$result = mysql_query("select * from new_c where name like %". $name ."% or c_name like %" . $name . "% order by name asc;");
$result = mysql_query("call sp_sel_test()");
if ($result === FALSE) {
die(mysql_error());
}
while($row = mysql_fetch_array($result))
{
echo $row['category_id'] . " " . $row['c_name'];
?>
<br />
<?php
}
mysql_close($con);
echo $txt;
?>
now its giving the error
PROCEDURE fourthes_a.sp_sel_test can't return a result set in the given context
mysql_query() returns false when the query fails. You didn't check if your sproc query succeeded, so most likely you're passing that boolean FALSE to the fetch function, which is rightfully complaining.
Rewrite your code like this, as a bare mininum, for proper error handling:
$res = mysql_query('call sp_sel_test()');
if ($res === FALSE) {
die(mysql_error());
}
Never ever assume a query succeeded. Even if the SQL syntax is perfect, there's far too many other reasons for a query to fail to NOT check if it worked.
You need to set client flags while connecting for using stored procedures with php. Use this:
mysql_connect($this->h,$this->u,$this->p,false,65536);
See MySQL Client Flags for more details. PHP MySQL does not allow you to run multiple statements in single query. To overcome this you must tell PHP to allow such queries by setting CLIENT_MULTI_STATEMENTS flag in your connection.
I know last answer was a year ago, but...
CREATE PROCEDURE sp_sel_test(OUT yourscalarvariable INT/TEXT...)
Statements that return a result set cannot be used within a stored function. This includes SELECT statements that do not use INTO to fetch column values into variables, SHOW statements, and other statements such as EXPLAIN. For statements that can be determined at function definition time to return a result set, a Not allowed to return a result set from a function error occurs (ER_SP_NO_RETSET_IN_FUNC). For statements that can be determined only at runtime to return a result set, a PROCEDURE %s can't return a result set in the given context error occurs (ER_SP_BADSELECT).
So, your select shoould be like this:
SELECT * FROM category **INTO** c;
http://www.cs.duke.edu/csl/docs/mysql-refman/stored-procedures.html

PHP mySql update works fine on localhost but not when live

I have a a php page which updates a mySql database it works fine on my mac (localhost using mamp)
I made a check if its the connection but it appears to be that there is a connection
<?php require_once('connection.php'); ?>
<?php
$id = $_GET['id'];
$collumn = $_GET['collumn'];
$val = $_GET['val'];
// checking if there is a connection
if(!$connection){
echo "connectioned failed";
}
?>
<?php
$sqlUpdate = 'UPDATE plProducts.allPens SET '. "{$collumn}".' = '."'{$val}'".' WHERE allPens.prodId = '."'{$id}'".' LIMIT 1';
mysql_query($sqlUpdate);
// testing for errors
if ($sqlUpdate === false) {
// Checked this and echos NO errors.
echo "Query failed: " . mysql_error();
}
if (mysql_affected_rows() == 1) {
echo "updated";
} else {
echo "failed";
}?>
In the URL i pass in parameters and it looks like this: http://pathToSite.com/updateDB.php?id=17&collumn=prodid&val=4
Maybe this has to do with the hosting? isn' t this simple PHP mySql database updating? what can be wrong here?
Why on localhost it does work?
Why on live server it doesn't?
Let's start with troubleshooting your exact problem. Your query is failing for some reason. We can find out what that problem is by checking what comes back from mysql_query, and if it's boolean false, asking mysql_error what went wrong:
$sh = mysql_query($sqlUpdate);
if($sh === false) {
echo "Query failed: " . mysql_error();
exit;
}
You have other problems here. The largest is that your code suffers from an SQL Injection vulnerability. Let's say your script is called foo.php. If I request:
foo.php?collumn=prodId = NULL --
then your SQL will come out looking like:
UPDATE plProducts.allPens SET prodId = NULL -- = "" WHERE allPens.prodId = "" LIMIT 1
-- is an SQL comment.
I just managed to nuke all of the product IDs in your table.
The most effective way to stop SQL injection is to use prepared statements and placeholders. The "mysql" extension in PHP doesn't support them, so you'd also need to switch to either the must better mysqli extension, or the PDO extension.
Let's use a PDO prepared statement to make your query safe.
// Placeholders only work for *data*. We'll need to validate
// the column name another way. A list of columns that can be
// updated is very safe.
$safe_columns = array('a', 'b', 'c', 'd');
if(!in_array($collumn, $safe_columns))
die "Invalid column";
// Those question marks are the placeholders.
$sqlUpdate = "UPDATE plProducts.allPens SET $column = ? WHERE allPens.prodId = ? LIMIT 1";
$sh = $db->prepare($sqlUpdate);
// The entries in the array you pass to execute() are substituted
// into the query, replacing the placeholders.
$success = $sh->execute(array( $val, $id ));
// If PDO is configured to use warnings instead of exceptions, this will work.
// Otherwise, you'll need to worry about handling the exception...
if(!$success)
die "Oh no, it failed! MySQL says: " . join(' ', $db->errorInfo());
Most mysql functions return FALSE if they encounter an error. You should check for error conditions and if one occurs, output the error message. That will give you a better idea of where the problem occurred and what the nature of the problem is.
It's amazing how many programmers never check for error states, despite many examples in the PHP docs.
$link = mysql_connect(...);
if ($link === false) {
die(mysql_error());
}
$selected = mysql_select_db(...);
if ($selected === false) {
die(mysql_error());
}
$result = mysql_query(...);
if ($result === false) {
die(mysql_error());
}
Your call to mysql_query() is faulty; you're checking the contents of the variable you're passing in but the function call doesn't work that way. It returns a value which is what you should check. If the query failed, it returned false. If it returns data (like from a SELECT) it returns a resource handle. If it succeeds but doesn't return data (like from an INSERT) it returns true.
You also have some problems constructing your SQL. #Charles mentions SQL injection and suggests prepared statements. If you still want to construct a query string, then you need to use mysql_real_escape_string(). (But I would recommend you read up on the mysqli extension and use those functions instead.)
Secondly, you're concatenating strings with embedded substitution. This is silly. Do it this way instead:
$sqlUpdate = 'UPDATE plProducts.allPens SET '.$collumn.' = \''.$val.'\'
WHERE allPens.prodId = '.intval($id).' LIMIT 1';
If you must accept it in the querystring, you should also check that $collumn is set to a valid value before you use it. And emit and error page if it's not. Likewise, check that $id will turn into a number (use is_numeric()). All this is called defensive programming.

Categories