PHP SQL query error - Unknown array column in WHERE clause - php

My page displays the name of players of a certain sports team using drop down menus. The coach can log in to pick his team and select the opposition which his team will play against.
When user has selected the team and opposition he clicks submit and the isset function is triggered.
Now I capture the values from the drop down menus and upload it to the correct table in the DB. Everything is pretty straight forward however when I click submit I get the error in the tittle. Any help would be appreciated
if ( isset($_POST['submit']) ) {
$player_ids = array_map('intval', $_REQUEST['players']);
$opponents_id = $_REQUEST['players'];
var_dump($player_ids);
var_dump($opponents_id);
$query = 'SELECT `name`, `position`
FROM `player_info`
WHERE `player_id` IN (' . implode(',', $player_ids) . ')';
$return_names = mysql_query($query) or die(mysql_error());
while ( $row = mysql_fetch_assoc($return_names) )
{
$selected[] = $row['name'];
$position[] = $row['position'];
}
$query = ("SELECT `fixture_id`
FROM `fixtures`
WHERE `fixture_id` = $opponents_id")
or die (mysql_error());
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($query))
{
$fixture_id[] = $row['fixture_id'];
}
for ($i=0; sizeof($selected) > $i; $i++){
$sql = mysql_query("INSERT INTO `team` (`selection_id`, `fixture_id`, `player_position`,`player_name`)
VALUES ('$fixture_id[$i]','$position[$i]','$selected[$i]')")
or die(mysql_error());
echo $selected[$i];
echo $position[$i];
echo $fixture_id[$i];
echo'<br>';
}

The Unknown column 'Array' in 'where clause' error means literally what it says -- you tried to put an array value into your where clause.
In this line:
$query = ("SELECT `fixture_id`
FROM `fixtures`
WHERE `fixture_id` = $opponents_id")
or die (mysql_error());
You are using the $opponents_id variable which your var_dump shows is an array containing five values. So, you need to use the IN clause and list them out (just like you did for $player_ids):
$query = ("SELECT `fixture_id`
FROM `fixtures`
WHERE `fixture_id` IN (" . implode(",", $opponents_id) . ");")
or die (mysql_error());
Note: Hopefully you are aware of the tiring subject of the mysql_* family of functions. These are being deprecated and are insecure. I wrote about it a while back: http://www.jorble.com/2012/06/you-are-vulnerable-for-sql-injection/

bodi0 is right, your $opponents_id is an array , if it must be an array so do some things like that
$opponents_id_text=implode(',',$opponents_id);
$query = ("SELECT `fixture_id`
FROM `fixtures`
WHERE `fixture_id` in ($opponents_id_text)")
or die (mysql_error());

The problem is in your second SQL query:
WHERE `fixture_id` = $opponents_id" -
Here the $opponents_id is array (it is converted automatically to array when you assign the value to it from the $_REQUEST, because the HTML component select sends the options as array).
Just implode() it also, like you did for $player_ids.

you did not specified Array properly in sql query.
when we use Arrays we have to specify array number in query

Related

Why the 2d array treatment in PHP isn't good?

I'm trying to build a 2d array in PHP with two loops using two different queries.
for some reason the page is not showing any message about any error that occurred.
It just reacts like the array doesn't exist.
Therefore I am assuming its because I did't handle the array right.
This is the code:
$stuarr= array(); ***//the 2d array initialization***
$query1 = "SELECT * FROM students WHERE userid= '$uid' ORDER BY name";
$stulist = mysqli_query($conn,$query1) or die ("cannot query the table1 " .mysqli_error($conn));
while ($students = mysqli_fetch_array($stulist)) {
${$students['name']}= array(); ******//the inside array initialization...the one that will insert to $stuarr***
$count=$_SESSION['counter'];
$sname=$students['name'];
$query3 = "SELECT * FROM ranks WHERE userid= '$uid' AND rankers='$sname' ORDER BY therate DESC";
$stur = mysqli_query($conn,$query3) or die ("cannot query the table1 " .mysqli_error($conn));
while ($sturank = mysqli_fetch_array($stur) && !$count==0) {
array_push(${$students['name']},$sturank['rated']);
$count=$count-1;
print_r(${$students['name']});
}
array_push($stuarr,${$stulist['name']});
print_r($stuarr); ***///this print is showing nothing***
}
I would love to hear your opinion about the code.
thank you!
Change
array_push($stuarr,${$stulist['name']});
into
array_push($stuarr,${$students['name']});

Query does not work when i fetch data and insert it into a table

I am trying to insert to another table the results of a select statement from another table. The select statement works but the insert statement does not work. Please help me.
$query="SELECT * FROM subject WHERE sub_code = '$enrol' ";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$csubject=$row['sub_name'];
$cday=$row['sub_day'];
$ctime=$row['sub_time'];
echo "<strong>". $csubject . "</strong>";
}
$query = mysql_query("INSERT INTO client (client_csub_code,client_csub_name,client_csub_day,client_csub_time) VALUES ('$enrol','$csubject','$cday','$ctime')");
header("Location:homeclient.php");
?>
You asked for how to do these two as one query.
This is how:
$query = mysql_query("INSERT INTO `client` ( `client_csub_code`, `client_csub_name`, `client_csub_day`, `client_csub_time` ) SELECT `sub_code`, `sub_name`, `sub_day`, `sub_time` FROM `subject` WHERE `code` = '$enrol'");
// I would also add error checking
if ( mysql_errno() )
echo mysql_error();
$query="SELECT * FROM subject WHERE sub_code = '$enrol' ";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$csubject=$row['sub_name'];
$cday=$row['sub_day'];
$ctime=$row['sub_time'];
echo "<strong>". $csubject . "</strong>";
$query = mysql_query("INSERT INTO client (client_csub_code,client_csub_name,client_csub_day,client_csub_time) VALUES ('$enrol','$csubject','$cday','$ctime')");
}
header("Location:homeclient.php");
?>
Try changing to this. Currently your query is outside of your while, it will only run once and the values of $csubject etc are always going to be the last values of your fetched results.

i want to insert data of a variable in two columns continuously

<?php
$db = mysql_connect('localhost', 'root', '') or
die ('Unable to connect. Check your connection parameters.');
mysql_select_db('my_db', $db) or die(mysql_error($db));
$query = 'SELECT
second, count(*) FROM tb_one GROUP BY second';
$result = mysql_query($query, $db) or die(mysql_error($db));
while ($row = mysql_fetch_assoc($result)) {
foreach ($row as $value) {
$queryy = 'INSERT INTO tb_two (name) VALUES ("' . $value . '")';
mysql_query($queryy, $db) or die(mysql_error($db));
}
}
?>
In this script first query is meant to select and count duplicate values(that works well), But in second query I want to insert the selected data in another table which has two columns, first column for its name and second column for its count of duplicate...If there is one column in the insert statement it works well and adds values. But I want two columns- one for name and one for its counted number of duplicates. thank you sir...I have been trying it for many days..
You can do this all in MySQL:
INSERT INTO tb_two(name, count)
SELECT second, count(*)
FROM tb_one
GROUP BY second;
Though, in other news the mysql_ functions have been deprecated. You should be using the PDO Library. Or at least the MySQL Improved Library.
Make your life easier by aliasing the duplicate column, so you can address it more easily.
Here is how:
Replace this
$query = 'SELECT second, count(*) FROM tb_one GROUP BY second';
by this:
$query = 'SELECT second, count(*) as duplicates FROM tb_one GROUP BY second';
You now have "duplicates" as the column name. Then you can use it, like this for example:
while ($row = mysql_fetch_assoc($result)) {
foreach ($row as $r) {
$queryy = "INSERT INTO tb_two SET name='".$r['second']."', duplicates='".$r['duplicates']."'";
mysql_query($queryy, $db) or die(mysql_error($db));
}
}
Try this, sorry if it has a syntax issue, I did it in notepad.
while ($row = mysql_fetch_assoc($result))
{
$query = "INSERT INTO tb_two (column1, column2) VALUES ('" . $row[0] . "', '" . $row[1] . "')";
mysql_query($query, $db) or die(mysql_error($db));
}

problem with PHP looping through members

I am having a problem with my updation script, basically if I keep the line as mysql_fetch_row then it only seems to want to insert every other member into the database, but if I change it to mysql_fetch_array then it inserts each member twice, but still not all the users from the database. I have just shown the start of the script below as I am pretty sure this must be where the error is.
Any help with this would be fantastic. Cheers.
$result = mysql_query("SELECT member_id FROM members ORDER BY member_id");
while ($member = mysql_fetch_array($result)){
foreach ($member as &$member_id){
$results_query = mysql_query("SELECT driver1 as driver1, driver2 as driver2, driver3 as driver3, driver4 as driver4, team as team, engine as engine, total_points as total FROM members WHERE member_id = '$member_id'")
or die ("Failed to update" . mysql_error());
$userteam = mysql_fetch_assoc($results_query);
//this is the bottom of the script after calculations have take place and the insert into the database//
$results_query = mysql_query("INSERT INTO member_results (member_id, track_id, driver1, driver2, driver3, driver4, team, engine, driver1_points, driver2_points, driver3_points, driver4_points, team_points, engine_points, qualifying_points, race_points, total_points)
VALUES ('$member_id', '$track', '$userteam[driver1]', '$userteam[driver2]', '$userteam[driver3]', '$userteam[driver4]', '$userteam[team]', '$userteam[engine]', '$userpoints[driver1]', '$userpoints[driver2]', '$userpoints[driver3]', '$userpoints[driver4]', '$userpoints[team]', '$userpoints[engine]', '$userpoints[qualifying]', '$userpoints[race]', '$userpoints[total]')")
or die ("Failed to update" . mysql_error());
$userteam["total"] += $userpoints["total"];
$results_query = mysql_query("UPDATE members SET total_points = '$userteam[total]' WHERE member_id = '$member_id'")
or die ("Failed to update" . mysql_error());
}
}
You shouldn't need a foreach loop when using mysql_fetch_array. The reason your query is being entered twice is because mysql_fetch_array fetches both an associative array and a numerical array for the row data, so it's looking at both of them and inserting the data twice, one for each array.
$member doesn't require a foreach for this reason. $member is just one row being pulled, not the entire data set. An associative array returns the column names as array keys.
while ($member = mysql_fetch_array($result)){
$results_query = mysql_query("SELECT driv1 as drivone, driv2 as drivtwo,
driv3 as drivthree, driv4 as drivfour, team as teamone,
eng as engone, total_points as total FROM members WHERE member_id = '$member['member_id']'") // If member_id is the column name for the ID
or die ("Failed to update" . mysql_error());
mysql_fetch_array returns multiple arrays(associative array, a numeric array, or both)
thats why its inserting twicein your foreach, and could be the reason why your script is breaking.
try var_dumping $member to see what syntax you can use to refine your foreach
see documentation here:
http://php.net/manual/en/function.mysql-fetch-array.php
Use mysql_fetch_assoc($result) or mysql_fetch_array($result, MYSQL_ASSOC);
by default mysql_fetch_array return:
the NUM indexation ( array( 0 => ..., 1 => ...)),
but also merge-in the assoc indexation ( array( 'fieldname' => ... , 'colname' => ...))
So your code should look like:
** Note that've removed the foreach.
$result = mysql_query("SELECT member_id FROM members ORDER BY member_id");
while ($member = mysql_fetch_assoc($result)){
$member_id = $member['member_id'];
//foreach ($member as &$member_id){
$results_query = mysql_query("SELECT driver1 as driver1, driver2 as driver2, driver3 as driver3, driver4 as driver4, team as team, engine as engine, total_points as total FROM members WHERE member_id = '$member_id'")
or die ("Failed to update" . mysql_error());
$userteam = mysql_fetch_assoc($results_query);
//...

SELECT limiting to only results based on a CSV list from a separate table

So I have a list of CSVs in one table. (EG: 1,3,19 )
I want to search out all of the usernames from the other table where the ids match any of those.
I feel like I should be able to do something like:
<?
$query = "SELECT player_ids FROM cast_list WHERE game='".$gameid."' ";
$result = mysql_query($query) or die(mysql_error());
$playerquery = "SELECT username,id FROM players WHERE id IN (".$result.") ORDER BY username;
$player_result = mysql_query($playerquery) or die(mysql_error());
echo "<ul>";
while ($row = mysql_fetch_array($player_result) ) {
echo "<li>".$row['username']."</li>";
}
echo "</ul>";
?>
but I can't get it to work. What am I doing wrong?
You can also use a subquery (which will be faster):
$playerquery = "SELECT username,id
FROM players
WHERE id IN (SELECT player_ids FROM cast_list WHERE game='".$gameid."')
ORDER BY username";
Btw if game is an integer field you don't have put quotes (' ') around the value.
The idea is correct, but you need to transfer the $result to an actual string array:
$game_ids = array();
while ($row = mysql_fetch_array($result) ) {
$game_ids[] = .$row[1];
}
Now using implode to convert the array to a comma separated values with a comma:
$playerquery = "SELECT username,id FROM players WHERE id IN (" . implode(",",$result) . ") ORDER BY username;

Categories