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.
Related
Recently I started to learn PHP and Oracle SQL.
I am trying to fetch list of all rows from the Department table by calling selectAllDepartments function using:
#oci_fetch_all($statement, $res, null, null, OCI_FETCHSTATEMENT_BY_ROW);
The above statement executes and returns 2D array $res with correct length. But unfortunately for me empty.
I was trying to echo the $res inside the function by iterating over it the following way:
for ($x = 0; $x < count($res); $x++) {
for ($y = 0; $y < count($res[$x]); $y++) {
echo $res[$x][$y];
echo "<br>";
}
}
here is the class with function:
<?php
class DatabaseHelper
{
const username = '***';
const password = '***';
const con_string = 'lab';
// Since we need only one connection object, it can be stored in a member variable.
// $conn is set in the constructor.
protected $conn;
// Create connection in the constructor
public function __construct()
{
try {
// Create connection
$this->conn = #oci_connect(
DatabaseHelper::username,
DatabaseHelper::password,
DatabaseHelper::con_string
);
//check if the connection object is != null
if (!$this->conn) {
die("DB error: Connection can't be established!");
}
} catch (Exception $e) {
die("DB error: {$e->getMessage()}");
}
}
public function __destruct()
{
// clean up
#oci_close($this->conn);
}
public function selectAllDepartments($deptID, $deptName)
{
if ($deptID && ($deptID != '')) {
$sql = "SELECT * FROM Department WHERE departmentID like '" . $deptID . "'";
} elseif ($deptName && ($deptName != '')) {
$sql = "SELECT * FROM Department WHERE departmentName like " . $deptName . "";
} else {
$sql = "SELECT * FROM Department";
}
$statement = #oci_parse($this->conn, $sql);
#oci_execute($statement);
#oci_fetch_all($statement, $res, null, null, OCI_FETCHSTATEMENT_BY_ROW);
echo $sql;
//clean up;
#oci_free_statement($statement);
for ($x = 0; $x < count($res); $x++) {
for ($y = 0; $y < count($res[$x]); $y++) {
echo $res[$x][$y];
echo "<br>";
}
}
return $res;
}
}
I assume that I either parse the data wrongly, or something is wrong with my connection. If so, then how it could be checked?
The problem was that I was wrongly calling the array elements. It should have been done the following way:
foreach ($res as $dept) {
echo $dept['DEPARTMENTID'];
echo $dept['DEPARTMENTNAME'];
echo $dept['NUMBEROFCAGES'];
}
or similarly with ordinary for loop
so basically I am trying to create a little thing where it outputs stars, based on the database saved rating integer. The problem is it does not seem to put the number I from the database, in the variable. Here is the code I used:
<?php
$productID = 100;
$con = mysqli_connect("localhost", "root", "", "example");
function connect()
{
$con = mysqli_connect("localhost", "root", "", "example");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
return $con;
}
}
function getStars($con)
{
$productID = 100;
$sql = "SELECT rating
FROM reviews
-- JOIN stockitemstockgroups USING (StockItemID)
-- JOIN stockgroups USING (StockGroupID)
WHERE reviewID = '5'
";
$result = $con->query($sql);
if ($con && ($result->num_rows > 0)) {
// output data of each row
while ($row = $result->fetch_assoc()) {
echo $row["rating"];
}
} else {
echo "error";
}
}
$value = getStars($con);
echo $value;
for ($x = 1; $x <= $value; $x++) {
echo '<div class="rating"><span>★</span></div>';
}
?>
I'm having trouble finding a duplicate, though I'm sure this is one. You aren't returning anything from your function, so $value doesn't have a value.
function getStars($con)
{
$productID = 100;
$sql = "SELECT rating FROM reviews WHERE reviewID = 5";
$result = $con->query($sql);
if ($result && ($result->num_rows > 0)) {
// output data of first row
$row = $result->fetch_assoc();
return $row["rating"];
} else {
return false;
}
}
As a general rule, never echo from a function. Also, no need for a loop over what will presumably be a single result.
For some reason I am getting this notice in my code.
Variable $conn seems to be uninitialized
I don't understand why I'm seeing this notice. I think I'm including my include in the right place.
Class Calendar {
public function show() {
include './includes/dbconn.php';
include_once './includes/functions.php';
for ($i=0; $i<$weeksInMonth; $i++) {
// Create days in a week
for ($j=1;$j<=7;$j++) {
$cal_date = (string)$this->currentDate;
$tutor_date = display_tutor_schedule($conn,$cal_date);
if(isset($tutor_date[$j]['date'])) {
$content .= $this->_showDay($i*7+$j, $tutor_date[$j]['date']);
}
else {
$content .= $this->_showDay($i*7+$j, 0);
}
}
$content .="</tr>";
}
}
}
My $conn variable is coming from include './includes/dbconn.php';. Since I am not getting any PHP database error, such as "Not connected to the database" or something like that, I assume that my connection is right.
functions.php
function display_tutor_schedule($conn,$tutor_date) {
$query = "select * from [dbo].[TUTOR_SCHEDULE] "
. "LEFT JOIN [dbo].[TUTOR] "
. "ON [dbo].[TUTOR_SCHEDULE].tutor_id = [dbo].[TUTOR].tutor_id "
. "LEFT JOIN [dbo].[STATUS] "
. "ON [dbo].[STATUS].status_id = [dbo].[TUTOR_SCHEDULE].status_id "
. "WHERE [dbo].[TUTOR_SCHEDULE].date = '$tutor_date' " ;
$stmt = sqlsrv_query($conn, $query);
$i = 0;
$appt_detail = array();
while ($row = sqlsrv_fetch_array($stmt)) {
$appt_detail[$i]['date'] = $row['date'];
$appt_detail[$i]['t_shedule_id'] = $row['t_shedule_id'];
$appt_detail[$i]['start_time'] = $row['start_time'];
$appt_detail[$i]['end_time'] = $row['end_time'];
$appt_detail[$i]['tutor_fname'] = $row['tutor_fname'];
$appt_detail[$i]['tutor_lname'] = $row['tutor_lname'];
$appt_detail[$i]['status_name'] = $row['status_name'];
$appt_detail[$i]['status_id'] = $row['status_id'];
$i++;
}
return $appt_detail;
}
my_class.php
<?php
$calendar = new Calendar();
echo $calendar->show();
?>
dbconn.php
$serverName = "myserver";
$connectionInfo = array("Database" => "my_database", "UID" => "user", "PWD" => "pwd");
$conn = sqlsrv_connect($serverName, $connectionInfo);
If you are using NetBeans or PhpStorm, then this might be IDE issue.
Check https://netbeans.org/projects/php/lists/users/archive/2013-03/message/49 and PhpStorm warning PHP variable might not have been defined
However, it is advisable that you show us the files you include to check them.
Don't use includes or global for your variables. It's bad.
Instead you should be using classes:
class Database {
private $conn;
public function __construct(){
$serverName = "myserver";
$connectionInfo = array("Database" => "my_database",
"UID" => "user",
"PWD" => "pwd");
$this->conn = sqlsrv_connect($serverName, $connectionInfo);
}
public function get_connection(){
return $this->conn;
}
}
Calendar.php
class Calendar
{
private $conn;
public $weeksInMonth;
function __construct($conn){
$this->conn = $conn;
}
public function show()
{
$content = "";
for ($i = 0; $i < $this->weeksInMonth; $i++) {
//Create days in a week
for ($j = 1; $j <= 7; $j++) {
$cal_date = (string)$this->currentDate;
$tutor_date = display_tutor_schedule($cal_date);
if (isset($tutor_date[$j]['date'])) {
$content .= $this->_showDay($i * 7 + $j, $tutor_date[$j]['date']);
} else {
$content .= $this->_showDay($i * 7 + $j, 0);
}
}
$content .= "</tr>";
}
return $content;
}
function display_tutor_schedule($tutor_date)
{
$query = "select * from [dbo].[TUTOR_SCHEDULE] "
. "LEFT JOIN [dbo].[TUTOR] "
. "ON [dbo].[TUTOR_SCHEDULE].tutor_id = [dbo].[TUTOR].tutor_id "
. "LEFT JOIN [dbo].[STATUS] "
. "ON [dbo].[STATUS].status_id = [dbo].[TUTOR_SCHEDULE].status_id "
. "WHERE [dbo].[TUTOR_SCHEDULE].date = '$tutor_date' ";
$stmt = sqlsrv_query($this->conn, $query);
$appt_detail = array();
while ($row = sqlsrv_fetch_array($stmt)) {
$appt_detail[] = $row;
}
return $appt_detail;
}
}
Usage
$db = new Database();
$conn = $db->get_connection();
$calendar = new Calendar($conn);
$calendar->weeksInMonth = 4;
echo $calendar->show();
Since the variable is first initialized in the dbconn.php, the IDE might not recognize it. Insert
$conn = null;
after the line
public function show() {
I have two rows in my MySQL data that I would like to have code echoed only if the MySQL row data is equal to '1' (as opposed to '0'). Here's the code so far, which seems to have some severe errors:
$query = "SELECT 162, 164 FROM search WHERE title = $title";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_row()) {
if ($row["162"] = 1) {
echo '<div id="162link">1.6.2</div>';
}
}
if ($row["164"] = 1) {
echo '<div id="162link">1.6.2</div>';
}
}
}
$result->close();
}
$mysqli->close();
As it says in the code above the two rows are "162" and "164" in the database.
Use:
if ($row["162"] == 1)
Instead of:
if ($row["162"] = 1)
and:
if ($row["164"] == 1)
I tried for you something like this if it gives you some idea:
$host = "localhost";
$user = "myusername";
$pass = "mypassword";
$database = "WorldEngine";
$mysqli = new mysqli($host, $user, $pass, $database);
$title = "My Good News";
$query = "SELECT `162`, `164` FROM search WHERE title = '$title';";
if ($result = $mysqli->query($query)) {
$i = 0;
while ($row = $result->fetch_row()) {
if ($row["162"] == 1) {
echo '<div id="162link' . $i . '">1.6.2</div>';
}
if ($row["164"] == 1) {
echo '<div id="164link' . $i . '">1.6.4</div>';
}
$i++;
}
$result->free();
}
$mysqli->close();
The index $i is appended to the div ID in order to produce unique DOM element ID's in the HTML document. I would also suggest you to change your numerical column names into alphabet-starting names like c162, c164, ...
Hope this will help you.
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.""
?>