function loginUser($con) { $login_email = $con->real_escape_string($_POST['email']); $login_password = $con->real_escape_string(md5($_POST['password'])); $return_url = base64_decode($_POST["return_url"]); $sql = $con->query("SELECT customer_id, customer_fname, customer_lname, email, password, level FROM customer WHERE email = '" . $login_email . "' AND password = '******' "); $result = $sql->num_rows; if ($result > 0) { $row = $sql->fetch_assoc(); if ($row) { $loggedin = array('loggedinemail' => $row['email'], 'loggedinfname' => $row['customer_fname'], 'loggedinlname' => $row['customer_lname'], 'loggedinpass' => $row['password']); $_SESSION['loggedin'] = $loggedin; //print_r($_SESSION['loggedin']); if (isset($_SESSION['loggedin'])) { header('location:' . $return_url); } /* if($row['level'] == '1') { $_SESSION['adminuser'] = 0; header('location: main.php'); } elseif($row['level'] == '9') { $_SESSION['adminuser'] = 1; header('location:'. $current_url); } */ } $sql->free_result(); } else { echo 'Wrong email or password'; } dbClose($con); }
function db_query($sql, $proxyFields) { $con = dbConnect(); if ($con == null) { return null; } foreach (array_keys($proxyFields) as $key) { $value = mysqli_real_escape_string($con, $proxyFields[$key]); if (is_string($value)) { $value = "\"{$value}\""; } $sql = str_replace($key, $value, $sql); } $result = mysqli_query($con, $sql); if (!$result) { echo "has error"; print_r(debug_backtrace()); $firstCall = end(debug_backtrace()); $errMsg = "Error calling " . $firstCall["function"]; $errMsg .= " on line " . $firstCall["line"]; $errMsg .= " in " . $firstCall["file"] . ": " . mysqli_error($con); dbErrorMsg($errMsg); return false; } else { if (strpos($sql, "INSERT") !== false) { return mysqli_insert_id($con); } else { return new result($result); } } dbClose($con); }
function dbSelect($con, $data) { global $DEBUGMODE; $waypoints = array(); $distance = 0; $slat = $data['slat']; $slon = $data['slon']; $elat = $data['elat']; $elon = $data['elon']; $distance = $data['d']; $theme = $data['t']; if ($DEBUGMODE) { echo "call haversine({$slat},{$slon},{$elat},{$elon},{$theme},{$distance})"; print_r($data); } unset($data['d']); unset($data['t']); //GET THEMATIC ROUTES POIS FROM DATABASE $result = mysqli_query($con, "call haversine(" . $slat . "," . $slon . "," . $elat . "," . $elon . ",'" . $theme . "'," . $distance . ")"); while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) { $waypoints[] = $row; } sort($waypoints); filterWp($waypoints); if ($DEBUGMODE) { //echo "<pre>"; print_r($waypoints); //echo "</pre>"; } dbClose($con); }
function findVersion() { global $error, $conf_centreon; $db = dbConnect($conf_centreon['hostCentreon'], $conf_centreon['user'], $conf_centreon['password'], $conf_centreon['db'], true); $reqVersion = mysql_query("SELECT mod_release FROM modules_informations WHERE name='Discovery';"); $version = mysql_fetch_array($reqVersion); return $version['mod_release']; dbClose($db); }
function enterRecord($name, $address, $latitude, $longitude, $type) { $conn = dbconnect(); $sql = "INSERT INTO markers (name, address, lat, lng, type)\n\tVALUES(" . "'" . $name . "', " . "'" . $address . "', " . "'" . $latitude . "', " . "'" . $longitude . "', " . "'" . $type . "')"; if ($conn->query($sql) === TRUE) { echo "New record created successfully. <br />"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } dbClose($conn); }
function createModuleCombo() { dbConnect(); echo '<select name="id">'; $res = dbQuery("SELECT M.`id-module`, M.intitule, D.intitule, M.no_semestre\r\n\r\n FROM module M, diplome D \r\n\r\n WHERE D.`id-diplome` = M.`id-diplome`\r\n\r\n ORDER BY D.intitule, M.no_semestre"); while ($row = mysql_fetch_array($res)) { echo '<option value="' . $row[0] . '">' . $row[2] . ' - SEM' . $row[3] . ' - ' . $row[1] . '</option>\\n'; } echo '</select>'; dbClose(); }
function parseXMLStr() { global $HTTP_RAW_POST_DATA, $xmlResponse, $xmlMessage, $result, $con; if (dbConnect() == FALSE) { $xmlMessage .= "<status>Fail</status>"; $xmlMessage .= "<info>Could not connect to the database</info>"; return FALSE; } $fp = fopen("./Log/codes.xml", "w+"); fwrite($fp, $HTTP_RAW_POST_DATA); fclose($fp); $xmldoc = domxml_open_file("./Log/codes.xml"); $noderoot = $xmldoc->document_element(); if ($noderoot->tagname = "insert") { $childnodes = $noderoot->child_nodes(); foreach ($childnodes as $value) { if ($value->tagname == "area") { $area = $value->get_content(); } else { if ($value->tagname == "assoc_code") { $assoc_code = $value->get_content(); } else { if ($value->tagname == "paper_code") { $paper_code = $value->get_content(); } else { if ($value->tagname == "assoc_desc") { $assoc_desc = $value->get_content(); } else { if ($value->tagname == "paper_desc") { $paper_desc = $value->get_content(); } else { if ($value->tagname == "location") { $location = $value->get_content(); } } } } } } } if (dbOperations($area, $assoc_code, $paper_code, $assoc_desc, $paper_desc, $location) == FALSE) { $xmlMessage .= "<status>Fail</status>"; $xmlMessage .= "<info>Registration failed, try registering again</info>"; $result = FALSE; } } else { $xmlMessage .= "<status>Fail</status>"; $xmlMessage .= "<info>Wrong XMLRequest Format</info>"; $result = FALSE; } dbClose(); return $result; }
function getStatusById($id) { $connection = dbConnect(); $options = ['columns' => 'id, status', 'where' => ['id' => $id]]; $sql = buildSelect('status_atividade', $options); $stmt = mysqli_prepare($connection, $sql); mysqli_stmt_bind_param($stmt, 'i', $id); mysqli_stmt_execute($stmt); $resultObject = mysqli_stmt_get_result($stmt); $result = mysqli_fetch_all($resultObject, MYSQLI_ASSOC); mysqli_stmt_close($stmt); dbClose($connection); return $result[0]; }
function getUserById($id) { $connection = dbConnect(); $options = ['columns' => 'u.id_setor, u.nome, u.email, u.ativo, u.tipo, s.sigla, s.nome as setor', 'join' => [['type' => 'INNER JOIN', 'table' => 'setores s', 'columns' => 's.id = u.id_setor']], 'where' => ['u.id' => $id]]; $sql = buildSelect('usuarios u', $options); $stmt = mysqli_prepare($connection, $sql); mysqli_stmt_bind_param($stmt, 'i', $id); mysqli_stmt_execute($stmt); $resultObject = mysqli_stmt_get_result($stmt); $result = mysqli_fetch_all($resultObject, MYSQLI_ASSOC); mysqli_stmt_close($stmt); dbClose($connection); return $result[0]; }
function dbConnect() { $con = mysqli_connect(DB_HOST, DB_USERNAME, DB_PASSWORD); if (mysqli_connect_errno()) { dbErrorMsg("Failed to connect to MySQL: " . mysqli_connect_error()); return null; } $sql = "USE " . DB_DATABASE; if (!mysqli_query($con, $sql)) { dbErrorMsg("Failed to execute USE for the database: " . mysqli_error()); dbClose($con); return null; } return $con; }
function getActivitiesById($id) { $connection = dbConnect(); $options = ['columns' => 'a.id, a.id_demandante, a.id_responsavel, a.id_setor, a.id_status, a.descricao, ud.nome as demandante, s.sigla, sa.status, a.titulo, a.data, a.tempo_gasto', 'join' => [['type' => 'INNER JOIN', 'table' => 'setores s', 'columns' => 's.id = a.id_setor'], ['type' => 'INNER JOIN', 'table' => 'status_atividade sa', 'columns' => 'sa.id = a.id_status'], ['type' => 'INNER JOIN', 'table' => 'usuarios ud', 'columns' => 'ud.id = a.id_demandante']], 'where' => ['a.id' => $id]]; $sql = buildSelect('atividades a', $options); $stmt = mysqli_prepare($connection, $sql); mysqli_stmt_bind_param($stmt, 'i', $id); mysqli_stmt_execute($stmt); $resultObject = mysqli_stmt_get_result($stmt); $result = mysqli_fetch_all($resultObject, MYSQLI_ASSOC); mysqli_stmt_close($stmt); dbClose($connection); return $result[0]; }
function panicExit(&$session, $errormsg) { static $exitwiki = 0; global $dbi; if ($exitwiki) { // just in case CloseDataBase calls us exit; } $exitwiki = 1; if ($errormsg != '') { print "<P><hr noshade><h2>Schwerer Fehler</h2>\n"; print $errormsg; print "\n</body></html>"; } dbClose($session); exit; }
function panicExit(&$session, $errormsg) { static $exitwiki = 0; if ($exitwiki) { // just in case CloseDataBase calls us exit; } $exitwiki = 1; if ($errormsg != '') { echo TAG_PARAGRAPH; echo TAG_HRULE; echo TAG_H2; echo "Schwerer Fehler"; echo TAG_H2_END; echo $errormsg; echo TAG_BODY_HTML_END; } dbClose($session); exit; }
function dbUpdate($table, $modifyFields, $idName, $idValue, $idName2 = null, $idValue2 = null) { $hadError = false; $con = dbConnect(); if ($con == null) { return null; } if ($idName == "OID") { dbOrderNormalize2SQL($modifyFields); } else { if ($idName == "CID") { dbCustomerNormalize2SQL($modifyFields); } } $i = 1; $sql = "UPDATE {$table} SET "; foreach ($modifyFields as $column => $value) { // escape the incoming value to prevent SQL injection $safeValue = mysqli_real_escape_string($con, $value); // note that the PHP triple-equal is used here, it // specifies that the $value has to be explicitely null // as opposed to something that "looks" like null - like zero if ($value === null) { $sql .= "{$column} = NULL"; } else { $sql .= "{$column} = '{$safeValue}'"; } if ($i != sizeOf($modifyFields)) { $sql .= ", "; } else { $sql .= " "; } $i++; } $sql .= "WHERE {$idName} = {$idValue} "; if ($idName2 != null && $idValue2 != null) { $sql .= "AND {$idName2} = {$idValue2} "; } else { $sql .= "LIMIT 1;"; } $result = mysqli_query($con, $sql); if (!$result) { dbErrorMsg("Error during sql insert in dbUpdate({$dbname})" . mysqli_error($con)); $hadError = true; } dbClose($con); if (!$hadError) { return $idValue; } else { return 0; } }
public function addLink($url) { $link = new Link(); // On tente de charger le lien try { $link->load($url); } catch (Exception $e) { return "false"; } /* --- Database --- */ $subjectId = $this->subjectId($link->getSubjectName()); if ($subjectId == false) { $subjectId = $this->addSubject($link->getSubjectName()); } $query = "INSERT INTO link(link, name, subject_id) VALUES(\$\$" . pg_escape_string($link->getUrl()) . "\$\$, \$\$" . pg_escape_string($link->getName()) . "\$\$, " . pg_escape_string($subjectId) . ")"; try { pg_query($query); } catch (Exception $e) { return "false"; } if ($link != false) { $arr = array('link' => $link->getUrl(), 'name' => $link->getName(), 'subject_id' => $this->subjectId($link->getSubjectName())); return json_encode($arr); } else { return "false"; } dbClose($db); }
function doPost() { global $conf_centreon; $db = dbConnect($conf_centreon['hostCentreon'], $conf_centreon['user'], $conf_centreon['password'], $conf_centreon['db'], true); $error = 0; if (isset($_POST["submit"]) && $_POST["submit"] == "Add") { if (isset($_POST["os"]) && isset($_POST["template"])) { mysql_query("INSERT INTO mod_discovery_template_os_relation (os,template) VALUES('" . $_POST["os"] . "','" . $_POST["template"] . "');"); $_POST = array(); } else { $error = 1; } } if (isset($_POST["save"])) { /* Couleurs */ if (isset($_POST['host_exists']) && isset($_POST['ip_exists']) && isset($_POST['host_missing']) && isset($_POST['consider_fqdn'])) { mysql_query("UPDATE mod_discovery_config SET host_exists_color='" . $_POST["host_exists"] . "', ip_exists_color='" . $_POST["ip_exists"] . "', host_missing_color='" . $_POST["host_missing"] . "', consider_fqdn='" . $_POST['consider_fqdn'] . "'") or die(mysql_error()); } /* NMAP */ if (isset($_POST["profil_nmap"])) { mysql_query("UPDATE mod_discovery_rangeip SET nmap_profil='" . $_POST["profil_nmap"] . "' WHERE id=0;"); } if (isset($_POST["nmap_timeout"]) && is_int(intval($_POST["nmap_timeout"])) && $_POST["nmap_timeout"] >= 15000 && $_POST["nmap_timeout"] < 100000) { mysql_query("UPDATE mod_discovery_rangeip SET nmap_host_timeout='" . $_POST["nmap_timeout"] . "' WHERE id=0;"); } if (isset($_POST["nmap_timeout_rtt"]) && is_int(intval($_POST["nmap_timeout_rtt"])) && $_POST["nmap_timeout_rtt"] >= 100 && $_POST["nmap_timeout_rtt"] < 10000) { mysql_query("UPDATE mod_discovery_rangeip SET nmap_max_rtt_timeout='" . $_POST["nmap_timeout_rtt"] . "' WHERE id=0;"); } if (isset($_POST["nmap_retries"]) && is_int(intval($_POST["nmap_retries"])) && $_POST["nmap_retries"] >= 0 && $_POST["nmap_retries"] < 100) { mysql_query("UPDATE mod_discovery_rangeip SET nmap_max_retries='" . $_POST["nmap_retries"] . "' WHERE id=0;"); } /* OID */ if (isset($_POST["hostname"]) && !empty($_POST["hostname"]) && ereg("^(\\.([1-9][0-9]+|[0-9]))+\$", $_POST["hostname"])) { mysql_query("UPDATE mod_discovery_rangeip SET oid_hostname='" . $_POST["hostname"] . "' WHERE id=0;"); } if (isset($_POST["OS"]) && !empty($_POST["OS"]) && ereg("^(\\.([1-9][0-9]+|[0-9]))+\$", $_POST["OS"])) { mysql_query("UPDATE mod_discovery_rangeip SET oid_os='" . $_POST["OS"] . "' WHERE id=0;"); } /* SNMP */ if (isset($_POST["version"])) { mysql_query("UPDATE mod_discovery_rangeip SET snmp_version='" . $_POST["version"] . "' WHERE id=0;"); } if (isset($_POST["port"]) && is_int(intval($_POST["port"])) && $_POST["port"] > 0 && $_POST["port"] < 65536) { mysql_query("UPDATE mod_discovery_rangeip SET snmp_port='" . $_POST["port"] . "' WHERE id=0;"); } if (isset($_POST["retries"]) && is_int(intval($_POST["retries"])) && $_POST["retries"] >= 0 && $_POST["retries"] < 100) { mysql_query("UPDATE mod_discovery_rangeip SET snmp_retries='" . $_POST["retries"] . "' WHERE id=0;"); } if (isset($_POST["timeout"]) && is_int(intval($_POST["timeout"])) && $_POST["timeout"] > 0 && $_POST["timeout"] < 100) { mysql_query("UPDATE mod_discovery_rangeip SET snmp_timeout='" . $_POST["timeout"] . "' WHERE id=0;"); } if (isset($_POST["community"]) && !strpos($_POST["community"], " ") && !empty($_POST["community"])) { mysql_query("UPDATE mod_discovery_rangeip SET snmp_community='" . $_POST["community"] . "' WHERE id=0;"); } echo '<META HTTP-EQUIV="Refresh" CONTENT="1; URL=main.php?p=61203">'; echo '<META HTTP-EQUIV="Refresh" CONTENT="1; URL=main.php?p=61203">'; } if (isset($_POST["defaults"])) { $reqDefault = mysql_query("SELECT * FROM mod_discovery_rangeip WHERE id=-1;"); while ($default = mysql_fetch_array($reqDefault, MYSQL_ASSOC)) { mysql_query("UPDATE mod_discovery_rangeip SET nmap_profil='" . $default['nmap_profil'] . "', nmap_host_timeout='" . $default['nmap_host_timeout'] . "', nmap_max_rtt_timeout='" . $default['nmap_max_rtt_timeout'] . "', nmap_max_retries='" . $default['nmap_max_retries'] . "', snmp_port='" . $default['snmp_port'] . "', snmp_retries='" . $default['snmp_retries'] . "', snmp_timeout='" . $default['snmp_timeout'] . "', snmp_community='" . $default['snmp_community'] . "', snmp_version='" . $default['snmp_version'] . "', oid_os='" . $default['oid_os'] . "', oid_hostname='" . $default['oid_hostname'] . "' WHERE id=0;"); } } if (isset($_POST["clear"]) && $_POST["clear"] == " Clear All ") { mysql_query("DELETE FROM mod_discovery_template_os_relation"); } if (!empty($_POST)) { $templateIDList = mysql_query("SELECT id FROM mod_discovery_template_os_relation;"); while ($templateIDListData = mysql_fetch_array($templateIDList, MYSQL_ASSOC)) { $id = $templateIDListData["id"]; $postVar = $id . "_x"; if (isset($_POST[$postVar]) || isset($_POST[$id])) { mysql_query("DELETE FROM mod_discovery_template_os_relation WHERE id='" . $id . "';"); } } unset($_POST); } if (isset($_GET["id"])) { $id = $_GET["id"]; if ($id < 1 || $id > 2) { $id = 1; } doFormTab($id); doForm($id, $error); } else { doFormTab(1); doForm(1, $error); } dbClose($db); }
function message_distro_delete($user_id_target, $msg_id) { /* * Delete message from table MESSAGE_DISTRO * * URL: /server?action=message_distro_delete&user_id=<user_id_target>&msg_id=<msg_id> */ $dbh = dbConn(); $sql = 'DELETE FROM MESSAGE_DISTRO WHERE USER_ID_TARGET = ' . $user_id_target . ' AND MSG_ID = ' . $msg_id; //echo "sql: " . $sql; $qry = $dbh->prepare($sql); $qry->execute(); dbClose($dbh); // build response array $response = array('USER_ID_TARGET' => $user_id_target, 'MSG_ID = ' . $msg_id); return $response; //return(sendResponse($response)); }
public function getAllianceRank($line, $args) { list($alliance, $game) = $this->getParams($line, $args); dbConnect(); $rv = $this->fetchDetRank($alliance, $game, 'a_general'); dbClose(); if ($line['to'] == $this->ircClass->getClientConf('nick')) { $to = $line['fromNick']; } else { $to = $line['to']; } if (is_array($rv)) { $msg = "[" . BOLD . $rv[0] . BOLD . "] Alliance " . BOLD . $alliance . BOLD . ": " . BOLD . "#{$rv[1]['ranking']}" . BOLD . " (" . BOLD . number_format($rv[1]['points']) . BOLD . " points)"; } elseif ($rv == 1) { $msg = "Game ID '" . BOLD . $game . BOLD . "' not found"; } elseif ($rv == 2) { $msg = "Alliance " . BOLD . $alliance . BOLD . " not found"; } $this->ircClass->sendRaw("PRIVMSG {$to} :{$msg}"); }
// Checking to see if the config.php file exists if (!file_exists('./config.php')) { // The config file wasn't found, so quit with an error message die('<h2>The config file was not found. Contact your network admin.</h2>'); } // Getting any settings from the config file require './config.php'; // Loading the functions file require './functions.php'; // Connecting to the database and saving the connection to it for use later $databaseConnection = dbConnect($CFG['DBHost'], $CFG['DBUser'], $CFG['DBPass'], $CFG['DBName']); // Getting the session ID passed. If there isn't anything, then we can just // return 'empty' if (isset($_POST['cookie'])) { // Sanitising the query $studentID = $databaseConnection->real_escape_string($_POST['studentID']); $yearGroup = $databaseConnection->real_escape_string($_POST['yearGroup']); $house = $databaseConnection->real_escape_string($_POST['house']); $form = $databaseConnection->real_escape_string($_POST['form']); $dob = $databaseConnection->real_escape_string($_POST['dob']); // Generating the update SQL query $sql = "UPDATE `sen_info`.`tbl_student_meta` SET `YearGroup`='{$yearGroup}', `House`='{$house}', `Form`='{$form}', `DoB`='{$dob}' WHERE `StudentID`=" . $studentID; $updateResult = dbUpdate($sql, $databaseConnection); // Sending back 'success' so that the calling function knows that it has completed echo 'success'; } else { echo 'empty'; } // Closing the connection to the database dbClose($databaseConnection);
function defineNewHash($email, $hash) { $con = dbConnect(); $sql = "UPDATE usuarios SET senha = ? WHERE email = ? "; $qry = mysqli_prepare($con, $sql); mysqli_stmt_bind_param($qry, 'ss', $email, $senha); mysqli_stmt_execute($qry); if (mysqli_affected_rows($con)) { $_SESSION['success'] = 'senha do usuário alterado com sucesso.'; return true; } else { $_SESSION['error'] = 'Erro: Não foi possível alterar a senha do usuário'; return false; } mysqli_stmt_close($qry); dbClose($con); }
echo '<input name="addToCart" type="submit" value="Add to Cart" />'; echo '</form>'; } else { echo "No such record found."; //TO DO - add code that randomly selects a product "We didn't find //the product you were looking for, but check this one out..." } //echo '<a href="#">Add To Cart</a>'; //empty length array $length = array(); ?> </ul> </div> <?php } ### end while loop //free the result for next query $result->free_result(); } else { $category_sales = "There were no items in this category."; } } ### end of if $start_number dbClose($conn); ?> </div> </div> </body> </html>
function tableSpew() { $dbh = dbConn(); $sql = "SELECT * FROM USER"; echo $sql . "<br><br>"; //if (!$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) { if (!($link = $dbh)) { echo 'Could not connect to mysql'; exit; } try { // Show existing guestbook entries. //echo "<div>"; //foreach($conn->query($sql) as $row) { //echo $row['USER_ID'] . " | " . $row['FRST_NME'] . " | " . $row['LAST_NME'] . " | " . $row['EMAIL_ADDR'] . "<br>"; //$array = $sql->fetchAll(PDO::FETCH_ASSOC); //var_dum($array); //return($array); $sth = $dbh->prepare($sql); $sth->execute(); /* Fetch all of the remaining rows in the result set */ //print("Fetch all of the remaining rows in the result set: <br><br>"); //$results = $sth->fetchAll(); $results = $sth->fetchAll(PDO::FETCH_ASSOC); //print_r($result); $rowcount = $sth->rowCount(); $colcount = $sth->columnCount(); echo "rowcount: " . $rowcount . "<br>"; echo "colcount: " . $colcount . "<br><br>"; foreach ($results as $row) { print_r($row); } /*if ($results) { echo "<table>\n"; echo " <tr>\n"; echo " <th>Record #</th>\n"; //foreach(sqlsrv_field_metadata($rs) as $fieldMetadata) { //foreach(PDOStatement::getColumnMeta($rs) as $fieldMetadata) { // echo " <th>" . $fieldMetadata["Name"] . "</th>\n"; /*for ($i = 0; $i < $sth->columnCount(); $i++) { $col = $sth->getColumnMeta($i); $columns[] = $col['name']; echo " <th>" . $col['name'] . "</th>\n"; } echo " </tr>\n"; //do { while ($row = $sth->fetch(PDO::FETCH_ASSOC)) { //$results = PDO::FETCH_ASSOC($rs, PDO::FETCH_NUM); //if ($results) { if ($row) { echo " <tr>\n"; echo " <td class=\"cell\">" . ++$i . "</td>\n"; foreach ($row as $v) { if (gettype($v) == "object") { echo " <td>" . $v->format("m/d/Y H:i:s") . "</td>\n"; } elseif (is_null($v)) { echo " <td class=\"cellNull\"><div class=\"cellNull\">NULL</div></td>\n"; } elseif ($v == "") { echo " <td class=\"cellEmpty\"><div class=\"cellEmpty\"> </div></td>\n"; } else { echo " <td class=\"cell\">" . $v . "</td>\n"; } } echo " </tr>\n"; } } //while ($results); echo "</table>\n"; //sqlsrv_free_stmt($rs);*/ //} //} //echo "</div>"; } catch (PDOException $ex) { echo "An error occurred."; } dbClose($dbh); }
function create_user() { $dbh = dbConn(); // test variables //$frst_nme = "frst004"; //$last_nme = "last004"; //$email_addr = "*****@*****.**"; //$user_pw = "password004"; $disp_nme = $_POST['disp_nme']; $email_addr = $_POST['email_addr']; $user_pw = $_POST['user_pw']; $user_type = "basic"; // date creation $date = date_create(); $tz = $date->getTimezone(); $timestamp = date_format($date, 'Y-m-d H:i:s'); $timezone = $tz->getName(); // load date variables $date_effective = $timestamp; $date_modified = $timestamp; $date_expired = '9999-12-31T23:59:59'; // sql statement //$sql = "INSERT INTO USER (FRST_NME, LAST_NME, EMAIL_ADDR, USER_PW, USER_TYPE, DATE_EFFECTIVE, DATE_MODIFIED, DATE_EXPIRED) // VALUES (:FRST_NME, :LAST_NME, :EMAIL_ADDR, :USER_PW, :USER_TYPE, :DATE_EFFECTIVE, :DATE_MODIFIED, :DATE_EXPIRED)"; $sql = "INSERT INTO USER (FRST_NME, EMAIL_ADDR, USER_PW, USER_TYPE, DATE_EFFECTIVE, DATE_MODIFIED, DATE_EXPIRED) \n VALUES (:FRST_NME, :EMAIL_ADDR, :USER_PW, :USER_TYPE, :DATE_EFFECTIVE, :DATE_MODIFIED, :DATE_EXPIRED)"; $q = $dbh->prepare($sql); $new_user = array(':FRST_NME' => $disp_nme, ':EMAIL_ADDR' => $email_addr, ':USER_PW' => $user_pw, ':USER_TYPE' => $user_type, ':DATE_EFFECTIVE' => $date_effective, ':DATE_MODIFIED' => $date_modified, ':DATE_EXPIRED' => $date_expired); $q->execute($new_user); dbClose($dbh); //$foo = $new_user; //$foo = array("chad","*****@*****.**"); return $new_user; }
function featuredLolcat($number) { //connect to db $conn = dbConnect('query'); //get product info from product and image tables $sqlRandom = "SELECT * FROM product\n\t\t\t\t\t\t LEFT JOIN image\n\t\t\t\t\t\t ON product.product_id = image.product_id\n\t\t\t\t\t\t ORDER BY RAND()\n\t\t\t\t\t\t LIMIT {$number}"; //submit the SQL query to the database and get the result $result = $conn->query($sqlRandom) or die(mysqli_error()); //loop through and display categories while ($row = $result->fetch_assoc()) { //loop through the results of the product query and display product info. //Plus build the link dynamically to a detail page echo '<div class="feature">'; echo '<p><a href="product_details.php?product_id=' . $row['product_id'] . ' "> ' . $row['product_name'] . '</a></p><br/>'; echo '<a href="product_details.php?product_id=' . $row['product_id'] . ' "><img src="images/' . $row['thumb_filename'] . '" /></a>'; echo '</div>'; } $result->free_result(); dbClose($conn); }
<title>Curso Básico - PHP do Jeito Certo</title> </head> <body> <h1>Consultar usuarios</h1> <h2>Evitando SQL Injection</h2> <?php //importa o arquivo de conexão require_once 'conexao.php'; //abre a conexao com o banco $con = dbConnect(); $nome = '%Carlos%'; //consulta preparada contra SQL Injection $sql = "SELECT id, nome, login, senha, email FROM usuarios WHERE nome LIKE ?"; $result = mysqli_prepare($con, $sql); //Executa a consulta if ($result) { mysqli_stmt_bind_param($result, 's', $nome); mysqli_stmt_execute($result); mysqli_stmt_bind_result($result, $id, $nome, $login, $senha, $email); while (mysqli_stmt_fetch($result)) { echo $nome . '<br />'; } } else { trigger_error('Statement failed: ' . mysqli_stmt_error($result), E_USER_ERROR); } mysqli_stmt_close($result); //fecha a conexao dbClose($con); ?> </body> </html>
function deletePixelAndCatalogID($data) { dbConnect(); $query = "DELETE FROM `script_shop` WHERE `shop_url` = '{$data}'"; $result = mysql_query($query); if ($result) { dbClose(); return array('status' => 1); } else { dbClose(); return array('status' => 0, 'error' => 'Not delete'); } }
function main() { global $CONFIG, $SCHEDULER_LAST; print "\n"; printd("start\n"); printd("cwd: " . getcwd() . "\n"); $date = date('Ymd'); fileWrite($CONFIG['PHPDL_STACK_PIDFILE'], posix_getpid()); $n = 0; while (!$SHUTDOWN) { $n++; $dbh = dbConnect(); $scheduler = scheduler($dbh); $filesDownloading = filesDownloading($dbh); if ($SCHEDULER_LAST != $scheduler) { plog("scheduler '{$scheduler}' matched\n"); $SCHEDULER_LAST = $scheduler; } $res = mysql_query("select id from packets where archive = '0' and active = '1' and ftime = '0' order by sortnr, id;", $dbh); if (mysql_num_rows($res)) { while ($row = mysql_fetch_assoc($res)) { $packet = new dlpacket($CONFIG['DB_HOST'], $CONFIG['DB_NAME'], $CONFIG['DB_USER'], $CONFIG['DB_PASS']); if ($packet->loadById($row['id'])) { $packetDirBn = getPacketFilename($packet->get('id'), $packet->get('name')); $packetDownloadDir = 'downloads/loading/' . $packetDirBn; $packetFinishedDir = 'downloads/finished/' . $packetDirBn; if ($packet->loadFiles()) { if ($packet->filesUnfinished()) { if ($scheduler > 0) { if ($filesDownloading < $CONFIG['DL_SLOTS']) { if (!$packet->get('stime')) { $packet->save('stime', mktime()); } if ($nextfile = $packet->getFileNextUnfinished()) { while ($nextfile->get('error')) { printd("nextfile " . $nextfile->get('id') . "\n"); $nextfile = $packet->getFileNextUnfinished(); if (!$nextfile) { break; } sleep(1); } if ($nextfile) { printd("packet " . $packet->get('id') . ": download " . $nextfile->get('id') . "\n"); $sh = 'php wget.php ' . $nextfile->get('id') . ' 1>> log/wget.' . $date . '.log 2>> log/wget.' . $date . '.log &'; printd("exec '{$sh}'\n"); system($sh); sleep(1); break; } } } else { plog("no free download slots (" . $CONFIG['DL_SLOTS'] . ")\n"); } } } else { printd("packet " . $packet->get('id') . ": all files finished\n"); if (!$packet->get('stime')) { $packet->set('stime', mktime()); } $packet->save('ftime', mktime()); $packet->md5Verify(); $packet->sizeVerify(); if (!$packet->fileErrors()) { if (file_exists($packetFinishedDir)) { $files = scandir($packetDownloadDir); foreach ($files as $file) { if ($file != '.' && $file != '..' && file_exists($packetDownloadDir . '/' . $file)) { rename($packetDownloadDir . '/' . $file, $packetFinishedDir . '/' . $file); } } reset($files); rmdir($packetDownloadDir); } else { rename($packetDownloadDir, $packetFinishedDir); } } } } } unset($packet); } } else { plog("no active download\n"); } dbClose($dbh); $SHUTDOWN = shutdownCheck(); sleep(5); } shutdown(); }
function doPost() { global $error, $conf_centreon; $db = dbConnect($conf_centreon['hostCentreon'], $conf_centreon['user'], $conf_centreon['password'], $conf_centreon['db'], true); if (isset($_POST["net"])) { $nbPlage = mysql_query("SELECT count(*) FROM mod_discovery_rangeip WHERE id!=0;"); $nbPlageData = mysql_fetch_array($nbPlage); if ($nbPlageData[0] <= 15) { $tmp = explode(" ", $_POST["net"]); if (isset($tmp[1])) { if (validateIpAddress($tmp[0]) && validateMask($tmp[1])) { $netAddr = ip2Subnet($tmp[0], $tmp[1]); if (mysql_num_rows(mysql_query("SELECT * FROM mod_discovery_rangeip WHERE plage='" . $netAddr . "';")) == 0) { $poller = findPoller($netAddr, maskToCidr($tmp[1])); if (!mysql_query("INSERT INTO mod_discovery_rangeip (plage,masque,cidr,nagios_server_id) VALUES('" . $netAddr . "','" . $tmp[1] . "','" . maskToCidr($tmp[1]) . "','" . $poller["poller_id"] . "');")) { echo mysql_error(); } } else { $error = 2; } } else { $error = 1; } } else { $tmp = explode("/", $_POST["net"]); if ($tmp[1]) { if (validateIpAddress($tmp[0]) && validateCidr($tmp[1])) { $netAddr = ip2Subnet($tmp[0], cidrToMask($tmp[1])); if (mysql_num_rows(mysql_query("SELECT * FROM mod_discovery_rangeip WHERE plage='" . $netAddr . "';")) == 0) { $poller = findPoller($netAddr, $tmp[1]); if (!mysql_query("INSERT INTO mod_discovery_rangeip (plage,masque,cidr,nagios_server_id) VALUES('" . $netAddr . "','" . cidrToMask($tmp[1]) . "','" . $tmp[1] . "','" . $poller["poller_id"] . "');")) { echo mysql_error(); } } else { $error = 2; } } else { $error = 1; } } else { $error = 1; } } } else { $error = 3; } unset($_POST); } if (isset($_POST["ClearAll"])) { if ($_POST["ClearAll"] == " Clear All ") { clearArray(); } } if (isset($_GET["id"])) { clearRow($_GET["id"]); unset($_GET); } doInput($error); doFormTab($error); dbClose($db); }
if (!isset($_POST['id'])) { centeredErrorMessage(3, 3, "Aucun module selectionné, redirection..."); print "<meta http-equiv=\"refresh\" content=\"2;url=admin.php?w=responsable_module&a=del\">\n"; return; } dbConnect(); // on recupere le login du responsable a supprimer $respMod = mysql_fetch_array(dbQuery('SELECT login, apogee FROM module, enseignant WHERE enseignant.`id-enseignant` = module.`id-responsable` AND module.`id-module` = ' . $_POST['id'])); dbQuery('UPDATE `module` SET `id-responsable` = 0 WHERE `id-module` = ' . $_POST['id']); // on supprime le dossier du responsable if ($respMod['login'] != "") { sup_repertoire("../Data/" . $respMod['apogee'] . "/" . $respMod['login']); } dbClose(); centeredInfoMessage(3, 3, "Responsable supprimée avec succès, redirection..."); print "<meta http-equiv=\"refresh\" content=\"2;url=admin.php?w=responsable_module\">\n"; } else { centeredErrorMessage(3, 3, "Administration des responsables de modules : choix incorrect, redirection"); print "<meta http-equiv=\"refresh\" content=\"1;url=admin.php?w=responsable_module\">\n"; } } else { print "<br><br><br><center><u>Impossible d'utiliser cette page directement</u></center>"; } /* ** EOF responsable_module */
function delete($table, $paramConditions) { // Atribui a instrução SQL construida no método $sql = buildDelete($table, $paramConditions); $conn = dbConnect(); extract($paramConditions); $id = antiInjection($id); $stmt = mysqli_prepare($conn, $sql); mysqli_stmt_bind_param($stmt, 'i', $id); if (!mysqli_stmt_execute($stmt)) { $return = false; } else { $return = true; } mysqli_stmt_close($stmt); dbClose($conn); return $return; }