help with php FOREACH loop - php

can some please tell me what's wrong with the bellow foreach php loop.
foreach ($_POST[sortlist] as $key => $value)
{
$sql = "UPDATE sortable
SET color_order = " . mysql_real_escape_string($key) . "
WHERE id = " . mysql_real_escape_string($value);
$result = mysql_query($sql) or die(mysql_error());
}
I keep getting warning: invalid argument suplied foreach() in ....
when i upload to server
Thanks

$_POST['sortlist'] is probably not an array. Try print_r($_POST) to see what do you have there.

Try change $_POST[sortlist] to $_POST['sortlist']

I'm assuming that $_POST[sortlist] is not an array. This is probably what you are trying to do:
foreach ($_POST as $varname => $varvalue) {
$sql = "update sortable set color_order = ".mysql_real_escape_string($varname)." where id = ".mysql_real_escape_string($varvalue);
$result = mysql_query($sql) or die(mysql_error());
}
Or if $_POST['sortlist'] is an array, try this:
foreach ($_POST['sortlist'] as $varname => $varvalue) {
$sql = "update sortable set color_order = ".mysql_real_escape_string($varname)." where id = ".mysql_real_escape_string($varvalue);
$result = mysql_query($sql) or die(mysql_error());
}

A tip: the error message refers to the foreach line. That only reads from one variable, $_POST[sortlist], which isn't modified inside the loop. So you can ignore all the SQL stuff; it's not relevant to your problem. Reduce the problem to the smallest possible piece of code that still has an error. That will help you solve it.

Don't use mysql_query , its very insecure and is deprecated .
start using mysqli_query, is not as safe as PDO but will be lot better.

Please, for the love of the internet, don't built an SQL query yourself. Use PDO.

Related

Passing mysql_query to JSON file does not work

I have a small code that should convert a query to my mysql database into a json file, but it does not return anything.
I have seen this example in many places but it does not work for me
Of course I checked before the query contains rows
I appreciate the help
<?php
if (!$enlace = mysql_connect('X.X.X.X', 'xxxx', 'xxxx') or !mysql_select_db('xxxx', $enlace)) {
echo 'No pudo conectarse a mysql';
exit;
}
$sql = 'SELECT * FROM `Tabla`';
$resultado = mysql_query($sql, $enlace);
$json = array();
while($row=mysql_fetch_assoc($resultado)){
$json[]=$row;
}
echo json_encode($json);
?>
The reason for not getting anything is because you are overwriting the array variable,
also note that you need to use mysqli since mysql_ is deprecated.
Change this line:
$resultado = mysql_query($sql, $enlace);
$json = array();
while($row=mysql_fetch_assoc($resultado)){
$json=$row;
}
to:
$resultado = mysqli_query($sql, $enlace);
$json = array();
while($row=mysqli_fetch_assoc($resultado)){
$json[]=$row;
}
Fist of all use mysqli instead of mysql it is deprecated since PHP 5.5.0.
And then add the row to the array instead of overwriting it.
$json[] = $row;
for test add this line in the loop
$json = [];
while($row = mysql_fetch_assoc($resultado)){
$json[] = $row;
print_r($row);
}
If you get no output the query is not giving you any results
You may try converting to array to be sure.
while($row=mysql_fetch_assoc($resultado)){
$json[]=(array)$row;
}
and yes simple debugging is important just use var_dump() to identify the issue
var_dump(['socket:', $resultado]); $i=0;
while($row=mysql_fetch_assoc($resultado)){
$json[]=(array)$row;
var_dump([$i++, $row]);
}
exit();
And of course you should not use deprecated functions but i assume this is a learning environment or just an old working system

Update over 100 fields in mysql

