Unknown column 'E5V7D24M10Y2015' in 'where clause' - php

I have the code below to update (more 'add to') a row in a database. I have read a few very similar posts, but still can't see where I'm going wrong...
I am getting the error:
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 ''EventID' = '2' WHERE GameID = 'E2V1D24M10Y2015' AND PlayerID = '55'' at line 1
In this case, 'E5V7D24M10Y2015' is the value of $GameID. I am looking for a column called GameID where the value is E5V7D24M10Y2015, not a column of that name. Please tell me why my $sql is looking for a column named after the value it is looking for.
Each time the function runs the count($Runners) will be different and the values in each variable will be different. That is why I have the SQL in a loop.
if ($formtype == "gameresults"){
$Runners = $_POST['runners'];
$event = $_POST['event'];
$eid = $_POST['eid'];
$vid = $_POST['vid'];
$GameID = $_POST['GameID'];
$date = $_POST['date'];
$season = $_POST['season'];
$region = $_POST['region'];
$notes = $_POST['notes'];
$kev = "kev#email.com";
$email = $_POST['manager'];
$notes = wordwrap($notes,70);
$subject = ("Results for " . $event);
$tix = "";
$cashs = "";
for ($x = 1; $x < ($Runners + 1); $x++){
$ID = $_POST['ID' . $x];
$Name = $_POST['Name' .$x];
$Place = $_POST['Place'.$x];
$Points = $_POST['Points'.$x];
$Cash = $_POST['Cash'.$x];
$Ticket = $_POST['Ticket'.$x];
$vn = $_POST['vn'];
$buyin = $_POST['buyin'];
$data = array($eid,$vid,$region,$buyin,$GameID,$date,$season,$ID,$Name,$Place,$Points,$Ticket,$Cash,$Runners);
$fields = array('EventID','VenueID','Region','Buyin','GameID','Date','Season','PlayerID','Name','Position','Points','Ticket?','Cash','Runners');
for ($x = 0; $x < (count($data) - 1); $x++){
$sql = "UPDATE results SET '$fields[$x]' = '$data[$x]' WHERE GameID = '$GameID' AND PlayerID = '$ID'";
$res = mysqli_query($dbcon, $sql) or die("Update failed. <br>" . mysqli_error($dbcon));
}

You could modify your code to be more clear. I did example but I did not map all the fields so you need to adjust it.
$eid = 4;
$vid = 5;
$region = 'aa';
$buyin = 'asd';
$gameID = 5;
$date = 5;
$playerID = 10;
$fields = array(
'EventID' => $eid,
'VenueID' => $vid,
'Region' => $region,
'Buyin' => $buyin,
'GameID' => $gameID,
'PlayerID'=> $playerID,
'Date' => $date,
);
$numItems = count($fields);
$query = "UPDATE `results` SET ";
$i = 0;
foreach($fields as $name => $value) {
++$i;
if($name == 'GameID' || $name == 'PlayerID') {
continue;
}
$query .= sprintf(" `%s` = '%s'%s ", $name, $value, ($i === $numItems ? "": ","));
}
$query .= sprintf(" WHERE `GameID` = '%d' AND `PlayerID` = '%d'", $fields['GameID'], $fields['PlayerID']);
echo $query;
Fields can be maped via $key => $value and then used in foreach loop. Also using sprintf() makes is more clear to read. However, the best option would be using prepared statements.
Also you don't need to make multiple UPDATE queries, just SET more parameters in one query.

$data = array($eid,$vid,$region,$buyin,$GameID,$date,$season,$ID,$Name,$Place,$Points,$Ticket,$Cash,$Runners);
$fields = array('EventID','VenueID','Region','Buyin','GameID','Date','Season','PlayerID','Name','Position','Points','Ticket?','Cash','Runners');
for ($x = 0; $x < (count($data) - 1); $x++){
$sql = "UPDATE results SET " . $fields[$x] . " = '$data[$x]' WHERE results.GameID = $GameID AND results.PlayerID = $ID";
$res = mysqli_query($dbcon, $sql) or die("Update failed. <br>" . mysqli_error($dbcon));
}
Try this by specifying alias.

Related

UPDATE record serialized - php mysql

I have this problem, I have to update a record of a table that has the values of a serialized column. the call to the function works and passes the data correctly. I can enter the record, but I can not update. This is my code:
public function update($user_id, $array_check)
{
$arrayB = array();
$array_check = unserialize($array_check);
foreach ($array_check $key => $value) {
if($value["id"] == $array_check){
$idRow = $value["id"];
if($value["value"] == "0"){
$valueRow = "1";
}else{
$valueRow = "0";
}
}else{
$idRow = $value["id"];
$valueRow = $value["value"];
}
$row = array("id" => $idRow, "value" => $valueRow);
$arrayB[] = $row;
}
$stmt = $this->_db->prepare('UPDATE data_docs SET docs_selected = :docs_selected WHERE user_id = :user_id');
$row = $stmt->execute(array(':user_id' => $user_id, ':docs_selected' => serialize($arrayB) ) );
return $arrayB;
}
edit.
Replace this:
$stmt = $this->_db->prepare('UPDATE data_docs SET docs_selected = :docs_selected WHERE user_id = :user_id);
with:
$deseralized = serialize($arrayB);
$stmt = $this->_db->prepare('UPDATE data_docs SET docs_selected = '$deseralized ' WHERE user_id = '$user_id');

unable to change input data and db query result to array for pattern recognition

I'm unable to change an input string($prima = $_POST['id'];) and a db query result ($systemuser['id'];) into an array
which will be used for pattern matching using one single character at a time and then trying to
find a match in the database "id" row that is queried. The point is to use two-third of an id(supposedly incomplete id of a user of a system) to query and find the complete id. Please see my code. I'd appreciate some help. Thanks
I'm getting "undefined offset:0 through 9" error.
<?php
session_start();
include_once('server.php');
$error = false;
$gat = "";
$get = "";
$rt1 = "";
$rt2 = "";
$rt3 = "";
$rt4 = "";
$rt5 = "";
$rt6 = "";
$rt7 = "";
$rt8 = "";
$rt9 = "";
$rt0 = "";
if(isset($_POST['btn-login'])){
$firstname = $_POST['firstname'];
$firstname = trim($firstname);
$firstname = trim($_POST['firstname']);
$firstname = htmlspecialchars(strip_tags($firstname));
$lastname = $_POST['lastname'];
$lastname = trim($lastname);
$lastname = trim($_POST['lastname']);
$lastname = htmlspecialchars(strip_tags($lastname));
$id = $_POST['id'];
$id = trim($id);
$id = trim($_POST['id']);
$id = htmlspecialchars(strip_tags($id));
$gender = $_POST['gender'];
if(!$error) {
//search data if no errors
$query = "select * from subscribers";
$conditions = array();
if(! empty($firstname)){
$conditions[] = "firstname='$firstname'";
}
if(! empty($lastname)){
$conditions[] = "lastname='$lastname'";
}
if(! empty($gender)){
$conditions[] = "gender='$gender'";
}
$sql = $query;
if(count($conditions) > 0){
$sql .= " WHERE " . implode(' AND ', $conditions);
}
$result = mysqli_query($conn, $sql);
while($systemuser = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$systemuser['id'];
$gat = $systemuser['id'];
}
//convert user input to array
$prima = $_POST['id'];
$prima = array();
$rt1 = $prima[0];
$rt2 = $prima[1];
$rt3 = $prima[2];
$rt4 = $prima[3];
$rt5 = $prima[4];
$rt6 = $prima[5];
$rt7 = $prima[6];
$rt8 = $prima[7];
$rt9 = $prima[8];
$rt0 = $prima[9];
//retrieve and convert db data into array
$gat = array();
foreach( $gat as $get ){
$rt1 = $prima[0];
if (preg_match("/[$rt1]+/", $gat));{
$get += 1;
}
$rt2 = $prima[1];
if (preg_match("/[$rt2]+/", $gat)){
$get += 1;
}
$rt3 = $prima[2];
if (preg_match("/[$rt3]+/", $gat)){
$get += 1;
}
$rt4 = $prima[3];
if (preg_match("/[$rt4]+/", $gat)){
$get += 1;
}
$rt5 = $prima[4];
if (preg_match("/[$rt5]+/", $gat)){
$get += 1;
}
$rt6 = $prima[5];
if (preg_match("/[$rt6]+/", $gat)){
$get += 1;
}
$rt7 = $prima[6];
if (preg_match("/[$rt7]+/", $gat)){
$get += 1;
}
$rt8 = $prima[7];
if (preg_match("/[$rt8]+/", $gat)){
$get += 1;
}
$rt9 = $prima[8];
if (preg_match("/[$rt9]+/", $gat)){
$get += 1;
}
$rt0 = $prima[9];
if (preg_match("/[$rt0]+/", $gat)){
$get += 1;
}
if ($get > 9){
echo 'match found!';
}
else{
echo 'match not found!';
}
}
}
}
?>
I started to refactor but there is just too much that is wrong.
You are getting that Undefined offset: 0 notice because...
<?php
$prima = array();
$rt1 = $prima[0];
Is referencing offset zero on an empty array. The code makes no sense. You seem to frequently assign a value and then overwrite in on the next line.
FWIW: strings in PHP can behave much like an array...
UPDATE:
I'm a little confused about crux here honestly. If I wanted to reference the first and second letters in a string I would do:
$str = "I like PHP";
$firstLetter = (isset($str[0])) ? $str[0] : '';
$secondLetter = (isset($str[1])) ? $str[1] : '';
See if you can follow this example:
$str = 'I like PHP';
for ($i=0; $i<strlen($str); $i++) {
echo $str[$i] . "|";
}
And then... are you looking to do a WHERE foo LIKE 'a%' type query? A "wildcard" search?

How do i verify query from mysql database before outputing record

In my code am trying to verify if query is true before outputing result i have tried:
require("init.php");
if(empty($_GET["book"]) && empty($_GET["url"])) {
$_SESSION["msg"] = 'Request not valid';
header("location:obinnaa.php");
}
if(isset($_GET["book"]) && isset($_GET["url"])) {
$book = $_GET['book'];
$url = $_GET['url'];
$drs = urldecode("$url");
$txt = encrypt_decrypt('decrypt', $book);
if(!preg_match('/(proc)/i', $url)) {
$_SESSION["msg"] = 'ticket printer has faild';
header("location:obinnaa.php");
exit();
} else {
$ql = mysqli_query($conn, "select * from books where book='$txt' AND used='loading'");
$count = mysqli_num_rows($sql);
if($count < 1) {
$_SESSION["msg"] = 'Transation has oready been made by a customer please check and try again';
header("location:obinnaa.php");
exit();
}
while($riow = mysqli_fetch_assoc($ql)) {
$id = $riow["id"];
$tqty = $riow["quantity"];
for($b = 0; $b < $tqty; $b++) {
$run = rand_string(5);
$dua .= $run;
}
}
$sql = mysqli_query($conn, "select * from books where book='$txt' AND used='loading'");
$split = $dua;
$show_plit = str_split($split, 5);
$b = 0;
while($row = mysqli_fetch_assoc($sql)) {
$id = $row["id"];
$qty = $row["quantity"];
$oldB = $b;
$am = " ";
for(; $b < $oldB + $qty; $b++) {
$am .= "$show_plit[$b]";
$lek = mysqli_query($conn, "UPDATE books SET ticket='$am' WHERE id=$id");
}
if($lek) {
$adr = urlencode($adr = "http://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
$ty = encrypt_decrypt("encrypt", $txt);
$vars = array(
"book" => $ty,
"url" => $adr
);
$querystring = http_build_query($vars);
$adr = "viewbuy.php?" . $querystring;
header("location: $adr");
} else {
$_SESSION["msg"] = 'Transation failed unknow error';
header("location:obinnaa.php");
}
}
}
}
but i get to
$_SESSION["msg"]='Transation has oready been made by a customer please check and try again
even when the query is right what are mine doing wrong.
Check your return variable name from the query. You have $ql when it should be $sql.
$sql = mysqli_query($conn, "select * from books where book='$txt' AND used='loading'");
$count = mysqli_num_rows($sql);
A good IDE would flag this. NetBeans is a good free one.
Public Service Announcement:
NEVER build SQL queries straight from a URL parameter. Always sanitize your inputs and (better yet) use parameterized queries for your SQL calls. You can Google these topics for more info.

error when I add break to foreach loop

Okay, this is really frustrating me and I don't know why. I have been scouring the internet for at least two days trying to figure out the problem. I am trying to pull xp amount for a certain skill for all the names stored in the database. It echoed the specified xp for all the users in the database, but was repeating the values with an undefined index. Even though that error is there it still prints the values. I researched the internet and found that break will stop the repeating, but when I add the break it then wont print the values and just gives me the undefined index. THe index does exist.
$sql = "SELECT rsn FROM users";
$qry = $conn->prepare($sql);
$qry->execute();
while($row = $qry->fetch(PDO::FETCH_ASSOC)) {
$rsn = $row['rsn'];
$hs = file_get_contents("http://hiscore.runescape.com/index_lite.ws?player=". $rsn);
$hs = explode("\n",$hs);
$skills = array("Overall","Attack","Defence","Strength","Constitution","Ranged","Prayer","Magic","Cooking","Woodcutting","Fletching","Fishing","Firemaking","Crafting","Smithing","Mining","Herblore","Agility","Thieving","Slayer","Farming","Runecrafting","Hunter","Construction","Summoning","Dungeoneering", "Divination", "Invention");
$i = 0;
foreach(array_unique($skills) as $value){
$hs[$i] = explode(",",$hs[$i]);
$stats[$value]["rank"] = number_format($hs[$i][0]);
$stats[$value]["level"] = number_format($hs[$i][1]);
$stats[$value]["xp"] = number_format($hs[$i][2]);
$i++;
/*require_once 'tourny_config_include.php';
$sql = "UPDATE active_tourny SET xp = :xp AND from_date = :from AND to_date = :to WHERE rsn = :rsn";
$qry = $conn->prepare($sql);
$qry->execute(array(':xp' => $xp, ':rsn' => $rsn, ':to' => $tournyTo, ':from' => $tournyFrom));*/
echo $stats["Attack"]["xp"] . '<br>';
break;
}
}
$qry = $conn->prepare($sql);
$qry->execute();
while($row = $qry->fetch(PDO::FETCH_ASSOC)) {
$rsn = $row['rsn'];
$hs = file_get_contents("http://hiscore.runescape.com/index_lite.ws?player=". $rsn);
$hs = explode("\n",$hs);
$skills = array("Overall","Attack","Defence","Strength","Constitution","Ranged","Prayer","Magic","Cooking","Woodcutting","Fletching","Fishing","Firemaking","Crafting","Smithing","Mining","Herblore","Agility","Thieving","Slayer","Farming","Runecrafting","Hunter","Construction","Summoning","Dungeoneering", "Divination", "Invention");
$i = 0;
foreach($skills as $skill){
$hs[$i] = explode(",",$hs[$i]);
$stats[$skill]["rank"] = number_format($hs[$i][0]);
$stats[$skill]["level"] = number_format($hs[$i][1]);
$stats[$skill]["xp"] = number_format($hs[$i][2]);
$i++;
/*require_once 'tourny_config_include.php';
$sql = "UPDATE active_tourny SET xp = :xp AND from_date = :from AND to_date = :to WHERE rsn = :rsn";
$qry = $conn->prepare($sql);
$qry->execute(array(':xp' => $xp, ':rsn' => $rsn, ':to' => $tournyTo, ':from' => $tournyFrom));*/
// display Attack xp if available
if isset($stats["Attack"]["xp"])
echo $stats["Attack"]["xp"] . '<br>';
}
}
Wow I cannot believe that it was this simple. All I had to do is move
echo $stats["Attack"]["xp"] . '<br>';
outside the foreach loop

Dynamically create a SQL statment from passed values in PHP

I am passing a number of values to a function and then want to create a SQL query to search for these values in a database.
The input for this is drop down boxes which means that the input could be ALL or * which I want to create as a wildcard.
The problem is that you cannot do:
$result = mysql_query("SELECT * FROM table WHERE something1='$something1' AND something2='*'") or die(mysql_error());
I have made a start but cannot figure out the logic loop to make it work. This is what I have so far:
public function search($something1, $something2, $something3, $something4, $something5) {
//create query
$query = "SELECT * FROM users";
if ($something1== null and $something2== null and $something3== null and $something4== null and $something5== null) {
//search all users
break
} else {
//append where
$query = $query . " WHERE ";
if ($something1!= null) {
$query = $query . "something1='$something1'"
}
if ($something2!= null) {
$query = $query . "something2='$something2'"
}
if ($something3!= null) {
$query = $query . "something3='$something3'"
}
if ($something4!= null) {
$query = $query . "something4='$something4'"
}
if ($something5!= null) {
$query = $query . "something5='$something5'"
}
$uuid = uniqid('', true);
$result = mysql_query($query) or die(mysql_error());
}
The problem with this is that it only works in sequence. If someone enters for example something3 first then it wont add the AND in the correct place.
Any help greatly appreciated.
I would do something like this
criteria = null
if ($something1!= null) {
if($criteria != null)
{
$criteria = $criteria . " AND something1='$something1'"
}
else
{
$criteria = $criteria . " something1='$something1'"
}
}
... other criteria
$query = $query . $criteria
try with array.
function search($somethings){
$query = "SELECT * FROM users";
$filters = '';
if(is_array($somethings)){
$i = 0;
foreach($somethings as $key => $value){
$filters .= ($i > 0) ? " AND $key = '$value' " : " $key = '$value'";
$i++;
}
}
$uuid = uniqid('', true);
$query .= $filters;
$result = mysql_query($query) or die(mysql_error());
}
// demo
$som = array(
"something1" => "value1",
"something2" => "value2"
);
search( $som );
Here's an example of dynamically building a WHERE clause. I'm also showing using PDO and query parameters. You should stop using the deprecated mysql API and start using PDO.
public function search($something1, $something2, $something3, $something4, $something5)
{
$terms = array();
$values = array();
if (isset($something1)) {
$terms[] = "something1 = ?";
$values[] = $something1;
}
if (isset($something2)) {
$terms[] = "something2 = ?";
$values[] = $something2;
}
if (isset($something3)) {
$terms[] = "something3 = ?";
$values[] = $something3;
}
if (isset($something4)) {
$terms[] = "something4 = ?";
$values[] = $something4;
}
if (isset($something5)) {
$terms[] = "something5 = ?";
$values[] = $something5;
}
$query = "SELECT * FROM users ";
if ($terms) {
$query .= " WHERE " . join(" AND ", $terms);
}
if (defined('DEBUG') && DEBUG==1) {
print $query . "\n";
print_r($values);
exit();
}
$stmt = $pdo->prepare($query);
if ($stmt === false) { die(print_r($pdo->errorInfo(), true)); }
$status = $stmt->execute($values);
if ($status === false) { die(print_r($stmt->errorInfo(), true)); }
}
I've tested the above and it works. If I pass any non-null value for any of the five function arguments, it creates a WHERE clause for only the terms that are non-null.
Test with:
define('DEBUG', 1);
search('one', 'two', null, null, 'five');
Output of this test is:
SELECT * FROM users WHERE something1 = ? AND something2 = ? AND something5 = ?
Array
(
[0] => one
[1] => two
[2] => five
)
If you need this to be more dynamic, pass an array to the function instead of individual arguments.

Categories