PHP mysql_query Examples

PHP mysql_query - 30 examples found. These are the top rated real world PHP examples of mysql_query extracted from open source projects. You can rate examples to help us improve the quality of examples.
Example #1
1
function getEventbriteEvents($eb_keywords, $eb_city, $eb_proximity)
{
    global $eb_app_key;
    $xml_url = "https://www.eventbrite.com/xml/event_search?...&within=50&within_unit=M&keywords=" . $eb_keywords . "&city=" . $eb_city . "&date=This+month&app_key=" . $eb_app_key;
    echo $xml_url . "<br />";
    $xml = simplexml_load_file($xml_url);
    $count = 0;
    // loop over events from eventbrite xml
    foreach ($xml->event as $event) {
        // add event if it doesn't already exist
        $event_query = mysql_query("SELECT * FROM events WHERE id_eventbrite={$event->id}") or die(mysql_error());
        if (mysql_num_rows($event_query) == 0) {
            echo $event_id . " ";
            // get event url
            foreach ($event->organizer as $organizer) {
                $event_organizer_url = $organizer->url;
            }
            // get event address
            foreach ($event->venue as $venue) {
                $event_venue_address = $venue->address;
                $event_venue_city = $venue->city;
                $event_venue_postal_code = $venue->postal_code;
            }
            // get event title
            $event_title = str_replace(array("\r\n", "\r", "\n"), ' ', $event->title);
            // add event to database
            mysql_query("INSERT INTO events (id_eventbrite, \n                                      title,\n                                      created, \n                                      organizer_name, \n                                      uri, \n                                      start_date, \n                                      end_date, \n                                      address\n                                      ) VALUES (\n                                      '{$event->id}',\n                                      '" . parseInput($event_title) . "',\n                                      '" . strtotime($event->created) . "',\n                                      '" . trim(parseInput($event->organizer->name)) . "',\n                                      '{$event_organizer_url}',\n                                      '" . strtotime($event->start_date) . "',\n                                      '" . strtotime($event->end_date) . "',\n                                      '{$event_venue_address}, {$event_venue_city}, {$event_venue_postal_code}'\n                                      )") or die(mysql_error());
        }
        $count++;
    }
}
function createMainDataElement($plan, $num, $dbConn)
{
    if ($plan['dato_principal_' . $num] != NULL) {
        $query_dato = sprintf("SELECT * FROM tipoDatosServicios WHERE id_tipoDato=%s", GetSQLValueString($plan['id_tipoDato_principal_' . $num], "int"));
        $dato = mysql_query($query_dato, $dbConn) or die(mysql_error());
        $row_dato = mysql_fetch_assoc($dato);
        $display = true;
        $label = "";
        if ($row_dato['tipo'] == "boolean") {
            if ($plan['dato_principal_' . $num] == "1") {
                $label = $row_dato['label'];
            } else {
                $display = false;
            }
        } else {
            if ($row_dato['display_label']) {
                $label = $plan['dato_principal_' . $num] . " " . $row_dato['label'];
            } else {
                $label = $plan['dato_principal_' . $num];
            }
        }
        if ($display) {
            echo "<div class='dato'>";
            echo "\t<li class='tipo_" . $plan['id_tipoDato_principal_' . $num] . "' value='" . $plan['dato_principal_' . $num] . "'>";
            echo $label;
            echo "\t</li>";
            echo "</div>";
        }
    }
    //if
}
Example #3
0
 function db($dbhost, $dbuser, $dbpw, $dbname = '', $dbcharset = 'utf8', $pconnect = 0)
 {
     if ($pconnect) {
         if (!($this->mlink = @mysql_pconnect($dbhost, $dbuser, $dbpw))) {
             $this->halt('Can not connect to MySQL');
         }
     } else {
         if (!($this->mlink = @mysql_connect($dbhost, $dbuser, $dbpw))) {
             $this->halt('Can not connect to MySQL');
         }
     }
     if ($this->version() > '4.1') {
         if ('utf-8' == strtolower($dbcharset)) {
             $dbcharset = 'utf8';
         }
         if ($dbcharset) {
             mysql_query("SET character_set_connection={$dbcharset}, character_set_results={$dbcharset}, character_set_client=binary", $this->mlink);
         }
         if ($this->version() > '5.0.1') {
             mysql_query("SET sql_mode=''", $this->mlink);
         }
     }
     if ($dbname) {
         mysql_select_db($dbname, $this->mlink);
     }
 }
