array access won't increment in php mysql - php

I'm trying to update the first column in a table with new values, using something like what I've got below..
the problem is that the $userTemp variable is not incrementing in mysql but it seems to run through the elements in an array (as expected) within a php for loop. however in mysql_query this does not seem to be reflecting? I don't quite understand why as when I echo $userTemp before the mysql_query it shows that it is incrementing correctly. the query is run through the function queryMysqlPopulate($userTemp,$row[0]); but the argument does not seem to get passed to the function. however after the function call running another echo for $userTemp shows that the value has infact incremented.
like seriously?! please could someone enlighten me as to why? does session control have something to do with this?
any help is greatly appreciated!
PS. this is not the full program I've just snipped the parts that are applicable, so as not to take up too much of your time (hope that helps).
$userlogins = array('c001','d001','dj001','ed001',
'k001','nr001','ol001','pt001',
'py001','rx001','s005');
if (tableExists('mytable'))
{
$tempQuery = queryMysql("SELECT username FROM students");
$numRows = mysql_num_rows($tempQuery);
for ($j = 0 ; $j < $numRows ; ++$j)
{
$userTemp = "$userlogins[$j]";
echo $userTemp;
$row = mysql_fetch_row($tempQuery);
queryMysqlPopulate($userTemp,$row[0]);
echo $userTemp;
}
}
and the function
function queryMysqlPopulate($tempLogin, $tempRow){
$result = mysql_query("UPDATE mytable SET username='$tempLogin' WHERE username='$tempRow'") or die(mysql_error());
return $result;}
i can't answer my own question cause i#M a newbie :P
so edit insteaD:
No problems this works fine, although it's not exactly what i was looking for as it's not exactly array access, but explicitly referring to a field by it's value :(
for($i = 0; $i < $loops; ++$i)
{
queryMysql("INSERT INTO $name VALUES" .
"('hi$i', 'there', 'all', 'you', 'cats')");
}
then changing update ...set to
if (tableExists('mytable'))
{
$tempQuery = queryMysql("SELECT username FROM mytable");
$numRows = mysql_num_rows($tempQuery);
for ($j = 0 ; $j < $numRows ; ++$j)
{
$userTemp = "$userlogins[$j]";
echo $userTemp;
$row = mysql_fetch_row($tempQuery);
queryMysqlPopulate($userTemp,'hi'.$j);
echo $userTemp;
//echo $row[0];
}
//echo tableExists('none');
}
I'd still prefer to do this by array access i.e. accessing the first field of the first column by element number in the update ... set mysql query. so any help with that is greatly appreciated.

Related

mysqli query returns true but fetch_assoc doesn't work

I am using PHP and MySQL (mysqli) in XAMPP, I have a drop down, and the user must choose one, then a query is used to find the id of the value that has been chosen but it does not work. I have already done this three more times and it worked but this one doesn't.
$sql = "SELECT foo_id FROM foo_table
WHERE foo_name = 'bar';";
$res = $conn->query($sql);
for ($i = 0; $i < 500; $i++) {
$row = $res->fetch_assoc();
echo $row[row["foo_id"]]
}
The problem is that fetch_assoc does not return anything even though the $res variable returns true.
Edit: I forgot to mention that running the query in phpmyadmin returns results normally.
I am not sure why you are iterating over 500 times? this doesn't make sense.
Best practice to retrieve the data from DB is
$sql = "SELECT foo_id FROM foo_table
WHERE foo_name = 'bar'";
$res = $conn->query($sql);
if ($res->num_rows > 0) {
// output data of each row
while($row = $res->fetch_assoc()) {
echo $row["foo_id"];
}
}
OR
$foo_id = ''
if ($res->num_rows > 0) {
// output data of each row
while($row = $res->fetch_assoc()) {
$foo_id = $row["foo_id"];
}
}
for ($i = 0; $i < 500; $i++) {
echo $foo_id;
}
I found the solution, the problem is that the real database used greek characters in the records and the database had to be set to utf8-bin, after doing so, it worked.

Understanding mysqli_fetch_array()

