PHP issue with random mysql rows - php

I'm having a little problem with php, basically I want to get a random row from my mysql database, I am really new to php and mysql so please be kind and explain me what's going on. I've already granted all permissions on mysql, now I just have to figure out what's going on, i tried to put some echoes to debug but it seems like anything happens, there's just a blank page with nothing on it, this drives me crazy so I'd like to resolve it. Here's the code
<?php
echo "test";
$host="127.0.0.1"; // Host name
$username="username"; // Mysql username
$password="password"; // Mysql password
$db_name="mine"; // Database name
$tbl_name="accounts"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Select a random account
$min=1;
$row=mysql_fetch_assoc(mysql_query("SHOW TABLE STATUS LIKE 'mine.accounts';"));
$max=$row["Auto_increment"];
$random_id=rand($min,$max);
$row=mysql_fetch_assoc(mysql_query("SELECT * FROM `mine`.`accounts` WHERE id='$random_id'");
echo $row["username"]. ":" . $row["password"]
?>
// --- UPDATE ---
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
$host="127.0.0.1"; // Host name
$username="username"; // Mysql username
$password="password"; // Mysql password
$db_name="mine"; // Database name
$tbl_name="accounts"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Select a random account
$row = mysql_query("SELECT username AND password FROM accounts order by RAND() LIMIT 1");
WHILE ($data = mysql_fetch_array($row))
ENDWHILE;
echo $row['username'] . " " . $row['password'];
?>

On this line, you forgot the closing parentheses.
$row=mysql_fetch_assoc(mysql_query("SELECT * FROM `mine`.`accounts` WHERE id='$random_id'");
Hence the single closing parentheses while you open two.
$row=mysql_fetch_assoc(mysql_query("SELECT * FROM `mine`.`accounts` WHERE id='$random_id'"));
And you'll have to use a while loop to make $row output anything, since fetch_assoc returns an associative array:
while($row = mysql_fetch_assoc(<...>){
$max = $row['Auto_increment'];
}
Also you might wanna look into Prepared Statements or PDO as mysql_* Functions are officially deprecated.

Related

Connect to two databases on the same host at the same time

How can i connect to two databases at the same time if both databases are on the same host and i have full privileges on both databases. So i have DB-1 and DB-2. And in this case i would like to have the following script working with the two databases. Im currently using require("db.php"); to connect to one database but i would like to connect to both databases.
require("DB-1.php");
$tbl_name="System_Info";
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "SELECT COUNT(a.student_id)
FROM DB-1.TableA a
INNER JOIN DB-2.TableB b ON a.student_id = b.student_id
WHERE a.account_status = 'AVTIVE'
AND a.semesteer = '6'
AND b.assesor_status = 'PENDING'";
$q = mysql_query($sql) or die("Query failed: ".mysql_error());
while ($row = mysql_fetch_array($q))
{
echo '' . $row[0];
}
and this is what its using on DB-1 to connect
db-1.php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="DB-1"; // Database name
With MySQLi you can store the different DB connections in different variables.
<?php
$mysqlOne = new mysqli("localhost", "user", "password", "database_1");
echo $mysqlOne->host_info . "\n";
$mysqlTwo= new mysqli("127.0.0.1", "user", "password", "database_2", 3306);
$result = $mysqlTwo->query("SELECT Name FROM City LIMIT 10");
Remember, you could also utilize one database connection and just change the database you're using in the SQL, such as SELECT * FROM database3.city
See: http://www.php.net/manual/en/mysqli.quickstart.connections.php
Use mysqli (or PDO) extension for this. Mysql extension (without i) is bit outdated, and its usage is disencouraged. With mysqli you can easily make and handle several (different) connections to DB.
See: http://www.php.net/manual/en/mysqli.quickstart.connections.php
I will also recommend you to use mysqli or PDO for connecting with mysql as mysql extension is deprecated in PHP5.5.
Additionally If you dont want to move and want to run your current code, then here is the solution :
1). First remove mysql_select_db("$db_name")or die("cannot select DB");
2). and Use table names with their respective database names e.g. DBName.TableName
It should work!

Insert statement not working. not transferring into other table

Pretty new to PHP and MySQL.
I have created an insert statement in my php script, to transfer a row of data from one table to the next for certain fields. Only thing is, it doesn't seem to be working?
Can anybody see where the issue is?
<?php
require_once('auth.php');
$host=""; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name="Instruction"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql="INSERT INTO Triage (Reference,Forename,surname,D.O.B,Mobile Number,Home Number,Address,Postcode1,Email,Accident,Details);
VALUES (Reference,Forename,surname,DOB,Mobile,Home,Address,Postcode1,Email,Accident,Details)";
$result=mysql_query($sql);
//
while($rows=mysql_fetch_array($result)){
echo 'update test';
}
//
// end of while loop
echo "Successful";
echo "<BR>";
echo "<a href='list_records.php'>View result</a>";
?>
Update
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$Reference=$_REQUEST['Reference'];
$Forename=$_REQUEST['Forename'];
$surname=$_REQUEST['surname'];
$DOB=$_REQUEST['DOB'];
$Mobile=$_REQUEST['Mobile'];
$Home=$_REQUEST['Home'];
$Address=$_REQUEST['Address'];
$Postcode=$_REQUEST['Postcode1'];
$Email=$_REQUEST['Email'];
$Accident=$_REQUEST['Accident'];
$Details=$_REQUEST['Details'];
//semi colon removed
$sql="INSERT INTO Triage (Reference,Forename,surname,D.O.B,Mobile Number,Home Number,Address,Postcode1,Email,Accident,Details)
VALUES('.$Reference.','.$Forename.','.$surname.','.$DOB.','.$Mobile.','.$Home.','.$Address.','.$Postcode1.','.$Email.','.$Accident.','.$Details.')";
$result=mysql_query($sql);
echo "Successful";
echo "<BR>";
echo "<a href='list_records.php'>View result</a>";
?>
first you should fix the assignments:
$Reference=$_REQUEST['Reference'];
$Reference=$_REQUEST['Forename'];
...
should be something like:
$Reference=$_REQUEST['Reference'];
$Forename=$_REQUEST['Forename'];
$surname=$_REQUEST['surname'];
Then update the query in:
$sql="INSERT INTO Triage (Reference,Forename,surname,D.O.B,Mobile Number,Home Number,Address,Postcode1,Email,Accident,Details)
VALUES (".$Reference.",".$Forename.","...
and so on with the rest of the values.
Also
while($rows=mysql_fetch_array($result)){
won't work since result will only contain true on success.
Maybe there are more mistakes I'm not sure. But you should also check this to learn how to avoid injection:
What's the best method for sanitizing user input with PHP?
If you want to transfer data from one table to another, you should select this table somewhere. You have not anywhere in your code, you just specified columns, how is your script supposed to know where do they come from?
INSERT INTO table1 (col1, col2, col3) SELECT correspondingColumn1, correspondingColumn2, correspondingColumn3 FROM table2
P.S.: You do not use $Reference, but still, you are overwritting it
try this one
1) you mention all var name as $Reference its changed
2) query not correct plz study how wrote query..
3) REFER:http://www.w3schools.com/php/php_mysql_intro.asp
<?php
require_once('auth.php');
$host=""; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name="Instruction"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$Reference=$_REQUEST['Reference'];
$Forename=$_REQUEST['Forename'];
$surname=$_REQUEST['surname'];
$DOB=$_REQUEST['DOB'];
$Mobile=$_REQUEST['Mobile'];
$Home=$_REQUEST['Home'];
$Address=$_REQUEST['Address'];
$Postcode=$_REQUEST['Postcode1'];
$Email=$_REQUEST['Email'];
$Accident=$_REQUEST['Accident'];
$Details=$_REQUEST['Details'];
//semi colon removed
$sql="INSERT INTO Triage (Reference,Forename,surname,D.O.B,Mobile Number,Home Number,Address,Postcode1,Email,Accident,Details)
VALUES ('$Reference','$Forename','$surname','$DOB','$Mobile','$Home','$Address','$Postcode1','$Email','$Accident','$Details')";
$result=mysql_query($sql);
//
while($rows=mysql_fetch_array($result)){
echo 'update test';
}
//
// end of while loop
echo "Successful";
echo "<BR>";
echo "<a href='list_records.php'>View result</a>";
?>