Example #4
0
function getTangentText($type, $keyword)
{
    global $dbHost, $dbUser, $dbPassword, $dbName;
    $link = @mysql_connect($dbHost, $dbUser, $dbPassword);
    if (!$link) {
        die("Cannot connect : " . mysql_error());
    }
    if (!@mysql_select_db($dbName, $link)) {
        die("Cannot find database : " . mysql_error());
    }
    $result = mysql_query("SELECT sr_keywords, sr_text FROM soRandom WHERE sr_type = '" . $type . "' ORDER BY sr_ID ASC;", $link);
    $tempCounter = 0;
    while ($row = mysql_fetch_assoc($result)) {
        $pKey = "/" . $keyword . "/";
        $pos = preg_match($pKey, $row['sr_keywords']);
        //echo $pos . " is pos<br>";
        //echo $keyword;
        //echo " is keyword and this is the search return: " . $row['keywords'];
        if ($pos != 0) {
            $text[$tempCounter] = stripslashes($row["sr_text"]);
            $tempCounter++;
        }
    }
    mysql_close($link);
    //$text=htmlentities($text);
    return $text;
}
Example #5
0
 function Query($sqlString)
 {
     if (!($resourseId = @mysql_query($sqlString, $this->dbId))) {
         die("<b>MySQL</b>: Unable to execute<br /><b>SQL</b>: " . $sqlString . "<br /><b>Error (" . mysql_errno() . ")</b>: " . @mysql_error());
     }
     return $resourseId;
 }
function executesql($sql, $link)
{
    if (!mysql_query($sql, $link)) {
        die('Error: ' . mysql_error());
        exit(0);
    }
}
Example #7
0
 function dataInsert($table, $dataArray)
 {
     $fldArray = $dataArray;
     $i = 0;
     $j = 0;
     $sql .= "insert into `" . $table . "` (";
     while (list($key1, $value1) = each($fldArray)) {
         $sql .= "`" . $key1 . "`";
         $j++;
         if ($j != count($fldArray)) {
             $sql .= ",";
         }
         if ($j == count($fldArray)) {
             $sql .= ") VALUES (";
         }
     }
     while (list($key1, $value1) = each($dataArray)) {
         $sql .= "'" . $value1 . "'";
         $i++;
         if ($i != count($dataArray)) {
             $sql .= ",";
         }
         if ($i == count($dataArray)) {
             $sql .= ")";
         }
     }
     mysql_query($sql) or die(CHECK_QUERY . $sql);
     $id = mysql_insert_id();
     return $id;
 }
function checkIndividually()
{
    #----------------------------------------------------------------------
    global $competitionCondition, $chosenWhich;
    echo "<hr /><p>Checking <b>" . $chosenWhich . " individual results</b>... (wait for the result message box at the end)</p>\n";
    #--- Get all results (id, values, format, round).
    $dbResult = mysql_query("\n    SELECT\n      result.id, formatId, roundId, personId, competitionId, eventId, result.countryId,\n      value1, value2, value3, value4, value5, best, average\n    FROM Results result, Competitions competition\n    WHERE competition.id = competitionId\n      {$competitionCondition}\n    ORDER BY formatId, competitionId, eventId, roundId, result.id\n  ") or die("<p>Unable to perform database query.<br/>\n(" . mysql_error() . ")</p>\n");
    #--- Build id sets
    $countryIdSet = array_flip(getAllIDs(dbQuery("SELECT id FROM Countries")));
    $competitionIdSet = array_flip(getAllIDs(dbQuery("SELECT id FROM Competitions")));
    $eventIdSet = array_flip(getAllIDs(dbQuery("SELECT id FROM Events")));
    $formatIdSet = array_flip(getAllIDs(dbQuery("SELECT id FROM Formats")));
    $roundIdSet = array_flip(getAllIDs(dbQuery("SELECT id FROM Rounds")));
    #--- Process the results.
    $badIds = array();
    echo "<pre>\n";
    while ($result = mysql_fetch_array($dbResult)) {
        if ($error = checkResult($result, $countryIdSet, $competitionIdSet, $eventIdSet, $formatIdSet, $roundIdSet)) {
            extract($result);
            echo "Error: {$error}\nid:{$id} format:{$formatId} round:{$roundId}";
            echo " ({$value1},{$value2},{$value3},{$value4},{$value5}) best+average({$best},{$average})\n";
            echo "{$personId}   {$countryId}   {$competitionId}   {$eventId}\n\n";
            $badIds[] = $id;
        }
    }
    echo "</pre>";
    #--- Free the results.
    mysql_free_result($dbResult);
    #--- Tell the result.
    noticeBox2(!count($badIds), "All checked results pass our checking procedure successfully.<br />" . wcaDate(), count($badIds) . " errors found. Get them with this:<br /><br />SELECT * FROM Results WHERE id in (" . implode(', ', $badIds) . ")");
}
	function consulta($sql=""){
		if($sql!="")
		{
			$this->consultaId=mysql_query($sql,$this->conexionId);
			return $this->consultaId;
		}
	}
