I am having a problem.
I know I am using deprecated MySQL, but I am working on a website for school and security is not necessary(as long as it works). I am trying to get all the Id's from a table called Reviews. This should be stored in a array. For some reason it only shows the first one. How to get all of them stored in 1 array? This is my code which is not working:
$sql1 = "SELECT Klanten_id FROM Reviews";
$res1 = mysql_query($sql1);
$r = mysql_fetch_assoc($res1)['Klanten_id'];
1.Don't use outdated mysql_* library.Turn to mysqli_* or PDO.
2.mysql_fetch_assoc: Fetch a result row as an associative array. So you need to apply loop to get all data
Like below:-
$ids = array(); //created an array
while ($row = mysql_fetch_assoc($res1)) {
$ids[] = $row['Klanten_id']; // assign each id to the array
}
print_r($ids);// print array
3.To start working on mysqli/PDO check basic example here:- mysqli/PDO example
Related
My system is composed of 3 components.
ios - php - mysql
If ios users select multiple 'id's,
then, ios app posts these selected 'id' request to server,
and, the server finds the data based on selected 'id's in MySQL.
and finally, the server passes these data to ios app.
These are the PHP statements I tried.
<?php
$id_0 = $_POST['0'];
$id_1 = $_POST['1'];
$id_2 = $_POST['2'];
$id_3 = $_POST['3'];
...
$id_n = $_POST['n'];
$conn = mysqli_connect('address', 'user', 'password', 'database');
$sql = "SELECT * FROM firstname WHERE id = '$id_0'";
if ($result = mysqli_query($conn, $sql)) {
$resultArray = array();
$tempArray = array();
while($row = $result->fetch_object()) {
$tempArray = $row;
array_push($resultArray, $tempArray);
}
} else {
}
mysqli_close($conn);
?>
To get multiple 'id' data, I found that I need to use loop statement.
But the problem is, the number of selected id are variable.
I think that in this code, I need two loop statement.
To get multiple data based on multiple id(the number of id are variable)
To append these data into array
I don't know how to use loop statement when the range is not defined.
How can I use loop statement in PHP, and how can I rearrange these codes?
I'm sure this question is a duplicate but I can't find an exact source.
Your current method means you need to run a whole MySQL query for each iteration.
As the query results will never change what the iteration contains, therefore; you can simply rework it to use MySQL IN to load all of your variables at once:
Step 1) Take all the values and place them in a single array.
$new = []; //new array
foreach ($_POST as $key=>$id){
// Check it is a numeric key
// Check id value is valid to avoid importing other POST values
if((int)$key == $key && (int)$id == $id){
$new[] = $id;
}
}
The above code block is nessecary to stop using values from $_POST['button'] or other posted data that should not be included. This step can be removed if you can clarify your posted data, such as saving all ids to a $_POST['id'] array itself.
Step 2) Empty the array of null/void or repeated values.
$new = array_unique($new);
Step 3) Turn the array into a string, inside the SQL
$arrayString = implode(',',$new);
Step 4) Plug the string into the SQL IN clause:
$sql = "SELECT * FROM firstname WHERE id IN (" . $arrayString . ") ORDER BY id";
Simplified and reduced:
$new = []; //new array
foreach ($_POST as $key=>$id){
if((int)$key == $key && (int)$id == $id){
$new[] = $id;
}
}
$new = array_unique($new);
$sql = "SELECT * FROM firstname WHERE id IN (" .
implode(',',$new) . ") ORDER BY id";
The SQL query above will give you an array of arrays, each one a different row. You can the order them, sort them and output them in PHP as you wish.
See also: This Q&A.
BUT
As expressed by others, you really, REALLY should be using Prepared Statements with MySQLi.
See also here, here and here to see further how to do it and WHY you should do it.
Top Tips:
Numerical columns (typical of id columns) in MySQL do not need the ' quotes.
Until you're using Prepared Statements you can typecast the variables to integers ((int)$var) to limit risk.
It is better to specify the columns you need rather than to use the * catch-all.
Your $_POST data should be an array $_POST['ids'][...].
Eat five different pieces of fruit or veg' a day.
Never trust user input!
I have a file file.php and inside my file I am using the code bellow to pull some data from my database and display some information.
My code is
$array = $_GET['theurl']; // My url looks like myfile.php?theurl=1,2,3 (id,s)
$sqlnt4 = "select * from mytable WHERE `id` IN ($array)";
$rsdt4 = mysql_query($sql);
$tc4a = mysql_fetch_assoc($rsdt4);
$mycomma4 = ",";
if ($tc4a['a_youtube'] == "#"){
}else{
while ($tc4 = mysql_fetch_assoc($rsdt4))
{
echo $tc4['a_youtube'];
echo ",";
}
}
I expect to echo the infos of the two id's (in array) inside my while function, but it returns the results only from the first.
Any ideas?
I am confusing on $sql :
$sqlnt4 = "select * from mytable WHERE `id` IN ($array)";
$rsdt4 = mysql_query($sql);
Can you take a look after changing below:
$sqlnt4 = "select * from mytable WHERE `id` IN ($array)";
$rsdt4 = mysql_query($sqlnt4);
First that's extremely vulnerable to security issues - I hope this isn't used in production and just for playing around.
I recommend switching to PDO, or at the very least securing your variables.
To put that array into the query, you need to implode it into a list, as such.
$list = implode(',', $array);
You can then use the list in the statement, which will look like 1,2,3.
Edit:
I've just realized your $array value isn't actually an array - have you missed code out or is it badly named?
mysql_fetch_assoc: "Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead." http://pt2.php.net/mysql_fetch_assoc
Try mysql_fetch_rows to return all matching rows into an array.
I'm trying to create a while loop in PHP which retrieves data from a database and puts it into an array. This while loop should only work until the array its filling contains a certain value.
Is there a way to scan through the array and look for the value while the loop is still busy?
to put it bluntly;
$array = array();
$sql = mysql_query("SELECT * FROM table");
while($row = mysql_fetch_array($sql)){
//Do stuff
//add it to the array
while($array !=) //<-- I need to check the array here
}
You can use in_array function and break statement to check if value is in array and then stop looping.
First off, I think it'd be easier to check what you're filling the array with instead of checking the array itself. As the filled array grows, searching it will take longer and longer. Insted, consider:
$array = array_merge($array, $row);
if (in_array('ThisisWhatIneed', $row)
{
break;//leaves the while-loop
}
However, if you're query is returning more data, consider changing it to return what you need, only process the data that needs to be processed, otherwise, you might as well end up with code that does something like:
$stmt = $db->query('SELECT * FROM tbl');
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
if ($row['dataField'] === 'username')
{
$user = $row;
break;
}
}
WHERE could help a lot here, don't you think? As well taking advantage of MySQL's specific SELECT syntax, as in SELECT fields, you, need FROM table, which is more efficient.
You may also have noticed that the code above uses PDO, not mysql_*. Why? Simply because the mysql_* extension Is deprecated and should not be used anymore
Read what the red-warning-boxes tell you on every mysql* page. They're not just there to add some colour, and to liven things up. They are genuine wanrings.
Why don't you just check each value when it gets inserted into the array? It is much more efficient than iterating over the whole array each time you want to check.
$array = array();
$stopValue = ...
$sql = mysql_query("SELECT * FROM table");
while($row = mysql_fetch_assoc($sql)){
array_push($array,$row['column']);
if($row['column'] == $stopValue){
// The array now contains the stop value
break;
}
I'm selecting a single column from a MySQL table with mysql_query(). Is there already a function for getting the results into an array, or will I have to iterate through all the results with something like mysql_fetch_array()?
You have to iterate.
If you moved into the 21st century, and used mysqli, there's a mysqli_fetch_all() function.... and you'd be able to use prepared statements
you can do this with mysqli_fetch_all and array_column
$r = mysqli_query($c,"SELECT bug_name FROM bugs WHERE color='red'");
$bug_names = array_column(mysqli_fetch_all($r,MYSQLI_ASSOC),"bug_name");
Nothing like that built in, you will need to do this manually.
you can use mysql_result function still need to do some coding
mysql_result($result,$row_num,$fieldname) ;
retrieves $row_num 'th columes $field_name field .
and following snippet can be taken as an example
$con =mysql_connect($host,$uname,$passwd);
mysql_select_db($dbname,$con);
$result = mysql_query($query,$con);
$arr = array();
$numrows = mysql_num_rows($result);
for($i=0;$i<$numrows;$i++) {
$arr[] = mysql_result($result,$i,$fieldname);
}
this stores every elements of column $fieldname to
array $arr
can any one know the, convert mysql query in to an php array:
this is mysql query :
SELECT SUM(time_spent) AS sumtime, title, url
FROM library
WHERE delete_status = 0
GROUP BY url_id
ORDER BY sumtime DESC
I want to convert this query in to simple php array .
So, you need to get data out of MySQL. The best way, hands down, to fetch data from MySQL using PHP is PDO, a cross-database access interface.
So, first let's connect.
// Let's make sure that any errors cause an Exception.
// <http://www.php.net/manual/en/pdo.error-handling.php>
PDO::setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// We need some credentials...
$user = 'username';
$pass = 'password';
$host = 'hostname';
$dbname = 'database';
// PDO wants a "data source name," made up of those credentials.
// <http://www.php.net/manual/en/ref.pdo-mysql.connection.php>
$dsn = "mysql:host={$host};dbname={$dbname}";
$pdo = new PDO($dsn, $user, $pass);
There, we've connected. Let's pretend that $sql has the SQL you provided in your question. Let's run the SQL:
$statement = $pdo->prepare($sql);
$statement->execute();
There, it's been executed. Let's talk about results. You steadfastly refuse to tell us how you want your data structured, so let's go through four ways that you could get your data.
Let's first assume that the query returns a single row. If you want a numerically indexed array, you would do this:
// <http://www.php.net/manual/en/pdostatement.fetch.php>
$array = $statement->fetch(PDO::FETCH_NUM);
unset($statement);
If you want an associative array with the column names as the keys, you would do this:
$array = $statement->fetch(PDO::FETCH_ASSOC);
unset($statement);
Now, what if the query returns more than one record? If we want each row in a numerically indexed array, with each row as an associative array, we would do this:
// <http://www.php.net/manual/en/pdostatement.fetchall.php>
$array = $statement->fetchAll(PDO::FETCH_ASSOC);
unset($statement);
What if we want each row as a numerically indexed array instead? Can you guess?
$array = $statement->fetchAll(PDO::FETCH_NUM);
unset($statement);
Tada. You now know how to query MySQL using the modern PDO interface and get your results as no less than four types of array. There's a tremendous number of other cool things that you can do in PDO with very minimal effort. Just follow the links to the manual pages, which I have quite intentionally not linked for you.
This over-the-top post has been brought to you by the letters T, F and W, and the number PHP_MAX_INT + 1.
i don't get you clearly, but
mysql_fetch_array and mysql_fetch_assoc
both returns only array
please refer:-
http://php.net/manual/en/function.mysql-fetch-array.php
http://php.net/manual/en/function.mysql-fetch-assoc.php
If you just need a simple array...
while ($row = mysql_fetch_array($query)) { //you can assume rest of the code, right?
$result[$row['url_id']] = array($row['sumtime']);
}
For a simple array
$sql = mysql_query("SELECT SUM(time_spent) AS sumtime, title, url
FROM library
WHERE delete_status = 0
GROUP BY url_id
ORDER BY sumtime DESC");
while($row = mysql_fetch_array($sql)){
$array1 = $row['sumtime'];
$array2 = $row['title'];
$array3 = $row['url'];
}
Hope this is one you wanted
Dude the fastest way is probably the following
$data = array();
while($row = mysql_fetch_array($result))
{
$data[] = $row;
}
print_r($data);