i have 181 fields in my database named S1, S2....S181. I want to update these fields using values from inputs WITH name="S1", .....NAME="S181".
MY CODE IS
$S1=$_POST['S1'];
...
...
$S181=$_POST['S181'];
$sql=mysqli_query($conn,"update 'cap' set S1='$S1'......S181='$S181'")
I am trying something like
for ($i = 1; $i<=181; $i++ ) {
$(S$i)=$_POST['S$i'];
$sql = mysqli_query($conn, "UPDATE `cap4a` SET
S$i='$(S$i)'
WHERE IDID=".$id) or die (mysqli_error($conn));
}
Is there something wrong in the way I use S$i, because I am getting errors:
"Parse error: syntax error, unexpected '(', expecting variable (T_VARIABLE) or '$' in C:\xampp1\htdocs\update_cap4a.php on line 5" ?
I don't think it's a good idea to run 181 queries to alter the same row as you do. Instead, run one query that makes all required changes to the row. The code below will work for you:
$id = (int)$_POST['id'];//remove (int) if id IDID is a string
$snippets = [];//holds little snippets eg: S1='value1'
for($i=1;$i<=181;$i++){
$varname = "S$i"; //S1...S181
if(!isset($_POST[$varname])) continue;
$snippets[] = " $varname='$_POST[$varname]' ";
}
$sql = '"UPDATE cap SET '.implode(",",$snippets)." WHERE IDID=$id";
$result = mysqli_query($conn,$sql) or die (mysqli_error($conn));
I don't cover it in this snippet but you need to add at least two things before using this in production:
Proper error handling, for when your query fails
Prepared statements or escaped values to protect against SQL injection
Is there something wrong in the way I use S$i
To dynamically create a variable named S10 and set it to 'value' when $i=10, do:
$varname = "S$i";
$$varname = 'value'; // $$varname can also be referred to as $S10
See Variable Variables in the docs.
I would gave done it this way:
for ($i = 1; $i<=181; $i++) {
$key = 'S'.$i;
$value = $_POST[$key];
$update[] = "`{$key}` = '".$value."'";
$sql = mysqli_query($conn, "UPDATE `cap4a` SET ".join(",",$update)."
WHERE IDID=".$id) or die (mysqli_error($conn));
}

Strange Illegal string offset in foreach from mysqli_fetch_array() and mysqli_fetch_assoc()

I am just testing out a data set I am looking to return from the DB.
I am running this in command line mode. When I var_dump() the data, I can see data being returned, but when I try to traverse the array, which has duplicate data in it, I get the warning message below and can not print the array item.
I am sure to some that is obvious to some, but I do not know why this is happening. I am sure I am doing something wrong here...but what?
Consider:
$link = mysqli_connect("localhost","username","password","mydatabase") or die("Error " . mysqli_error($link));
$query = "SELECT * FROM citizen_application";
$execute = $query or die("Error in the consult.." . mysqli_error($link));
//execute the query.
$result = $link->query($execute);
$data = mysqli_fetch_array($result); // also tried mysqli_fetch_assoc() and the issue persists
//display information:
//var_dump($data); //This show duplicates in the array returned???
foreach($data as $data_unit){
print_r($data_unit["dob"]."\r");
}
The warning in the logs:
Illegal string offset 'dob'
There seems to be no way to do this with a foreach() when running the script in command line mode. But I found a solution below that gives me what I was looking for:
while($data = mysqli_fetch_assoc($result)) {
print_r($data["dob"]."\n");
}
I noticed all the examples in the documentation where doing this way. I thought it was just a preference. It does not seem so. I hope this helps someone else, because this was quite irritating. You used to be able to do this easily with the previous mysql functions.
mysqli_fetch_array returns an array, you're traversing the array with the foreach, $data_unit will most likely be a single element and not an array... try just
foreach($data as $data_unit){
echo $data_unit."\r";
}
or use mysqli_fetch_assoc() and try
foreach($data as $fieldname => $data_unit){
echo "$fieldname = $data_unit\r";
}

using form variables for mysql query

I'm trying to fetch a result from a mysql table using two form variables namely $sessionID and $semesterID. I used the following code and it seems to have an error in the sql syntax
<?php
...
mysql_select_db($database_connChePortal, $connChePortal);
$query_rsRegcourses =sprintf("SELECT * FROM VW_reg vwr WHERE vwr.sessionID=%s AND vwr.semesterID=%s",$sessionID,$semesterID);
$rsRegcourses = mysql_query($query_rsRegcourses, $connChePortal) or die(mysql_error());
$row_rsRegcourses = mysql_fetch_assoc($rsRegcourses);
$totalRows_rsRegcourses = mysql_num_rows($rsRegcourses);
print_r($query_rsRegcourses); die;
...
?>
I tried running the query and I have the following error report
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AND vwr.semesterID=' at line 1
thanks
I think you should surround your variable with single quotes '' please change as follow
"SELECT * FROM VW_reg vwr WHERE vwr.sessionID='%s' AND vwr.semesterID='%s'"
Put the %s in single quotes like this
"SELECT * FROM VW_reg vwr WHERE vwr.sessionID='%s' AND vwr.semesterID='%s'",$sessionID,$semesterID);
To insert a variable into query, you have to properly format it.
Two other answers contains improper formatting - so, you shouldn't follow them.
To make formatting more handy, you have to encapsulate sprintf() into function like this:
function paraQuery()
{
$args = func_get_args();
$query = array_shift($args);
$query = str_replace("%s","'%s'",$query);
foreach ($args as $key => $val)
{
$args[$key] = mysql_real_escape_string($val);
}
$query = vsprintf($query, $args);
$result = mysql_query($query);
if (!$result)
{
throw new Exception(mysql_error()." [$query]");
}
return $result;
}
which would apply proper formatting and also will handle errors
Also note that your way of counting records is extremely inefficient and may cause server to hang. You have to query the only data you need. So, if you need only count - request the count only
so, the code would be
mysql_select_db($database_connChePortal, $connChePortal);
$sql = "SELECT count(*) FROM VW_reg vwr WHERE vwr.sessionID=%s AND vwr.semesterID=%s";
$res = paraQuery($sql,$sessionID,$semesterID);
$row = mysql_fetch_row($res);
print_r($row[0]); die;
it will make your query properly formatted and thus invulnerable to SQL injection
also, it seems that $semesterID is not set which may cause some problem too

php sql code, foreach warning

I have the following code, not written bymyself, but I am wondering if you could spot anything wrong with it?
$query = "SELECT * from #__properties_type where published = 1 AND parent = ".$Category_id." OR parent = 0";
$db->setQuery( $query );
$types = $db->loadObjectList();
$nP = count($types);
$mitems[0]->id=0;
$mitems[0]->name='Type';
foreach ( $types as $item ) {
$mitems[] = $item;
}
It seems to work fine but sometimes I will see a random Warning: Invalid argument supplied for foreach() in etc/etc/etc/
Any ideas?
Your loadObjectList function seems to return a non-array sometimes, maybe when the SQL query fails.
Quick fix:
if (is_array($types))
foreach ( $types as $item ) {
$mitems[] = $item;
}
but you should look for the deeper cause why the function fails, and handle the error accordingly if there is one.
It probably means your $types variable isn't being set.
This will set a PHP warning off.
Unless $mitems[0] is predefined before your code snippet, there's no way PHP can know about $mitems[0] contains an object, hence $mitems[0]->id will throw an warning.
To solve this:
$mitems[0] = new YourObject();
$mitems[0]->id=0;
$mitems[0]->name='Type';

Categories