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
Related
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.
i did follow the solution here : Warning: pg_query(): Query failed: ERROR: syntax error at or near but i still got the following error :
Warning: pg_query(): Query failed: ERROR: column "rosmoffi" does not exist LINE 1: ... FROM public."espece" where "espece"."Code_Espece" =Rosmoffi ^
this is my code :
$conn = pg_connect($conn_string);
$query = 'SELECT * FROM public."espece" where "espece"."Code_Espece" ='.$idd ;
if (!$result = pg_query($conn, $query)){
echo pg_result_error ($conn);
return false;
}
$result = db($result);
return $result;
$query = 'SELECT * FROM public."espece" where "espece"."Code_Espece" ='.$idd ;
Do not do this. If you were to output what you get here you'd see the error, as you should from the error message. Whatever is in the variable $idd will be put into the query as is and it will not be considered a string. It's just a part of the query. So since there are no quotes it will in this case be understood as a column name.
The worst part of this is that if $idd is coming from the user think what will happen when someone sets it to 1; truncate table espece. Or something worse. Learn how to use parameters immediately.
Using parameters your code would be:
$query = 'SELECT * FROM public."espece" where "espece"."Code_Espece" =$1';
if (!$result = pg_query_params($conn, $query, array($idd))){
This way the variable is given properly to the database and there is no injection vulnerability.
NB! For those who keep saying the double quotes should be removed, no. They should not. If the column name is capitalized as Code_Espece then PostgreSQL will not recognize it without the quotes. Capitalization is usually not recommended.
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);
I need to get 'groupLeader' field from the table 'groups' in the database and store it in a variable and then compare to the current logged in username but I get the error:
Warning: mysql_numrows() expects parameter 1 to be resource, object given in /home/content/00/7923300/html/uber/tasks.php on line 31
The code I currently have is this:
$sq = "SELECT * FROM groups WHERE groupID='".$groupID."'";
$result=$db->query($sq);
$num=mysql_numrows($result);
$i=0;
while ($i < $num) {
$gLeader= mysql_result($result, $i, 'groupLeader');
$i++;
}
if($_COOKIE['$username'] == $gLeader) {
echo "User is leader.";
}
Forgive me if this seems like a rather simple request. I'm new to php and working with databases.
EDIT: Forgot to mention line 31 is the line that contains
$num=mysql_numrows($result);
You might need to use with PHP's mysql_query or your framework row number method.
$result = mysql_query($sq);
Or perhaps
$db->number_of_rows($sq);
The problem here is, the query is not executed properly for an unknown reason. That is why it is returning False to $result, which is really not a resource.
use:
$sq = "SELECT * FROM groups WHERE groupID='".$groupID."'";
$result = mysqli_query($connection, $sq);
or
$result = mysql_query($sq);
Most of that code is redundant and pointless. if all you want is a single field from a single row, then don't do SELECT *, and don't use a loop.
$sql = "SELECT groupLeader FROM ..."
$result = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($result) > 0) {
$row = mysql_fetch_assoc($reuslt);
if ($row['groupLeader'] == $_COOKIE['username']) {
...
}
}
However, note that the mysql_*() function complex is officially deprecated in PHP and should not be used anymore. Consider switching to mysqli instead, which is generally drop-in compatible, or better yet, use PDO instead.
I have a mySQL database from where I fetch some data via PHP.
This is what I've got:
if ($db_found) {
$URL_ID = $_GET["a"];
$SQL = "SELECT * FROM tb_employees WHERE URL_ID = $URL_ID";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
$firstname = $db_field['firstname'];
$surname = $db_field['surname'];
$function = $db_field['function'];
$email = $db_field['email'];
$telnr = $db_field['telnr'];
}
mysql_close($db_handle);
}
else {
print "Database not found... please try again later.";
mysql_close($db_handle);
}
The URL_ID field in my mySQL database is, for this example, 001. When I go to www.mydomain.com/index.php?a=001 it fetches all the data, puts it into a variable, and I can echo the variables without any problem.
Now, I want to change the URL_ID, and I've changed it to "62ac1175" in the mySQL database. However, when I proceed to www.mydomain.com/index.php?a=62ac1175, I get this error message:
Warning: mysql_fetch_assoc() expects parameter 1 to be resource,
boolean given in
mydomain.com\db_connect.php on line 17
The field in mySQL has varchar(8) as type and utf8_general_ci as collation.
If I change the entry back to 001 and change my URL to ?a=001, it works fine again.
What's going wrong?
You are not doing any error checking in your query, so it's no wonder it breaks if the query fails. How to add proper error checking is outlined in the manual on mysql_query() or in this reference question.
Example:
$result = mysql_query($SQL);
if (!$result)
{ trigger_error("mySQL error: ".mysql_error());
die(); }
your query is breaking because you aren't wrapping the input in quotes. You can avoid* quotes only for integers (which 62ac1175 is not). Try
$SQL = "SELECT * FROM tb_employees WHERE URL_ID = '$URL_ID'";
Also, the code you show is vulnerable to SQL injection. Use the proper sanitation method of your library (like mysql_real_escape_string() for the classic mysql library that you are using), or switch to PDO and prepared statements.
In your code, this would look like so: Instead of
$URL_ID = $_GET["a"];
do
$URL_ID = mysql_real_escape_string($_GET["a"]);
* however, if you avoid quotes, mysql_real_escape_string() won't work and you need to check manually whether the parameter actually is an integer.