Is there a way to make the code below cleaner?
I wanted to access the rows of $query4week like this: $query4week[0].
But mysqli_query() returns an Object on which I don't know how to access its particular rows. So, using fetch_array and a for loop I decided to create my own index.
$sql2 = "SELECT * FROM meals ORDER BY RAND() LIMIT 7";
$query4week = mysqli_query($con, $sql2) or die(mysqli_error($con));
for ($i = 0; $result = mysqli_fetch_array($query4week, MYSQLI_ASSOC); $i++)
{
$meal4week[$i] = $result['meal'];
}
I am still learning PHP and yet quite weak with OOP topics, please be patient :-)
Do it in this way
$i = 0;
while ($result = mysqli_fetch_array($query4week, MYSQLI_ASSOC))
{
$meal4week[$i] = $result['meal'];
$i++;
}
should work.
You shouldn't need a for loop if your fetching an associative array.
$i = 0;
while($row = mysqli_fetch_array($query4week, MYSQLI_ASSOC))
{
$meal4week[$i] = $row['meal'];
$i++;
}
There are already some perfectly reasonable answers here, but this is a little long for a comment. If all you are creating is a numerically indexed array starting with index 0, you don't need to explicitly define the index.
while($row = mysqli_fetch_array($query4week, MYSQLI_ASSOC)) {
$meal4week[] = $row['meal'];
}
should work just fine. No $i necessary.
mysqli_query returns you a resource which represents the query result. You need to use the mysql_fetch_* functions to iterate over the result row by row. So yes, you need some kind of loop, if you are interested in more than the first row.

Sort mysql result in php

