So, I'm writing this application in PHP where the user has a "Student's Name" and each user has a unique student name. So, before I go any further with my problem, here is the code
*Note I've already prevented the SQL injections
function hello($username123) {
// Connect to Database //
$host3 = "db";
$username3 = "db";
$password3 = "db";
$db3 = "db";
$con3 = mysqli_connect($host3,$username3,$password3,$db3) or die("Can not connect to Server.");
$query3 = mysqli_query($con3,"SELECT student1 FROM users WHERE username = '$username123'");
$student1name = "$query3";
return $student1name;
So, the person enters the username which the registered before hand and each user has a student name.I start a query which selects student1 and student1 is equal to student1name. Student 1 name is then defnied as query3. When I test it all out, all I get is (null).. Does anyone know the problem? Thank you!
I suspect what you want is something like this:
function hello($username123) {
// Connect to Database //
$host3 = "db";
$username3 = "db";
$password3 = "db";
$db3 = "db";
$con3 = mysqli_connect($host3,$username3,$password3,$db3) or die("Can not connect to Server.");
$query3 = mysqli_query($con3,"SELECT student1 FROM users WHERE username = '$username123'");
while ($row = mysqli_fetch_array($query3))
{
$student1name = $row['student1'];
}
return $student1name;
This will put the contents of the last returned row of your query, column "student1", into the variable $student1name, and return it.
You are not fetching data from result. Try this:
function hello($username123) {
// Connect to Database //
$host3 = "db";
$username3 = "db";
$password3 = "db";
$db3 = "db";
$con3 = mysqli_connect($host3,$username3,$password3,$db3)
if (!$con3)
throw new Exception("Connection error");
$result = mysqli_query($con3,"SELECT student1 FROM users WHERE username = '$username123'");
if ($result)
return $result->fetch_object();
else
throw new Exception("Query error: " . mysqli_error($con3));
}
Related
This is just a test case I wrote but my main question is my whole
application works locally connect to MySQL and return a couple thousand
records I turn error reporting on EALL for the page and I don't get any error all I actual get for output of this test case is Number Number Number Number Number five times which doesn't make any sense as I am grabbing one row
by primary key in this example. Any way I am new at PHP so any reference
for going from XAMPP to lamp would be appreciated. URL is http://prestigeworldwide.me/game/
<?php
$servername = "localhost";
$username = "root";
$password = "Mypass";
$dbname = "test";
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sqltest = sprintf("SELECT num, num2 FROM mytest WHERE num = 2");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$resulttest = mysqli_query($conn, $sqltest);
foreach($resulttest as $row){
echo("Number".$row['num'].$row['num2']);
}
mysqli_close($conn);;
?>
I suggest you to use PDO.
Take a look here.
$dbtype = "mysql";
$dbhost = "localhost";
$dbname = "*****";
$dbuser = "*****";
$dbpass = "*****";
try{
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname; charset=utf8", $dbuser,$dbpass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e){
echo $e->getMessage();
}
$sql = "SELECT num, num2 FROM mytest WHERE num = '2'";
$q = $conn->query($sql);
while ($r = $q -> fetch()):
echo "Number" . $r['num'] . $r['num2']);
endwhile;
I'm trying to use a mysqli connection to retrieve rows from my database however I continue to receive a 500 internal server error no matter what I try.
$getUserQuery = "SELECT * FROM members WHERE name = ? AND member_id > 0";
$getUserStatement = $mysqli_conn->prepare($getUserQuery);
$getUserStatement->bind_param("s", $name);
$mysqli_conn->ping() results in a value of true so I know there's no issue with the database connection. var_dump($getUserStatement) results in bool(false) so there's some issue with the prepare. Whole code:
$user_dirty = $_GET['u'];
$pass_dirty = $_GET['p'];
$getUserQuery = "SELECT * FROM members WHERE name = ? AND member_id > 0";
$getUserStatement = $mysqli_conn->prepare($getUserQuery);
if ($getUserStatement) {
echo($getUserStatement);
} else {
echo("not good");
}
$getUserStatement->bind_param("s", $user_dirty);
$getUserStatement->execute();
$getUserResult = $getUserStatement->get_result();
And how I create my DB connection:
$mysql_host = "host";
$mysql_user = "user";
$mysql_password = "pass";
$mysql_database = "db";
$mysqli_conn = new mysqli($mysql_host, $mysql_user, $mysql_password, $mysql_database);
You gets 500 internal error because statement is false probably(https://stackoverflow.com/a/845025/2962442 turn on display errors), not resource like it should be, it can be caused by lost connection, try ping or reconnect before prepare.
Example good code:
$getUserQuery = "SELECT * FROM members WHERE name = ? AND member_id > 0";
$getUserStatement = $mysqli_conn->prepare($getUserQuery);
if ($getUserStatement) {
$getUserStatement->bind_param("s", $name);
} else {
//statement is false, not good
}
and good example of connection part
$mysql_host = "host";
$mysql_user = "user";
$mysql_password = "pass";
$mysql_database = "db";
$mysqli_conn = new mysqli($mysql_host, $mysql_user, $mysql_password, $mysql_database);
if (!$mysqli_conn) {
//not connected...
}
I'm using PHP code to upload or insert data from MDB file to MySQL database.I want my table value get inserted into MySQL database. But data does not inserted into MySQL database.This code shows me no error.Here is my code. please help I have tried every solution on net.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'payroll_system';
//mysql
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
mysql_select_db($dbname);
$sql = "SELECT * FROM attendance";
$result = mysql_query($sql);
//mdb
$conn2 = new COM("ADODB.Connection") or die("Cannot start ADO");
$conn2->Open("DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=C:\\xampp\\htdocs\\payroll\\eTimeTrackLite1.mdb");
$rs = $conn2->Execute("SELECT * FROM AttendanceLogs");
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$column1=$row["AttendanceLogId"];$column2=$row["AttendanceDate"];$column3=$row["EmployeeId"];$column4=$row["InTime"];
$column6=$row["OutTime"];$column8=$row["Duration"];
echo "hello";
echo $column1;echo $column2;echo $column3;echo $column4;
$rs->MoveFirst();
while (!$rs->EOF)
{
$attendance_id = $rs->Fields("AttendanceLogId");
$attendance_date = $rs->Fields("AttendanceDate");
$emp_id = $rs->Fields("EmployeeId");
$in_time = $rs->Fields("InTime");
$out_time = $rs->Fields("OutTime");
$duration = $rs->Fields("Duration");
mysql_query("UPDATE attendance SET AttendanceLogId = '$attendance_id', AttendanceDate='$attendance_date', EmployeeId='$emp_id',InTime='$in_time',OutTime='$out_time',Duration='$duration' '"); ?>
<?php
$rs->MoveNext();
}
}
?>
</table> <?php
mysql_free_result($result);
$rs->Close();
$conn2->Close();
$rs = null;
$conn2 = null;
?>
you need to INSERT each records data instead of UPDATE. Re-write the following line:
mysql_query("UPDATE attendance SET AttendanceLogId = '$attendance_id', AttendanceDate='$attendance_date', EmployeeId='$emp_id',InTime='$in_time',OutTime='$out_time',Duration='$duration' '");
I'm trying to build a login process where, by using $_SESSION variables, the login credentials of the user are stored and used to show their relevant data from the database on screen (i.e. they will only see the school data that they work for).
<?php
session_start();
if(!isset($_SESSION['Initials'], $_SESSION['Surname']))
{
$host = "xxx";
$username = "xxx";
$password = "xxx";
$database_name = "xxx";
$table_name = "xxx";
mysql_connect($host, $username, $password) OR die("Can't
connect");
mysql_select_db($database_name) OR die("Can't connect to
Database");
$query = "SELECT Class FROM $table_name WHERE Initials = '".
$_SESSION['Initials']."' AND staff LIKE '%".$_SESSION['Surname']."'";
$result = mysql_query($query);
$class = mysql_fetch_array($result);
$count = mysql_num_rows($result);
if($count === NULL)
{
echo "ERROR";
}
else
{
$_SESSION['Class'] = $result;
echo "Class added to sessions";
}
}
?>
My initial problem where the query couldn't recognize the session variables was easily solved by adding the correct brackets for the if-statement. My next problem that has arisen here is that even though the query should be successfull (I don't receive an error message saying 'ERROR' when the $count is either FALSE or NULL) it's not creating the result array into a new session, because when I print the session array on a new page it's still only carrying over the 'Initials' and 'Surname' sessions.
What do I need to change to my query, or post-query process in order for that array (because it's bound to throw up multiple results) to be made into a new session?
Many thanks for the answers to my initial problem!
if(!isset($_SESSION['Initials'], $_SESSION['Surname'])) {
// code
}
u need { } brackets
if(!isset($_SESSION['Initials'], $_SESSION['Surname']))
$host = "xxxxx"; $username = "xxxxx"; $password = "xxxxx";
is
if(!isset($_SESSION['Initials'], $_SESSION['Surname'])) {
$host = "xxxxx";
}
$username = "xxxxx";
$password = "xxxxx";
I've found the answer - it turned out that I wasn't treating one of the session variables as a proper array and thus wouldn't load properly. I've added my script below so that people with similar problems in the future can use it as a reference point:
<?php
session_start();
// Server Details //
$host = "---";
$username = "---";
$password = "---";
$database_name = "---";
$table_name = "---";
// Connect Command //
mysql_connect($host, $username, $password) OR die("Can't
connect");
mysql_select_db($database_name) OR die("Can't connect to
Database");
// Query to call up the unique school name //
$query_school = mysql_query("SELECT DISTINCT School FROM $table_name
WHERE Initials = '".$_SESSION['---']."'
AND staff LIKE '%".$_SESSION['---']."'") or die( mysql_error());
$result_school = mysql_result($query_school, 0);
// Query to call up the unique centre no //
$query_centreno = mysql_query("SELECT DISTINCT CentreNo FROM
$table_name WHERE Initials = '".$_SESSION['---']."'
AND staff LIKE '%".$_SESSION['---']."'") or die( mysql_error());
$result_centreno = mysql_result($query_centreno, 0);
// The newly created sessions for school info //
$_SESSION['---'] = $result_school;
$_SESSION['---'] = $result_centreno;
// Query to call up the array of classes //
$query_class = mysql_query("SELECT Class FROM $table_name WHERE
Initials = '".$_SESSION['---']."'
AND staff LIKE '%".$_SESSION['---']."'") or die( mysql_error());
$query_class__array = array();
while($row = mysql_fetch_assoc($query_class))
$query_class_array[] = $row;
$_SESSION['---'] = $query_class_array;
?>
Here is what I'm trying to do: When user adds a contact to his list, the number of this contact gets run by with the numbers in the database and it gives feedback if the user is already in the database or not. Right now I always get back "User is in database" even though he isn't. Then again I'm not that well acquainted with php. I changed the code a bit again, now it doesn't work at all, because it doesn't like the part
$number = ($_GET["number"] from $DB_Table);
Full code
<?php
$DB_HostName = "localhost";
$DB_Name = "db";
$DB_User = "user";
$DB_Pass = "pw";
$DB_Table = "contacts";
$number = ($_GET["number"] from $DB_Table);
$fnumber = ($_GET["fnumber"]);
if ($number == $fnumber) {
echo "This user is already in database";
} else {
echo "This user isn't in the database";
}
$con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die (mysql_error());
mysql_select_db($DB_Name,$con) or die(mysql_error());
mysql_close($con);
?>
I don't actually see you executing the database query. You could do something like this:
<?php
$DB_HostName = "localhost";
$DB_Name = "db";
$DB_User = "user";
$DB_Pass = "pw";
$DB_Table = "contacts";
$con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die (mysql_error());
mysql_select_db($DB_Name,$con) or die(mysql_error());
$fnumber = mysql_real_escape_string($_GET["fnumber"]);
$result = mysql_query("SELECT * FROM $DB_Table WHERE Something = '$fnumber'", $con);
if ($result) {
// Check the number of rows in the result set
if (mysql_num_rows($result) > 0) {
echo "This user is already in database";
}
else echo "This user isn't in the database";
}
mysql_close($con);
?>
This is not valid PHP code: $number = ($_GET["number"] from $DB_Table);
$_GET["number"] represents the value of the "number" parameter that you find in the url of your page.
Example: http://example.com/index.php?number=7 so $_GET["number"] is 7.
In your code, $DB_Table is a just a string ("contact") and "from" does not fit there using php syntax.
mysql_select_db($DB_Name,$con) or die(mysql_error());
is valid PHP but you are not doing anything with what you get from the database. I suggest you at least take a look at this tutorial php mysql select