Example #10
0
function get_user_paid_expenses_test($userid_array)
{
    if (is_array($userid_array)) {
        $userids = implode(",", $userid_array);
    } else {
        $userids = $userid_array;
    }
    $sql = "SELECT user_id as userid, expense_id as exid, group_id, amount, UNIX_TIMESTAMP(expense_date) AS expensedate, \n            description FROM expenses WHERE user_id in ({$userids})";
    if (!($result = mysql_query($sql))) {
        return false;
    } else {
        $total = 0;
        while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
            $paid['users'][$row['userid']]['groups'][$row['group_id']][$row['exid']]['amount'] = $row['amount'];
            $paid['users'][$row['userid']]['groups'][$row['group_id']][$row['exid']]['expense_date'] = date("j M Y", $row['expensedate']);
            $paid['users'][$row['userid']]['groups'][$row['group_id']][$row['exid']]['description'] = $row['description'];
            $paid['users'][$row['userid']]['groups'][$row['group_id']]['group_total'] += $row['amount'];
            $paid['users'][$row['userid']]['user_total'] += $row['amount'];
            $total += $row['amount'];
            // format totals with two decimals
            $paid['users'][$row['userid']]['groups'][$row['group_id']]['total'] = number_format($paid['users'][$row['userid']]['groups'][$row['group_id']]['total'], DECIMALS, DSEP, TSEP);
            $paid['users'][$row['userid']]['total'] = number_format($paid['users'][$row['userid']]['total'], DECIMALS, DSEP, TSEP);
            $paid['users'][$row['userid']]['groups'][$row['group_id']][$row['exid']]['running_total'] += $row['amount'] + $last_running[$row['userid']][$row['group_id']];
            $last_running[$row['userid']][$row['group_id']] = $paid['users'][$row['userid']]['groups'][$row['group_id']][$row['exid']]['running_total'];
        }
        $paid['total'] = number_format($total, DECIMALS, DSEP, TSEP);
    }
    // array structure: ['users'][$userid]['groups'][$groupid][$expenseid]['amount|expense_date|description']
    return $paid;
}
Example #11
0
function get_img_old($id)
{
    $query = mysql_query("select menu_img from menus \n\t\t\t\t\t\twhere menu_id = '" . $id . "'");
    $result = mysql_fetch_array($query);
    $row = $result['menu_img'];
    return $row;
}
Example #12
0
 public function query($sql)
 {
     if ($this->link) {
         $resource = mysql_query($sql, $this->link);
         if ($resource) {
             if (is_resource($resource)) {
                 $i = 0;
                 $data = array();
                 while ($result = mysql_fetch_assoc($resource)) {
                     $data[$i] = $result;
                     $i++;
                 }
                 mysql_free_result($resource);
                 $query = new \stdClass();
                 $query->row = isset($data[0]) ? $data[0] : array();
                 $query->rows = $data;
                 $query->num_rows = $i;
                 unset($data);
                 return $query;
             } else {
                 return true;
             }
         } else {
             $trace = debug_backtrace();
             trigger_error('Error: ' . mysql_error($this->link) . '<br />Error No: ' . mysql_errno($this->link) . '<br /> Error in: <b>' . $trace[1]['file'] . '</b> line <b>' . $trace[1]['line'] . '</b><br />' . $sql);
         }
     }
 }