When I use the following code:
$result = queryMysql("SELECT * FROM games ORDER BY game ASC");
$num = $result->num_rows;
for ($j = 0 ; $j < $num ; ++$j)
{
$row = $result->fetch_array(MYSQLI_ASSOC);
echo "<input type='checkbox' name='game' value='$row['id']'>$row['game']<br>";
}
the result is not shown alphabetically. it has Destiny first, and Battlefield last. Destiny has ID 1, and Battlefield has ID 11.
Why isn´t it being sorted? If I use the command in PhpMyAdmin I get the list back sorted.
(Sorry if this is too simple, but I didn´t find any solutions here. All refered to use ORDER BY, but that´s not working).
New code changed to:
$result = queryMysql("SELECT * FROM games ORDER BY game ASC");
while ($row = $result->fetch_array(MYSQLI_ASSOC))
{
echo "<input type='checkbox' name='game' value='$row['id']'>$row['game']<br>";
}
Still not working. Could this be a server error?
Not sure what happened here, but after 8 hours of sleep and I reload the page, it´s sorting as it should (still using Maximus2012´s example).
I guess it must have been a server glitch, since I didn´t change the code while sleeping.
I´ll give creds to Maximus2012 for his quick and good responds!
(and thanks to all others too ofcourse!)
Replace this :
$num = $result->num_rows;
for ($j = 0 ; $j < $num ; ++$j)
{
$row = $result->fetch_array(MYSQLI_ASSOC);
echo "<input type='checkbox' name='game' value='$row['id']'>$row['game']<br>";
}
with this: (get rid of $num and the for loop)
while ($row = $result->fetch_array(MYSQLI_ASSOC))
{
echo "<input type='checkbox' name='game' value='$row['id']'>$row['game']<br>";
}
and see if that works. You don't need for loop since you are not using the $j variable anywhere anyway. This answer is based on the assumption that your MySQL query is giving you correct result.
It looks like you are sorting by whatever your first field game rather than the field that actually contains the name of your game (can't tell what that is from the information given).
Just sort the proper field.
Run SET NAMES utf8; Be sure you have collation utf8_general_ci in your table and field. Check that field game has character set utf8
Then run this query just before your own query and see if this helps.
function queryMysql($query)
{
global $connection;
$connection->query("SET NAMES utf8");
$result = $connection->query($query);
if (!$result) die($connection->error);
return $result;
}

How to echo columns 1...n from mysql database except the first one in php?

I have a table with par_id and columns (par1-5) 1 up to 5, but I'm trying to have my php function below to echo any number of columns
//-------------------------------------- get about ----------------------------------------------
function getAbout($option){
$div = array();
$sql_st = "undefined";
if($option == "about")
$sql_st = "SELECT * FROM `about` where par_id='1'";
// connect to database
mysql_connect($_SESSION['dbSever'],$_SESSION['dbUser'],$_SESSION['dbPass']) or die(mysql_error());
mysql_select_db($_SESSION['tblName']) or die(mysql_error());
$result = mysql_query($sql_st) or die(mysql_error()."<br/>".$sql_st);
$num_rows = mysql_num_rows($result);
while ($row = mysql_fetch_array($result) ){
// not sure what to do here
}
// disconnect
mysql_close();
return $div;
}
From your question title I'm assuming you have an ID maybe in your first column and you want to keep that from being printed. You could try something like:
$numberOfColumns = mysql_num_fields($result);
while ($row = mysql_fetch_array($result) ){
for ($i = 1; $i < $numberOfColumns; $i++){
echo $row[$i];
}
}
The $i iterator in the for loop is initiated with value of 1 because PHP handles (like many languages) arrays as zero-based, which means that the first element is referenced by $row[0] (as in this example) - by starting the loop at one and going for as many elements there are in the array, you're effectively grabbing all elements except for the first one.
A really simple one would be to have a flag like so:
$skippedFirstRow = false;
while ($row = mysql_fetch_array($result)){
if(!$skippedFirstRow) {
//do whatever you want here
}
$skippedFirstRow = true;
}
However, keep in mind that this is just a quick hack for what you want and considering your code, but it is not an elegant solution.

If Statements Inside For Loops = Problems

For some reason my if statements don't work as expected.
$query = "SELECT title FROM blog";
$result = mysql_query($query);
$rows = mysql_num_rows($result);
for ($j = 0; $j < $rows; ++$j)
{
if (isset($_POST['$j']))
{
$id = mysql_real_escape_string($_POST['id']);
$query = "DELETE FROM blog WHERE id='$id'";
mysql_query($query);
echo 'Deleted post.. ';
echo 'Click here';
}
else
{
echo 'Failed!';
}
}
What happens is that "Deleted post.." and the "link" get echoed the number of rows I have in my table blog. Only one row in my table gets deleted though which is what I want. One button gets pressed each time, so shouldn't it echo "Deleted post.." only one time and "Failed!" the rest of the times? Thanks =)
Note: I'm still new to programming, sorry if the question is stupid.
Note 2: I have many buttons on another page.. they are labeled by numbers '1, 2, 3' etc.
change:
$_POST['$j'] // here, due to the single quotes you're
// always testing for the literal `$j`, and not
// the value of current loop iteration.
to:
$_POST[$j]
Variables are not parsed in single quotes, you need to use double quotes. isset($_POST["$j"]
Also you are trying to delete the same record over and over in the loop, you're checking if $_POST["$j"] is set but using $_POST['id']
Try this
<?php
$query = "SELECT title FROM blog";
$result = mysql_query($query);
$rows = mysql_num_rows($result);
for ($j = 0; $j < $rows; ++$j)
{
if (isset($_POST[$j]))
{
$id = mysql_real_escape_string($_POST['id']);
$query = "DELETE FROM blog WHERE id='" .$id ."'";
mysql_query($query);
echo 'Deleted post.. ';
echo 'Click here';
}
else
{
echo 'Failed!';
}
}
?>
The problem is that you're looping through $_POST[0] to $_POST[Whatever], but you're only deleting where ID = $_POST['id']. $_POST['id'] never changes. Even though you're looping over and over, you're still trying to delete the same row for each loop
It will not work because the POST or GET or REQUEST only takes what was posted to the current page from the previous page.
You need to POST some variable to some page then only is it that you can use the $_POST['j']. You cannot use the variables in the current page inside POST
If you are posting j from some other page then I think you can use this condition instead of using like that
$j = $_POST['j'];
if(isset($_POST['j'])){
for($j = 0; $j < $rows; ++$j){
//your code
}
}
Hope this helps

Categories