I'm posting a JSONArray.toString() to a php file. The JSONArray contains a set of id values. I want to make a mysql query that only returns rows that have an id contained in the jsonarray. My method below isn't working. Is there another way?
$jsonarray= $_POST["ids"];
$query = mysql_query("SELECT * FROM table WHERE id IN $jsonarray")or die(mysql_error());
It'd help if we had an example of the JSON array, however, you should decode the JSON array into a comma separated list to use with IN.
$jsonarray = $_POST["ids"];
$ids = implode(",", json_decode($jsonarray,true));
$query = mysql_query("SELECT * FROM table WHERE id IN ($ids)")or die(mysql_error());
Also, you should be using mysqli or PDO_MySQL for new development:
It is recommended to use either the mysqli or PDO_MySQL extensions. It
is not recommended to use the old mysql extension for new development.
A detailed feature comparison matrix is provided below. The overall
performance of all three extensions is considered to be about the
same. Although the performance of the extension contributes only a
fraction of the total run time of a PHP web request. Often, the impact
is as low as 0.1%.
Related Reading:
http://php.net/manual/en/mysqlinfo.api.choosing.php
http://www.php.net/manual/en/mysqlinfo.library.choosing.php
echo out the contents of $jsonarray and you will see the error when you check the syntax of the MySQL query
Related
i'm getting data out of a oracle database:
My code is really simple
$stmt = $con->prepare($query);
$stmt->execute($data);
$res = $stmt->fetchAll(PDO::FETCH_ASSOC);
PHP gives me a resource ID for very long strings in $res.
I want them as a string not a resource ID.
So i can set
$con->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, true);
But now all values are Strings. Not just the resource ones.
Is there a way to achieve this?
(Yes i know that resource IDs are maybe better, but i want it as a string in this case)
The general rule is to use native drivers like PHP OCI8 instead of the limited PHP PDO interface. With OCI8 you can do things like:
while (($arr = oci_fetch_array($s, OCI_ASSOC))) {
$arr = oci_fetch_array($s, OCI_ASSOC+OCI_RETURN_LOBS);
echo $arr['BLOBDATA']; // do something with the LOB
unset($arr); // free PHP's memory before fetching the next LOB.
}
Check out the PHP manual pages or the LOB chapter http://www.oracle.com/technetwork/topics/php/underground-php-oracle-manual-098250.html
How could I return the values from this query as an array so that I can perform an action with the array?
$sql = mysql_query("SELECT username FROM `users`");
$row = mysql_fetch_array($sql);
How would I get the code to be like the following? Here, the user1 and user2 would be the usernames of the users selected from the above query.
$userarray = array("user1","user2");
Before I point out best practices, you need working code first. So I'll give you a simple solution first.
To run a query with the mysql extension the function is mysql_query, you can't pass the query text directly to mysql_fetch_array. Nextly mysql_fetch_array doesn't do what you think it does. mysql_fetch_array combines the functionality of mysql_fetch_row and mysql_fetch_assoc together by storing the key names of the resulting columns along with their numeric indexes. The mysql_fetch_array function does not return an array with all rows from your query. To get all rows from the query, you need to run mysql_fetch_array in a loop like so:
$sql = "SELECT username FROM `users`";
$result = mysql_query($sql);
if(!$result){echo mysql_error();exit;}
$rows=array();
while($row = mysql_fetch_array($result))
{
$rows[]=$row;
}
print_r($rows);
Nextly, do note that the mysql_* functions are deprecated because the mysql extension in PHP is no longer maintained. This doesn't mean MySQL databases are deprecated, it just means the database adapter called mysql in PHP is old and newer adapters are available that you should be using instead, such as mysqli and PDO.
Next point, it is bad practice to rely upon short tags as it can be disabled by php.ini settings, always use either <?php ... ?> or <?= ... ?> for easy echoing which isn't affected by short tags.
Please read up on some mysqli or PDO simple examples to get started with one or the other. The mysqli extension is specific for MySQL while PDO (PHP Data Objects) is designed as a generic adapter for working with several kinds of databases in a unified way. Make your pick and switch so you're no longer using the deprecated mysql_* functions.
You would need to use a foreach loop to do it:
$userarray = [];
foreach($row as $single)
{
array_push($userarray, $single['username']);
}
and if can, try to use this MySQLi Class, it's very simple to get what you want from the database.
$db = new MysqliDb ('host', 'username', 'password', 'databaseName');
$userarray = $db->getValue('users', 'username', null);
I have a MySQL Database Table containing products and prices.
Though an html form I got the product name in a certain php file.
For the operation in this file I want to do I also need the corresponding price.
To me, the following looks clear enough to do it:
$price = mysql_query("SELECT price FROM products WHERE product = '$product'");
However, its echo returns:
Resource id #5
instead a value like like:
59.95
There seem to be other options like
mysqli_fetch_assoc
mysqli_fetch_array
But I can't get them to output anything meaningful and I don't know which one to use.
Thanks in advance.
You will need to fetch data from your database
$price = mysql_query("SELECT price FROM products WHERE product = '$product'");
$result = mysql_fetch_array($price);
Now you can print it with
echo $result['price'];
As side note I would advise you to switch to either PDO or mysqli since mysql_* api are deprecated and soon will be no longer mantained
If you read the manual at PHP.net (link), it will show you exactly what to do.
In short, you perform the query using mysql_query (as you did), which returns a Result-Resource. To actually get the results, you need to perform either mysql_fetch_array, mysql_fetch_assoc or mysql_fetch_object on the result resource. Like so:
$res = mysql_query("SELECT something FROM somewhere"); // perform the query on the server
$result = mysql_fetch_array($res); // retrieve the result from the server and put it into the variable $result
echo $result['something']; // will print out the result you retrieved
Please be aware though that you should not use the mysql extension anymore; it has been officially deprecated. Instead you should use either PDO or MySQLi.
So a better way to perform the same process, but using for example the MySQLi extension would be:
$db = new mysqli($host, $username, $password, $database_name); // connect to the DB
$query = $db->prepare("SELECT price FROM items WHERE itemId=?"); // prepate a query
$query->bind_param('i', $productId); // binding parameters via a safer way than via direct insertion into the query. 'i' tells mysql that it should expect an integer.
$query->execute(); // actually perform the query
$result = $query->get_result(); // retrieve the result so it can be used inside PHP
$r = $result->fetch_array(MYSQLI_ASSOC); // bind the data from the first result row to $r
echo $r['price']; // will return the price
The reason this is better is because it uses Prepared Statements. This is a safer way because it makes SQL injection attacks impossible. Imagine someone being a malicious user and providing $itemId = "0; DROP TABLE items;". Using your original approach, this would cause your entire table to be deleted! Using the prepared queries in MySQLi, it will return an error stating that $itemId is not an integer and as such will not destroy your script.
So i have this so far..
if(isset($_POST['Decrypt']))
{
$dbinary = strtoupper($_POST['user2']);
$sqlvalue = "SELECT `value` FROM `license` WHERE `binary` = '$dbinary'";
$dvalue = mysql_query($sqlvalue) or die(mysql_error());
}
I have a field where the user enters a binary code which was encrypted. (The encrypt part works). This is supposed to retrieve the value from the database. When ever i do it, instead of the value showing up, it says "Resource id #11".
There's nothing wrong with your quoting. In fact, everything looks right so far.
The thing is, right now $dvalue is just a resource to the SQL database. You have to fetch the contents with one more line:
$dvalue = mysql_fetch_array($dvalue);
In the future, you might want to start using PDO or MySQLi instead of the mysql functions, because those are deprecated as of 5.5.0. The advantage of PDO and MySQLi is that they offer security from SQL Injection, which is when users run their own SQL code by inputting something like x'; DROP TABLE members; --.
Don't use the mysql_ functions anymore. They are deprecated. Use PDO or MySQLi instead.
That being said, you are only running the query, and not retrieving any results. You will have to call a function like mysqli_fetch_array to get data from the resource ID that mysqli_query will return.
My advice is to go back to the tutorials and documentation and try again with one of these other extensions. Good luck.
Read this page: W3 Schools page on MySQL select useage. Basically $dvalue is a result set id and you'll need to actually fetch the array out of the database in another step. Also, mysql_* functions are deprecated. Lookup and use the mysqli_* functions instead.
while($row = mysqli_fetch_array($dvalue))
{
echo $row['value'];
echo "<br>";
}
I'm using something like the following PHP code to put all data from a query into an array:
<?php
$results = array();
$q = odbc_exec("SELECT * FROM table");
while ($row = odbc_fetch_array($q)) {
$results[] = $row;
}
?>
This works fine, but it is very slow when the query contains thousands of rows.
My question is, is there any way in PHP to dump all the data into an array without having to loop through each record one by one?
NOTE: Using MS SQL Server for the database.
You could try using mssql functions instead of odbc, but its unlikely to make a large difference.
With the way drivers work, the result set is an iterator handle to the result data itself. In some cases, php doesn't actually get the data until the row is requested by php. Unless there is a fetch all available in the driver, looping through all the rows is generally your only option.
If you don't need all the columns, you could limit the data being transfered by specifing only the columns you actually need.
Specifying the cursor_type in odbc_connect made odbc fetching much quicker.
$conn = odbc_connect($dsn, $user, $pass, SQL_CUR_USE_ODBC)
http://aaronsaray.com/blog/2007/08/02/odbc-for-udb-and-php-how-i-increased-performance-by-400/
I was able to find a way to do this with ADOdb (a database abstraction library for PHP) using the GetAll() function:
http://adodb.sourceforge.net/
$results = $DB->GetAll("SELECT * FROM table");
This returns all the rows as a 2-dimensional array.