Upon a user entering x.com/y.php?username=z, I would like to take that username as an argument to generate an ID and associate it with that username by writing it to a table. However, so far I've been getting nothing but 500 errors when I input a username.
(Third day into this)
<?php
error_reporting(E_ALL);
$con = mysql_connect("localhost","&&&&&","&&&&&");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("wp", $con);
Function RandomString()
{
$characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
for ($i = 0; $i < 20; $i++)
{
$randstring.= $characters[rand(0, strlen($characters))];
}
return $randstring;
}
if (isset($_GET["username"]) && !empty($_GET["username"]))
{
$username = $_GET['username'];
$usercheck = mysql_query("SELECT COUNT(*) AS a FROM wp_users WHERE user_login=".$username."",$con);
$res1 = $usercheck->fetch();
$usercheck->closeCursor();
if (empty($res1["a"]))
{
$log = "genlog.txt";
$fh = fopen($log, 'a') or die("can't open file");
$date = date("m/d/Y");
$stringData = "Database write failed at ".time()." -- .\n Data entered was: ".$username."\n";
fwrite($fh, $stringData);
fclose($fh);
die('ERROR: Username does not exist.');
}
else
{
$n = 1;
while($n != 0)
{
$randstring = "live_".RandomString();
echo $randstring;
$req0 = mysql_query("SELECT COUNT(*) AS n, streamer_id FROM streamer_ids WHERE streamer_id=".$randstring."",$con);
$res0 = $req0->fetch();
$req0->closeCursor();
$n = $res0["n"];
}
$temp = mysql_query("INSERT INTO streamer_ids (username,streamer_id,premium) VALUES('".$username.",".$randstring.",0')",$con);
$temp->closeCursor();
}
}
else
echo "Wrong:".$username.""
?>
Try this, there were some syntax errors and MySql queries were not done correctly, not sure if you are using a different module, but I change it to work in generic setup.
<?php
error_reporting(E_ALL);
$con = mysql_connect("localhost","root","123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("wp_test", $con);
Function RandomString()
{
$characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
for ($i = 0; $i < 20; $i++)
{
$randstring.= $characters[rand(0, strlen($characters))];
}
return $randstring;
}
if (isset($_GET["username"]) && !empty($_GET["username"]))
{
$username = $_GET['username'];
$result = mysql_query("SELECT COUNT(*) AS a FROM wp_users WHERE user_login='".$username."'",$con);
$res1 = mysql_fetch_assoc($result);
// $usercheck->closeCursor();
if (empty($res1["a"]))
{
$log = "genlog.txt";
$fh = fopen($log, 'a') or die("can't open file");
$date = date("m/d/Y");
$stringData = "Database write failed at ".time()." -- .\n Data entered was: ".$username."\n";
fwrite($fh, $stringData);
fclose($fh);
die('ERROR: Username does not exist.');
}
else
{
$n = 1;
while($n != 0)
{
$randstring = "live_".RandomString();
echo $randstring;
$result = mysql_query("SELECT COUNT(*) AS n, streamer_id FROM streamer_ids WHERE streamer_id='".$randstring."'",$con);
$res0 = mysql_fetch_assoc($result);
// $req0->closeCursor();
$n = $res0["n"];
}
$temp = mysql_query("INSERT INTO streamer_ids (username,streamer_id,premium) VALUES('".$username."', '".$randstring."',0)",$con);
// $temp->closeCursor();
}
}
else
echo "Wrong:".$username.""
?>
Related
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.
I am trying to use the phpexcel library for loading some Excel data in to a database and everything is working fine if the user already exists - it's not showing any error.
How do I show an error message if a user already exists in the database?
Here is my code:
<?php
require('../config.php');
set_include_path(get_include_path() . PATH_SEPARATOR . 'Classes/');
include 'PHPExcel/IOFactory.php';
$inputFileName = $_FILES['filename']['tmp_name'];
try {
$objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
}
catch (Exception $e) {
die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME) . '": ' . $e->getMessage());
}
$allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
$arrayCount = count($allDataInSheet);
$ref = 1;
$today = date("Y-m-d H:i:s");
for ($i = 1; $i <= $arrayCount; $i++) {
$username = trim($allDataInSheet[$i]["A"]);
$firstname = trim($allDataInSheet[$i]["B"]);
$lastname = trim($allDataInSheet[$i]["C"]);
$email = trim($allDataInSheet[$i]["D"]);
$password = trim($allDataInSheet[$i]["E"]);
if ($username != '' || $username != 0) {
$insert_record = new stdClass();
$insert_record->username = $username;
$insert_record->email = $email;
$insert_record->firstname = $firstname;
$insert_record->lastname = $lastname;
$insert_record->password = password_hash($password, PASSWORD_DEFAULT);
$insert_record->idnumber = 1;
$insert_record->timecreated = time();
$insert_record->mnethostid = 1;
$insert_record->confirmed = 1;
$resultcheck = $DB->insert_record('user', $insert_record);
}
}
header("Location:user_management.php");
?>
for ($i = 1; $i <= $arrayCount; $i++) {
...
$resultcheck = $DB->insert_record('user', $insert_record);
if ($resultcheck == false){
header("Location:error.php");
}
}
OR if you are able to use jQuery/AJAX
for ($i = 1; $i <= $arrayCount; $i++) {
...
$resultcheck = $DB->insert_record('user', $insert_record);
if ($resultcheck == false){
echo json_encode ('Your Error Message.');
exit ();
}
}
Maybe you could add some check in your DB class
public function insert_record($table, $insert_record) {
$sql = "SELECT * FROM users WHERE username =: username";
$statement = $this->db->prepare ( $sql );
$statement->bindValue ( ':username', $insert_record->username, PDO::PARAM_STR );
$statement->execute ();
$result = $statement->fetch ( PDO::FETCH_ASSOC );
if (count($result) > 0){
return false;
}
// Do your other stuff here
}
There are multiple paths to solve the problem. It depends on your actual code.
If you set the username field as unique in your database and you're using PDO queries, you can't try and catch the error code:
try{
//Make the insert
}
catch(PDOException $e){
if($e->errorInfo[1] == 1062){
//Duplicated
}
else{
//Other errors...
}
}
This first part work very well in other script of mine. But in this example the script simply skip this part and goes to the end and execute the last query..
I don't know what I'm doing wrong because I do it exactly same yet it doesn't work. This is full script.
for ($i = 1; $i <= $numofservers; $i++)
{
if($servers[$i][1] == $server)
{
$srv = $i;
$connect = mysql_connect($servers[$srv][3], $servers[$srv][4], $servers[$srv][5]) or die('Could not connect: ' . mysql_error());
mysql_select_db($servers[$srv][6]);
}
}
$sql = mysql_query("SELECT * FROM db_users WHERE username = '".$nick."'") or die('Nick na serveru Neexistuje!' . mysql_error());
$sql = mysql_fetch_array($sql);
$balance = $sql['donate_balance'];
$steamid = $sql['steam_id'];
$balance = $balance + $price_sms;
$money = mysql_query("UPDATE db_users SET `donate_balance`='". $balance ."' WHERE steam_id = '".$steam_id."'");
<?php
$db_site_name = ''; // db connection name
$db_site_password = '';
$db_site_username = 'root'; // username of connection
$db_site_ip = '127.0.0.1:3306';
$link = mysql_connect($db_site_ip, $db_site_username, $db_site_password) or die('Could not connect: ' . mysql_error());
mysql_select_db($db_site_name) or die('Not connected<br>');
$serversquery = mysql_query("SELECT * FROM db_servers ORDER BY id");
$numofservers = 0;
while ($servers_array = mysql_fetch_array($serversquery))
{
$numofservers++;
$servers[$numofservers] = array(
$servers_array['id'],
$servers_array['name'],
$servers_array['about'],
$servers_array['server_ip'],
$servers_array['server_username'],
$servers_array['server_password'],
$servers_array['server_name'],
$servers_array['server_admin_rank'],
$servers_array['donate_factor']
);
}
if (isset($_GET["request"])){
$request_sms = ($_GET["request"]);
$status = ($_GET["status"]);
$message = ($_GET["message"]);
$request = mysql_query("UPDATE `sms_confirm` SET `status` = '".$status."' WHERE `sms_id` = '".$request_sms."'");
$findid = mysql_query("SELECT * FROM `sms_confirm` WHERE `sms_id` = '".$request_sms."' LIMIT 1") or die(mysql_error()); ;
$query = mysql_fetch_array($findid);
if ($query['status'] == 'DELIVERED' AND $query['added'] == 'false'){
$price_sms = $query['cena'];
$nick = $query['nick'];
$server = $query['server'];
for ($i = 1; $i <= $numofservers; $i++)
{
if($servers[$i][1] == $server)
{
$srv = $i;
$connect = mysql_connect($servers[$srv][3], $servers[$srv][4], $servers[$srv][5]) or die('Could not connect: ' . mysql_error());
mysql_select_db($servers[$srv][6]);
}
}
$sql = mysql_query("SELECT * FROM db_users WHERE username = '".$nick."'") or die('Nick na serveru Neexistuje!' . mysql_error());
$sql = mysql_fetch_array($sql);
$balance = $sql['donate_balance'];
$steamid = $sql['steam_id'];
$balance = $balance + $price_sms;
$money = mysql_query("UPDATE db_users SET `donate_balance`='". $balance ."' WHERE steam_id = '".$steam_id."'");
$link = mysql_connect($db_site_ip, $db_site_username, $db_site_password) or die('Could not connect: ' . mysql_error());
mysql_select_db($db_site_name) or die('Not connected<br>');
//this executes fine
$request = mysql_query("UPDATE `sms_confirm` SET `added` = 'true' WHERE `sms_id` = '".$request_sms."'");
}
}
//Header("HTTP/1.1 204 NO_CONTENT");
//Header("Content-type: text/plain");
?>
First of all, don't use mysql_* functions. It's deprecated and will be removed.
And if you want to use more than one database connection, you have to pass link to it to every function that will contact with your databases.
Eg, check here (second parameter).
Sample code
$link = mysql_connect($db_site_ip, $db_site_username, $db_site_password);
mysql_select_db($db_site_name, $link);
mysql_query($query, $link);
I try to read every word after this word #EXTINF:-1
and the next line from the local file and subsequently add the result to MySQL if it does not exist.
The contents of the file looks like this:
#EXTM3U
#EXTINF:-1,name1
http://www.name1
#EXTINF:-1,name2
http://www.name2
#EXTINF:-1,name3
http://www.name3
#EXTINF:-1,name4
http://www.name4
And my code:
$file = file("file.m3u);
array_shift($file);
$count = count($file);
if($count > 0) {
foreach($file as $row) {
$pos = strpos($row, ',');
if($pos !== false){
$getname[] = substr($row, $pos + 1);
} else {
$geturl[] = $row;
} } }
$count = count($getname);
for($i=0; $i < $count; $i++){
$name = $getname[$i];
$url = $geturl[$i];
if (empty($name)) { exit; };
if (empty($url)) { exit; }
$get_user = mysql_query("select * from users where (name = '$name')");
$show_user = mysql_fetch_array($get_user);
$userid = $show_user['userid'];
$get_url = mysql_query("select * from urls where url = '$url'");
$show_url = mysql_fetch_array($get_url);
$urlid = $show_url['urlid'];
if (empty($userid) && empty($urlid)) {
$add_user = "INSERT INTO users(name)
VALUES('$name')";
mysql_query($add_user);
$userid = mysql_insert_id();
$add_url = "INSERT INTO urls(userid, url)
VALUES('$userid', '$url')";
mysql_query($add_url);
$urlid = mysql_insert_id();
}
}
My code cannot read file correctly, because when I try check the line that I had read from file, it does not work.
The info that I try to read:
name = name1
url = http://www.name1
is for every user.
This might have something to do with it
$file = file("file.m3u);
It should be
$file = file("file.m3u");
I have this code, but when I try to execute it, it gives the following error:
Fatal error: Cannot redeclare genereerLiveCodeP() (previously declared in livestream.php:33) in livestream.php on line 32.
session_start();
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
//header("location: index.php");
if($_SESSION['***'] == '***'){
$fp = fopen("test.html", 'w');
fwrite($fp, "");
fwrite($fp, '<p class="green">*** is online</p>');
$result = mysql_query("select count(1) FROM ***");
$row = mysql_fetch_array($result);
$rows = $row[0]+1000;
echo "Rows: ".$rows."\n";
for ($id = 1000; $id < $rows; $id++) {
echo "ID: ".$id."\n";
function genereerLiveCodeP () {
$lengthCode = 6;
$characters = '1234567890abcdefghijklmnopqrstuvwxyz';
$liveCodeFunction = '';
for ($p = 0; $p < $lengthCode; $p++) {
$liveCodeFunction .= $characters[mt_rand(0, strlen($characters))];
}
return $liveCodeFunction;
}
$livecode = genereerLiveCodeP ();
echo "Livecode: ".$livecode."\n";
$x = mysql_query("UPDATE *** SET livecode='".$livecode."' WHERE *** = '".$***."'");
echo $x."\n";
}
}
What should I do?
You forgot to close the for loop before declaring the function. Your code should look like this:
...
for ($id = 1000; $id < $rows; $id++) {
echo "ID: ".$id."\n";
}
function genereerLiveCodeP () {
...
Firstly, you are using a deprecated extension (ext/mysql).
You need to move your function outside of the for loop. PHP doesn't work that way (redeclaring a function isn't possible, hence the error)
You can get a bigger boost in performance if you use a prepared query, and have far more future-proof code (your code will break in PHP 5.5 when those functions start throwing errors)
session_start();
$db = new mysqli($host, $username, $password, $db_name);
function generate_live_code($length = 6) {
$characters = '1234567890abcdefghijklmnopqrstuvwxyz';
$str = '';
for ($i = 0; $i < $length; $i++) {
$str .= $characters[mt_rand(0, strlen($characters))];
}
return $str;
}
//header("location: index.php");
if($_SESSION['id'] == 'debug') {
$fp = fopen("test.html", 'w');
fwrite($fp, "");
fwrite($fp, '<p class="green">*** is online</p>');
// writing html to a file? consider using a database...
$result = $db->query("select count(1) FROM x");
$row = $result->fetch_assoc($result);
$rows = $row[0]+1000;
echo "Rows: $rows\n"; // no need to concat with double quotes.
if ($query = $db->prepare("UPDATE x SET livecode = ? WHERE id = ?")) {
for ($id = 1000; $id < $rows; $id++) {
echo "ID: ".$id."\n";
$livecode = generate_live_code();
echo "Livecode: $livecode\n";
$query->bind_param("si", $livecode, $id);
$query->execute();
}
}
}
You are declaring function genereerLiveCodeP() inside a loop, try to put it at the beginning of the file.