Example #13
0
 public function saveRatinglist()
 {
     foreach ($this->ratings as $player) {
         //Controleren of speler al bestaat + ophalen id
         $sql = "SELECT * FROM svn_leden WHERE knsb = " . $player["knsb"];
         $query = mysql_query($sql);
         if (mysql_num_rows($query) == 1) {
             $data = mysql_fetch_assoc($query);
             $player["id"] = $data["id"];
         } elseif (mysql_num_rows($query) == 0) {
             //Toevoegen van de speler
             print_r($player);
         }
         //Controleren of de rating al bestaat
         $sql = "SELECT * FROM svn_rating WHERE id = " . $player["id"] . " AND datum = '" . $this->ratingList . "'";
         $query = mysql_query($sql);
         if (mysql_num_rows($query) == 0) {
             //Toevoegen rating
             $sql = "INSERT INTO svn_rating VALUES ('',\"" . $this->ratingList . "\"," . $player["id"] . ",1," . $player["rating"] . ")";
             mysql_query($sql);
         }
     }
     $sql = "SELECT * FROM svn_leden WHERE knsb = " . $speler_geg["id"];
     $result = mysql_query($sql);
     $speler_dat = mysql_fetch_array($result);
     if ($speler_geg["rating"] != "") {
         $sql = "INSERT INTO svn_rating VALUES ('',\"" . $datum . "\"," . $speler_dat[0] . ",1," . $speler_geg["rating"] . ")";
         //echo $sql;
         mysql_query($sql);
     }
 }
Example #14
0
function insert_item()
{
    // Connect to the 'test' database
    // The parameters are defined in the teach_cn.inc file
    // These are global constants
    connect_and_select_db(DB_SERVER, DB_UN, DB_PWD, DB_NAME);
    // Get the information entered into the webpage by the user
    // These are available in the super global variable $_POST
    // This is actually an associative array, indexed by a string
    $itemNumber = mysql_real_escape_string($_POST['itemNumber']);
    $itemDescription = mysql_real_escape_string($_POST['itemDescription']);
    $category = mysql_real_escape_string($_POST['category']);
    $departmentName = mysql_real_escape_string($_POST['departmentName']);
    $purchaseCost = mysql_real_escape_string($_POST['purchaseCost']);
    $retailPrice = mysql_real_escape_string($_POST['retailPrice']);
    // Create a String consisting of the SQL command. Remember that
    // . is the concatenation operator. $varname within double quotes
    // will be evaluated by PHP
    $insertStmt = "INSERT INTO Item (ItemNumber, ItemDescription, Category, DepartmentName,\n\t\t       PurchaseCost, FullRetailPrice) values ( '{$itemNumber}','{$itemDescription}', '{$category}',\n                      '{$departmentName}', '{$purchaseCost}', '{$retailPrice}')";
    //Execute the query. The result will just be true or false
    $result = mysql_query($insertStmt);
    $message = "";
    if (!$result) {
        $message = "Error in inserting Item. <br />Item Number: {$itemNumber}<br />Item Description:\n{$itemDescription} <br />Category:\n{$category}\n<br />Department\n Name: {$departmentName} <br />" . mysql_error();
    } else {
        $message = "Data for Item inserted successfully. <br />Item Number: {$itemNumber}<br />Item Description: {$itemDescription} <br />Category: {$category} <br />Department Name: {$departmentName}";
    }
    ui_show_item_insert_result($message, $itemNumber, $itemDescription, $category, $departmentName, $purchaseCost, $retailPrice);
}
Example #15
0
 public function query($sql)
 {
     $resource = mysql_query($sql, $this->link);
     if ($resource) {
         if (is_resource($resource)) {
             $i = 0;
             $data = array();
             while ($result = mysql_fetch_assoc($resource)) {
                 $data[$i] = $result;
                 $i++;
             }
             mysql_free_result($resource);
             $query = new stdClass();
             $query->row = isset($data[0]) ? $data[0] : array();
             $query->rows = $data;
             $query->num_rows = $i;
             unset($data);
             return $query;
         } else {
             return true;
         }
     } else {
         trigger_error('Error: ' . mysql_error($this->link) . '<br />Error No: ' . mysql_errno($this->link) . '<br />' . $sql);
         exit;
     }
 }
