Mysql to mysqli or PDO - php

I have a project here that has a LOT of this kind of code below.
It is everything in mysql and I want to change do mysqli or PDO.
The problem is that the code make the fields of the table be variables, inside the loop. So, If I need to change to something different, I will have to re-write thousand of lines of code. Because inside the loops below I will change every call of the var. Example: $row["product_name"] instead of $product_name
This is the code:
$query = "SELECT product_name, product_price from products";
$result = mysql_query($query_sql);
while($row = mysql_fetch_array($result)) {
$j = mysql_num_fields($query);
for($i=0;$i<$j;$i++) {
$k = mysql_field_name($query,$i);
$$k = $row[$k];
}
//Here, inside the loop, I use $product_name instead of $row["product_name"]
}
It there a way to change the code to do the same with mysqli or PDO? I want to keep using $field_name instead of $row["field_name"].

mysqli object method shown. I don't recommend doing it this way, but it can be done. I would highly suggest you learn how to deal with either a result object or array directly. Dynamically setting variables like this will introduce a lot of unnecessary overhead.
$result = $mysqli->query($query_sql);
while($row = $mysqli->fetch_assoc($result)) {
extract($row);
//Here, inside the loop, I use $product_name instead of $row["product_name"]
}

Here is what you are looking for: http://www.doctrine-project.org/
I specifically do not like this specific project, because it tends to be slow with larger amounts of data, but provides what you need:
You specify domain classes (understand map database lines to php objects) and you only have to specify the exact name of the table column, if it does not match up with the class variable name.
So you set every column once for every object type and you use that definition throughout you code, you are making a request for the object, that has a mapping to the database.
so it goes like: $entitiy_manager->getReference('myobject', $objectid = 1 );
Creating a new object is just adding a new instance of the class.
If I understood you properly this should be you are looking for.

Thank you for every answer and opinion, but I just found the solution for my question.
I will leave here, for future reference.
This code is in mysql:
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
$j = mysql_num_fields($query);
for($i=0;$i<$j;$i++) {
$k = mysql_field_name($query,$i);
$$k = $row[$k];
}
}
And this would be the same in mysqli:
$result = mysqli_query($link, $query);
while($row = $query->fetch_assoc())
{
$j = mysqli_num_fields($query);
for($i=0;$i<$j;$i++) {
$k = mysqli_fetch_field_direct($query, $i)->name;
$$k = $row[$k];
}
}

Related

How to loop the query in this case?