Updating MySQL db

<?php
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="hsp_property"; // Database name
$tbl_name="project_directory"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
//Get values from form
$id = $_POST['id'];
$hospital = $_POST['hospital'];
$project = $_POST['project'];
$state = $_POST['state'];
$status = $_POST['status'];
$da_status = $_POST['da_status'];
$pm = $_POST['pm'];
$budgett = $_POST['budgett'];
$budgetat = $_POST['budgetat'];
$pdapproval = $_POST['pdapproval'];
$pdcs = $_POST['pdcs'];
$pdcd = $_POST['pdcd'];
$pdcf = $_POST['pdcf'];
$pnm = $_POST['pnm'];
$prm = $_POST['prm'];
$comments = $_POST['comments'];
// update data in mysql database
$sql="UPDATE $tbl_name SET Hospital='$hospital', Project='$project', State='$state',Project_Status='$status',DA_Status='$da_status',Project_Manager='$pm',Budget_Total='$budgett',Budget_Approved='$budgetat',Project_Approval_Dates='$pdapproval',Project_Contstruction_Dates='$pdcs',Project_Contract_Dates='$pdcd',Project_Current_Dates='$pdcf',Program_Next_Milestone='$pnm',Program_Milestone='$prm',Comments='$comments' WHERE id='$id'";
$result=mysql_query($sql);
// if successfully updated.
if ($result) {
header ('Location: ../project_directory.php');
}
else {
echo 'Error';
}
?>
The above is some code to update a MySQL db, i'm running WAMP to test the website before I'll upload.
I've been using the phpeasysteps tutorial as php and mysql is new to me. It's been working all ok until now.
Would love to know what i'm doing wrong, the PhpEasySteps tutorial might be a tad old as i've had to update a few elements of the initial code to get it to work..
Replace echo 'Error'; with echo mysql_error(); to see why you didn't get a result and then slap yourself for misspelling a column name or something most likely easily overlooked. If you still can't figure it out, post the error. And if you go that far, post the result of SHOW CREATE TABLE project_directory
You need to add $link_identifier to your mysql_select_db database selection,
Syntax: bool mysql_select_db ( string $database_name [, resource $link_identifier = NULL ] )
$link = mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name", $link)or die("cannot select DB");
You can use mysql_error(); function to find the mysql related errors.