function getGameCount()
{
    // Load game info
    $gameData = mysql_query("SELECT * FROM games");
    // Get game count and return it
    return mysql_num_rows($gameData);
}
Example #17
0
function getNumTaxtype()
{
    $sql = "select count(taxtype) from cri_ro_taxtypes where status=1";
    $result = mysql_query($sql);
    $total = mysql_fetch_array($result);
    return $total[0];
}
function candidatesArePeopleToo()
{
    $s = mysql_query("SELECT * FROM candidates");
    while ($r = mysql_fetch_array($s)) {
        $name = $r['name_cleaned'];
        $sid = $r['id'];
        if (strpos($r['url'], "http://") === 0) {
            $url = $r['url'];
        } else {
            $url = 'http://www.alegeri-2008.ro' . $r['url'];
        }
        $idString = '<a href=' . $url . '>alegeri2008</a>';
        $persons = getPersonsByName($name, $idString);
        // If I reached this point, I know for sure I either have one
        // or zero matches, there are no ambiguities.
        if (count($persons) == 0) {
            $person = addPersonToDatabase($name, $r['name_cleaned']);
        } else {
            $person = $persons[0];
            info("Found      {" . $name . "}");
        }
        // First and foremost, attempt to add this to the person's history.
        addPersonHistory($person->id, "alegeri/2008", $url);
        // Locate these people and update them in several tables now.
        // We're mainly interested in updating the ID to the new ID that
        // will be in the People database, from the previous ID that was
        // the senator's ID in the senators table.
        mysql_query("UPDATE candidates " . "SET idperson={$person->id} " . "WHERE id=" . $r['id']);
    }
}
Example #19
0
	function service($text)
	{
		$text = str_replace("\\\"","\"",$text);
		$token = explode(",",$text);
		$last_token = $token[sizeof($token)-1];
		$last_token = trim($last_token);
		$items = array();		
		$result = mysql_query("select firstName, lastName, email from employees where CONCAT(firstName,' ',lastName,' ', email) like '%$last_token%' order by email;");
		
		while($row = mysql_fetch_assoc($result))
		{

			$text = '"'.$row["firstName"]." ".$row["lastName"].'"'."<".$row["email"].">";
			$text_array = $token;
			$text_array[sizeof($text_array)-1] = $text;
			$text = join(",",$text_array);			
			
			$html = '"'.$row["firstName"]." ".$row["lastName"].'"'."[".$row["email"]."]";
			$html = preg_replace("/".$last_token."/i","<b>$last_token</b>",$html);
			$html = str_replace("[","&lt;",$html);
			$html = str_replace("]","&gt;",$html);
			
			$item = array("text"=>$text,"html"=>$html);
			array_push($items,$item);
		}
		return $items;
	}
function inserir($coluna, $valor, $tabela)
{
    //Perguntar se os dado recebidos são arrays
    if (is_array($coluna) and is_array($valor)) {
        //Verificar o numero de elementos
        if (count($coluna) == count($valor)) {
            //Montar sql
            $inserir = "INSERT INTO {$tabela}(" . implode(', ', $coluna) . ")\n                    VALUES('" . implode('\', \'', $valor) . "')";
        } else {
            return false;
        }
    } else {
        //
        //Montar sql
        $inserir = "INSERT INTO {$tabela} ({$coluna}) values ('{$valor}')";
    }
    //Conectou?
    if ($conexao = connect()) {
        //Inseriu?
        if (mysql_query($inserir, $conexao)) {
            //Fechar conexao
            fecharConexao($conexao);
            return TRUE;
        } else {
            echo "Query invalida!";
            return false;
        }
    } else {
        return FALSE;
    }
}
Example #21
0
 function connect($dbhost, $dbuser, $dbpw, $dbname = '', $dbcharset = '', $pconnect = 0, $tablepre = '', $time = 0)
 {
     $this->dbhost = $dbhost;
     $this->dbuser = $dbuser;
     $this->dbpw = $dbpw;
     $this->dbname = $dbname;
     $this->dbcharset = $dbcharset;
     $this->pconnect = $pconnect;
     $this->tablepre = $tablepre;
     $this->time = $time;
     if ($pconnect) {
         if (!($this->link = mysql_pconnect($dbhost, $dbuser, $dbpw))) {
             $this->halt('Can not connect to MySQL server');
         }
     } else {
         if (!($this->link = mysql_connect($dbhost, $dbuser, $dbpw))) {
             $this->halt('Can not connect to MySQL server');
         }
     }
     if ($this->version() > '4.1') {
         if ($dbcharset) {
             mysql_query("SET character_set_connection=" . $dbcharset . ", character_set_results=" . $dbcharset . ", character_set_client=binary", $this->link);
         }
         if ($this->version() > '5.0.1') {
             //mysql_query("SET sql_mode=''", $this->link); //关闭严格模式
         }
     }
     if ($dbname) {
         mysql_select_db($dbname, $this->link);
     }
 }