I have been trying to loop this query but all I get is the first value.
When I do the same command in workbench I get all the values.
What am I doing wrong here? Any answers are much appreciated!
global $db;
$stmt12 = $db->query('SELECT `Value` FROM overriddenpropertyvalues WHERE ParentGUID LIKE "' . $itemguid . '";');
$propertyvaluerow = $stmt12->fetch();
while ($propertyvaluerow != null) {
You are fetching only one value with ->fetch(). That's why you receive only one value.
Example from here:
$query = $db->prepare('SELECT `Value` FROM `overriddenpropertyvalues` WHERE ParentGUID LIKE :like');
$query->execute([':like' => $itemguid]);
$stmt->bind_result($value);
while ($query->fetch()) {
echo $value."<br/>"
}
There might possibly be a loophole in your Program depending on what the $stmt12->fetch() does. If it fetches an Array of Data, your while loop might not behave as expected. Below is a commented alternative to what you might want to try out:
<?php
global $db;
$stmt12 = $db->query('SELECT `Value` FROM overriddenpropertyvalues WHERE ParentGUID LIKE "' . $itemguid . '";');
// ASSUMES YOU ARE USING PDO SO WE FETCH ALL THE DATA
$propertyvaluerow = $stmt12->fetchAll();
// THERE MIGHT BE A LOOPHOLE IN YOUR PROGRAM DEPENDING ON WHAT $stmt12->fetch() IS AND DOES
// ASSUMING IT FETCHES AN ARRAY OF NESTED OBJECTS OR SCALAR VALUES, THE WHILE LOOP WOULD NOT BEHAVE AS EXPECTED.
// THAT MEANS IF IT IS AN ARRAY YOU COULD USE A DIFFERENT CONSTRUCT LIKE THE ONE BELOW YOUR WHILE CONSTRUCT:
/* while ($propertyvaluerow != null) { */
// CREATE A $count VARIABLE TO HOLD THE INCREMENTAL COUNT THROUGH THE ITERATION:
$count = count($propertyvaluerow);
while($count > 0){
// DO YOUR WORK HERE
//DECREMENT THE VALUE OF COUNT OTHERWISE YOU MAY HAVE AN INFINITE LOOP TO DEAL WITH.
$count--;
}
?>
There is yet another alternative:
<?php
// OR EVEN A MUCH MORE EASIER WAY IS TO USE THE FOREACH LOOP, WHICH ACHIEVES THE SAME THING AS THE WHILE LOOP:
foreach($propertyvaluerow as $iKey=>$objData){
// SIMPLY USE THE $objData IN WITHING THE LOOP
// THE $objData IS THE VALUE OF THE CURRENT OBJECT IN THE $propertyvaluerow IN THE ITERATION
}
Best way:
global $db;
$stmt = $db->prepare('SELECT `Value` FROM OverriddenPropertyValues WHERE ParentGUID=?');
$stmt->execute([$itemguid]);
$rows = $stmt->fetchAll();
foreach($rows as $row) {
// $row->Value or $row['Value']
}

How do I insert values into an multidimensional-array, then show them?

I'm fairly new to php, and I don't know how to work with arrays very well. Here's the deal, I want to add into a multidimensional array three or more values I obtain from my database, then I want to sort them based on the timestamp (one of the values). After that, I want to show all of the sorted values. I can't seem to do this, here's the code
$queryWaitingPatients = 'SELECT ArrivalTime, TargetTime, Order, Classification FROM exams WHERE (CurrentState = "Pending")';
$results = mysql_query($queryWaitingPatients) or die(mysql_error());
if (mysql_num_rows($results) == 0) {
echo '<p>There\'s currently no patient on the waiting list.</p>';
return;
}
while ($rows = mysql_fetch_array($results)) {
extract($rows);
//now is the part that I don't know, putting the values into an array
}
// I'm also not sure how to sort this according to my $TargetTime
asort($sortedTimes);
//the other part I don't know, showing the values,
Thanks for the help!
Well, let's look at your code. First, you have a query that's returning a result set. I don't recommend using mysql_fetch_array because it's not only deprecated (use mysqli functions instead) but it tends to lend itself to bad code. It's hard to figure out what you're referencing when all your keys are numbers. So I recommend mysqli_fetch_assoc (be sure you're fully switched to the mysqli functions first, like mysql_connect and mysqli_query)
Second, I really dislike using extract. We need to work with the array directly. Here's how we do this
$myarray = array();
while ($rows = mysqlI_fetch_assoc($results)) {
$myarray[] = $rows;
}
echo $myarray[0]['ArrivalTime'];
So let's go over this. First, we're building an array of arrays. So we initialize our overall array. Then we want to push the rows onto this array. That's what $myarray[] does. Finally, the array we're pushing is associative, meaning all the keys of the row match up with the field names of your query.
Now, the sorting really needs to be done in your query. So let's tweak your query
$queryWaitingPatients = 'SELECT ArrivalTime, TargetTime, `Order`, Classification
FROM exams
WHERE CurrentState = "Pending"
ORDER BY TargetTime';
This way, when your PHP runs, your database now churns them out in the correct order for your array. No sorting code needed.
$arr = array();
while ($rows = mysql_fetch_array($results)) {
array_push ($arr, $row);
}
print_r($arr);
<?php
$queryWaitingPatients = ' SELECT ArrivalTime, TargetTime, Order, Classification, CurrentState
FROM exams
WHERE CurrentState = "Pending"
ORDER BY TargetTime ';
$results = mysql_query($queryWaitingPatients) or die(mysql_error());
if ($results -> num_rows < 1)
{
echo '<p>There\'s currently no patient on the waiting list.</p>';
}
else
{
while ($rows = mysqli_fetch_array($results))
{
$arrivaltime = $row['ArrivalTime'];
$targettime = $row['targettime'];
$order = $row['Order'];
$classification = $row['Classification'];
echo "Arrival: ".$arrivaltime."--Target time: ".$targettime."--Order: ".$order."--Classification: ".$classification;
}
}
echo "Done!";
//or you could put it in a json array and pass it to client side.
?>

Passing each row of a mysql query to a php array

i am running a mysql query to return all rows from a temp database, i then need to ammend some of the attributes in those rows so i am trying to return each row to an array so i can then reference the array and amend specific attributes of each row
im just stuck on how to get each row into its own array, im guessing i will need to use a 2d array for this however cannot figure out how to populate it from the mysql query into the 2d array. Im guessing it is something like i have tried below?
$result_array = array();
while ($row = mysql_fetch_assoc($res2)) {
$result_array[] = $var;
foreach($row as $key => $var) {
// Insert into array
echo $var;
}
however when trying this i am getting a notice saying:
Notice: Array to string conversion
any help pointing me in the right direction for this would be great
If I understand what you're asking for, you literally want each row from the SQL query to be a single index in the $result_array array?
If that's the case, you're already getting it with $row - you can add that directly to the array:
$result_array = array();
while ($row = mysql_fetch_assoc($res2)) {
$result_array[] = $row;
}
You can modify the values inside the array either when you're adding them to the global array, or after:
foreach ($result_array as $index => $row) {
$result_array[$index]['some_key'] = $row['some_key'] . ' [modified]';
}
Side-note (not answer specific)
I would recommend against using the old, deprecated mysql_ functions and instead favor MySQLi or PDO. Both of these are easy to use, more secure than the older methods and offer a large range of features such as prepared statements.
The above can be written with mysqli like:
if ($result = mysqli_query($connection, $query)) {
$results = array();
while ($row = mysqli_fetch_assoc($result)) {
$results = $row;
}
mysqli_free_result($result);
}

Get ID for each array element inside second array

I need to get unique ID for each array element inside second array. That ID already exist in table but I cant get them separately. URL that am getting now looks like this: http://page.com/index.php?p=view&m=area&id=173id=552id=768id=36id=217id=
I need just one ID and if first is used set second and so on.
I know that I should use mysqli or PDO and normalized tables but that later, now I need help with this.
This is the code:
$res= mysql_query("SELECT * FROM area WHERE user='$user' ORDER BY date") or die("Error: " . mysql_error());
while($row = mysql_fetch_assoc($res))
{
$id = $row['id'];
$x = array();
$parent = array();
foreach($row as $value)
{
if ($value == $id) continue;
else if ($value == $user) continue;
$result = explode(",", $value);
foreach($result as $newvalue)
{
$query = "SELECT x,firm FROM list where list.x='$newvalue'";
$result = mysql_query($query);
$r = mysql_fetch_assoc($result);
$x[] = $r['x'];
$xx = implode("id=",$x);
$parent[] = $r['firm'];
$list = implode("<a href='index.php?p=view&m=area&$xx'>", $parent)."</a>";
}
}
echo "<td><span>" . $list . "</span>/td>";
}
Thank you
first of all
$list = implode("<a h
should be
$list .= implode("<a h
That URL syntax is not the correct way to pass an array of values to a PHP script. It should use PHP array syntax for the parameter names. Also, you need separate your parameters with an ampersand (&):
http://page.com/index.php?p=view&m=area&id[]=173&id[]=552&id[]=76&8id[]=36&id[]=217
Then you can get the second one by using
$second_id = $_GET['id'][1]; // 552
etc.
FYI, you shouldn't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

How to put MySQL cell values into variables named after column names in PHP

This code selects cell values in MySQL and manually adds them to PHP variables:
$sql = "SELECT * FROM table LIMIT 0,1";
$result = mysql_query($sql);
while($rows = mysql_fetch_array($result)) {
$col1 = $rows['col1'];
$col2 = $rows['col2'];
$col3 = $rows['col3'];
.....
}
This is obviously unmanageable for multiple and large tables.
What's a better way to automatically generate the variable names and values without manually entering all the column names on all tables?
I think this is what you're looking for
$sql = "SELECT * FROM table LIMIT 0,1";
$result = mysql_query($sql);
while ($rows = mysql_fetch_array($result, MYSQL_ASSOC)) {
foreach ($rows as $key => $value) {
$$key = $value;
}
}
You could use extract() for that. But I'd keep the values in the array.
..SELECT x,y,z FROM ..
while( false!==($rows=mysql_fetch_array($result, MYSQL_ASSOC)) ) {
extract($rows);
echo $x;
...
}
Wouldn't it be more convenient having associative arrays? That way you can call your variables with their column name as you describe plus you have the benefit of having them bundled in one unit which is much better if you need to pass more than one of them to any function or view or whatever.
so I would use mysql_fetch_assoc and that's it.
I don't recommend having a variable for each row, I used to do the same to simplify writing HTML later:
echo "<tr><td>$name</td><td>$count</td></tr>";
Instead of:
echo "<tr><td>{$row['name']}</td><td>{$row['count']}</td></tr>";
Until I found a better and more readable way do it using mysql_fetch_object
while ($row = mysql_fetch_object($result)) {
:
echo "<tr><td>{$row->name}</td><td>{$row->count}</td></tr>";
:
}
Use variable variables:
Code example:
$a = 'col1';
$$a = 'somevalue';
echo $col1;
will output 'somevalue'.
http://www.php.net/manual/en/language.variables.variable.php

Categories