Update SQL tables

I want to update a table on a specific row need some advice on my php statement
I use this statement to call the client's info
<?php
$host="localhost"; // Host name
$username="****"; // Mysql username
$password="****"; // Mysql password
$db_name="****"; // Database name
$tbl_name="members"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// get value of id that sent from address bar
$id=$_GET['id'];
// Retrieve data from database
$sql="SELECT * FROM $tbl_name WHERE member_msisdn='$query'";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
?>
This works fine echoĆ­ng the information I need and able to alter it.
<form name="form1" method="post" action="control_clientupdated.php">
This referes to my action php script
Problem I need assistance with is how do i notify my action script to use the same id I ran the query on to update that row.
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// update data in mysql database
$sql="UPDATE $tbl_name SET member_name='$member_name',
member_surname='$member_surname', member_msisdn='$member_msisdn', cid='$cid',
cofficenr='$cofficenr', cfax='$cfax', e2mobile='$e2mobile' WHERE member_msisdn='$query'";
$result=mysql_query($sql);
I have placed the WHERE statement on the end of the update
Let me just state it shows done, but it did not update the table at all
Firstly you need to store your ID into a hidden form element in your form.
<form method="post" action="control_clientupdated.php">
<input type="hidden" name="member_msisdn" value="<?=$query?>" />
...
</form>
This will allow you to passthrough the value from your first php script.
Then in your control_clientupdated.php you need to use $_POST to recover your value.
// Store the $_POST value for my query ID
$query = $_POST['member_msisdn'] ;
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// update data in mysql database
$sql="UPDATE $tbl_name SET member_name='$member_name',
member_surname='$member_surname', member_msisdn='$member_msisdn', cid='$cid',
cofficenr='$cofficenr', cfax='$cfax', e2mobile='$e2mobile' WHERE member_msisdn='$query'";
$result=mysql_query($sql);
This should be what you need - note that you cannot use $_GET to retrieve the variable passed by the form, as you are sending it with the method="post" attribute, you must use $_POST instead of $_GET

mysql_fetch_assoc() error [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Warning when using mysql_fetch_assoc in PHP
i am having a problem with the following codes, i am new in encountering this error
here is the code
session_start();
$uname=$_SESSION['login'];
$host="localhost";
$username="root";
$password="";
$db_name="sampledb";
$tbl_name="tblsched";
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "SELECT * FROM tblteacher WHERE teacherName=$uname";
$result=mysql_query($sql);
$row = mysql_fetch_assoc($result);
$teacherid = $row['teacherID'];
it gives me a "mysql_fetch_assoc() expects parameter 1 to be resource, boolean" error, how do i deal with this error?? i have used this code already a few times in other files and it worked perfectly except now, i checked the names of the rows and it was correct
i already tried using other commands such as mysql_fetch_array, mysql_result, mysql_fetch_row and it gives the same error
You seem to be using a variable that is a string, you need to encapsulate it in quotes:
SELECT * FROM tblteacher WHERE teacherName='$uname'
On that note, I see that it is coming from a Session variable, I take it that it is already cleansed to make sure there are no possible injection attacks within it - yes?
Try
$sql = "SELECT * FROM tblteacher WHERE teacherName='$uname'";
The problem is in this line
$sql = "SELECT * FROM tblteacher WHERE teacherName=$uname";
change to
$sql = "SELECT * FROM tblteacher WHERE teacherName='$uname'";
the uname is string and it should be quoted using single or double quotes.
Try This // user index no
session_start();
$uname=$_SESSION['login'];
$host="localhost";
$username="root";
$password="";
$db_name="sampledb";
$tbl_name="tblsched";
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "SELECT * FROM tblteacher WHERE teacherName=$uname";
$result=mysql_query($sql);
$row = mysql_fetch_assoc($result);
**$teacherid = $row[0];**

Categories