Example #22
0
function get_table_rows($table)
{
    $temp = mysql_query("SELECT SQL_CALC_FOUND_ROWS * FROM {$table} LIMIT 1");
    $result = mysql_query("SELECT FOUND_ROWS()");
    $total = mysql_fetch_row($result);
    return $total[0];
}
Example #23
0
function add_pack()
{
    $msg = new messages();
    $response = new StdClass();
    /*recibimos variables*/
    $ini = $_POST["ini"];
    $fin = $_POST["fin"];
    $inter = $_POST["inter"];
    $per = $_POST["per"];
    if ($ini == "" || $fin == "" || $inter == "") {
        $res = false;
        $mes = $msg->get_msg("e005");
    } else {
        $con = new con();
        $con->connect();
        /* ingresamos datos de la finca */
        $qry = "INSERT INTO tbl_remisiones_fisicas (rf_persona_entrega, rf_interventor, rf_dig_ini, rf_dig_fin, rf_created, rf_estado)\n\t\t\t\t\tVALUES ('" . $per . "','" . $inter . "'," . $ini . "," . $fin . "," . $_SESSION["ses_id"] . ",1);";
        $resp = mysql_query($qry);
        if (!$resp) {
            $res = false;
            $mes = $msg->get_msg("e003");
        } else {
            $res = true;
            $mes = $msg->get_msg("e004");
        }
    }
    $response->res = $res;
    $response->mes = $mes;
    echo json_encode($response);
    $con->disconnect();
}
 function RetrieveRecordArray($filter = null)
 {
     $dtoArray = array();
     $query = "SELECT * FROM cobranca WHERE removido = 0 AND " . $filter;
     if (empty($filter)) {
         $query = "SELECT * FROM cobranca WHERE removido = 0";
     }
     $recordSet = mysql_query($query, $this->mysqlConnection);
     if (!$recordSet && $this->showErrors) {
         print_r(mysql_error());
         echo '<br/><br/>';
     }
     $recordCount = mysql_num_rows($recordSet);
     if ($recordCount == 0) {
         return $dtoArray;
     }
     $index = 0;
     while ($record = mysql_fetch_array($recordSet)) {
         $dto = new ContractChargeDTO();
         $dto->id = $record['id'];
         $dto->codigoContrato = $record['contrato_id'];
         $dto->codigoSubContrato = $record['subContrato_id'];
         $dto->codigoContador = $record['contador_id'];
         $dto->modalidadeMedicao = $record['modalidadeMedicao'];
         $dto->fixo = $record['fixo'];
         $dto->variavel = $record['variavel'];
         $dto->franquia = $record['franquia'];
         $dto->individual = $record['individual'];
         $dtoArray[$index] = $dto;
         $index++;
     }
     mysql_free_result($recordSet);
     return $dtoArray;
 }
function alertnoticias_consultar($consulta,$accion)
{
	$enlace = mysql_connect('atc-nh-natsdb.nationalnet.com', 'staffcenter','XgwofvLY2ayLf') or die('No pudo conectarse : ' . mysql_error());
	mysql_select_db('staffcenter',$enlace) or die('No pudo seleccionarse la BD.');
	$sql = $consulta;
	$resultado = mysql_query($sql,$enlace) or die('La consulta fall&oacute;: ' . mysql_error());
	while ($row = mysql_fetch_array($resultado)){
	
		switch($accion)
		{
			case "noticiasdeldia":
				$idsnoticias[]=$row['idnoticia'].",".$row['titulo'];
			break;
		
		}
	}
	mysql_free_result($resultado);
	
	switch($accion)
	{
		case "noticiasdeldia":
			return $idsnoticias;
		break;
	}
}
Example #26
0
 /**
  * execute query - show be regarded as private to insulate the rest of
  * the application from sql differences
  * @access private
  */
 function query($sql)
 {
     global $CONF;
     if (is_null($this->dblink)) {
         $this->_connect();
     }
     //been passed more parameters? do some smart replacement
     if (func_num_args() > 1) {
         //query contains ? placeholders, but it's possible the
         //replacement string have ? in too, so we replace them in
         //our sql with something more unique
         $q = md5(uniqid(rand(), true));
         $sql = str_replace('?', $q, $sql);
         $args = func_get_args();
         for ($i = 1; $i <= count($args); $i++) {
             $sql = preg_replace("/{$q}/", "'" . preg_quote(mysql_real_escape_string($args[$i])) . "'", $sql, 1);
         }
         //we shouldn't have any $q left, but it will help debugging if we change them back!
         $sql = str_replace($q, '?', $sql);
     }
     $this->dbresult = mysql_query($sql, $this->dblink);
     if (!$this->dbresult) {
         die("Query failure: " . mysql_error() . "<br />{$sql}");
     }
     return $this->dbresult;
 }
Example #27
0
function print_table($table, $attributes, $callback = NULL)
{
    $attr_list_str = implode(', ', $attributes);
    $query = "SELECT {$attr_list_str} FROM {$table}";
    $result = mysql_query($query);
    $num = @mysql_numrows($result);
    echo "<table>";
    echo "<tr>";
    foreach ($attributes as $attr) {
        echo "<th>";
        echo $attr;
        echo "</th>";
    }
    echo "</tr>";
    $i = 0;
    while ($i < $num) {
        echo "<tr>";
        foreach ($attributes as $attr) {
            echo "<td>";
            if ($callback != NULL) {
                $value = mysql_result($result, $i, $attr);
                $callback($attr, $value);
            } else {
                echo mysql_result($result, $i, $attr);
            }
            echo "</td>";
        }
        echo "</tr>";
        $i++;
    }
    echo "</table>";
    return $num;
}
 function query($sql)
 {
     if (!empty($this->db) || $this->connect()) {
         return @mysql_query($sql, $this->db);
     }
     return false;
 }
 public function grabar_venta($pedido, $cliente, $tipo_documento, $nro_documento, $serie_documento)
 {
     $query = "INSERT INTO ventas(ped_id,cli_id,ven_fecha,ven_estado,ven_nrodoc,tipc_id,ven_seriedoc) VALUES ('{$pedido}','{$cliente}','" . date('y-m-d') . "','0','{$nro_documento}','{$tipo_documento}','{$serie_documento}')";
     $rs = mysql_query($query);
     $_SESSION['venta_codigo'] = mysql_insert_id();
     return $rs;
 }
 /**
  * Find pixels coords and draw these on the current image
  *
  * @param integer $image Number of the image (to be used with $this->height)
  * @return boolean Success
  **/
 function drawPixels($image)
 {
     $limit = 0;
     do {
         /** Select with limit */
         $result = mysql_query(sprintf($this->query, $image * $this->height, ($image + 1) * $this->height - 1) . ' LIMIT ' . $limit . ',' . $this->limit);
         if ($result === false) {
             return $this->raiseError('Query failed: ' . mysql_error());
         }
         $count = mysql_num_rows($result);
         while ($click = mysql_fetch_row($result)) {
             $x = (int) $click[0];
             $y = (int) ($click[1] - $image * $this->height);
             if ($x < 0 || $x >= $this->width) {
                 continue;
             }
             /** Apply a calculus for the step, with increases the speed of rendering : step = 3, then pixel is drawn at x = 2 (center of a 3x3 square) */
             $x -= $x % $this->step - $this->startStep;
             $y -= $y % $this->step - $this->startStep;
             /** Add 1 to the current color of this pixel (color which represents the sum of clicks on this pixel) */
             $color = imagecolorat($this->image, $x, $y) + 1;
             imagesetpixel($this->image, $x, $y, $color);
             $this->maxClicks = max($this->maxClicks, $color);
             if ($image === 0) {
                 /** Looking for the maximum height of click */
                 $this->maxY = max($y, $this->maxY);
             }
         }
         /** Free resultset */
         mysql_free_result($result);
         $limit += $this->limit;
     } while ($count === $this->limit);
     return true;
 }