Trying to: get all users by using the query in the below script into an array
Looking to get output like this:
$existing_users=array('value','value','value', 'value'...)
Php Script:
<?php
require_once('../../../inc/db/dbc.php');
$connect = mysql_connect($h, $u, $p) or die ("Cant Connect to Database.");
mysql_select_db($db);
$q = mysql_query("SELECT uUName FROM User");
$existing_users=array(
while ($row = mysql_fetch_array($q, MYSQL_NUM)) {
echo " '$row'.','";
}
);
// $existing_users=array('joe','warren','tim');
# ^^^^ manual way of doing it
//value got from the get metho
$user_name=$_POST['user_name'];
//checking weather user exists or not in $existing_users array
if (in_array($user_name, $existing_users))
{
//user name is not availble
echo "no";
}
else
{
//user name is available
echo "yes";
}
?>
How do I accomplish this? I know my while/array formation is a bit off there, how do I fix this?
Thanks
$existing_users = Array();
while(list($username) = mysql_fetch_row($q)) $existing_users[] = $username;
mysql_fetch_row($q) will give you Array(0 => result:uUName)
so list($xxx) = mysql_fetch_row($q) - $xxx is first element of Array(0 => result:uUName) equals your result:uUName.
Related
I am trying to store IP's in a MySQL database and I had a few problems with it which i was able to fix but i keep getting 1 error for people that trying to get onto my website. So when someone gets on my website their IP is displayed with a time stamp but it only works when I connect to my website. When I got my friend to go onto my website he got an error saying why u no query? which helps me find out where the problem is. Now the problem is that I have been trying to solve this issue for the past 2 hours with no luck :(
Screenshot of my screen: My screen
Screenshot of my friends screen: Friends screen
<html>
<head>
<title>Your IP!</title>
</head>
<body>
<?php
$db_host = '127.0.0.1';
$db_user = '***************';
$db_pwd = '*************';
$db = '***************';
// Find their IP and tell them what it is.
$con=mysqli_connect($db_host, $db_user, $db_pwd);
if (getenv('HTTP_X_FORWARDED_FOR')) {
$pip = getenv('HTTP_X_FORWARDED_FOR');
$ip = getenv('REMOTE_ADDR');
echo "Your Proxy IP is: ".$pip."(via ".$ip.")";
} else {
$ip = getenv('REMOTE_ADDR');
echo "Your IP is: ".$ip;
}
echo "<br /><br />";
// Try to select the database.
if(!mysqli_select_db($con, $db)) {
// die("why u no use db? ".mysql_error());
die("why u no use db?");
}
// Try to perform query.
// This is a function so it may easily be called multiple times.
function do_query($query) { // Take in query.
global $con;
if(!$result = mysqli_query($con, $query)) {
// die("why u no query? ".mysql_error());
die("why u no query?");
}
return $result; // Give back result.
}
// Try to see if they are in the database already,
// and if not, then add them.
$result = do_query("select ip from ips where ip='".$ip."'");
$rows = mysqli_num_rows($result);
if($rows == 0) {
do_query("insert into ips (ip) values ('".$ip."')");
}
// Now, display the table.
$result = do_query("select * from ips");
$cols = mysqli_num_fields($result);
echo "<table cellpadding=\"5\" bgcolor=\"#7F7F7F\"><tr>";
for($i = 0; $i < $cols; $i++) {
echo "<td>".mysqli_fetch_field($result)->name."</td>";
}
echo "</tr>";
while($row = mysqli_fetch_row($result)) {
echo "<tr>";
for($i = 0; $i < $cols; $i++) {
if($row[$i] == $ip) { // bold their IP.
echo "<td><b>".$row[$i]."</b></td>";
} else {
echo "<td>".$row[$i]."</td>";
}
}
echo "</tr>";
}
echo "</table>";
?>
</body>
</html>
So first I changed
function do_query($query) { // Take in query.
global $con;
if(!$result = mysqli_query($con, $query)) {
// die("why u no query? ".mysql_error());
die("why u no query?");
to
function do_query($query) { // Take in query.
global $con;
if(!$result = mysqli_query($con, $query)) {
// die("why u no query? ".mysql_error());
die(mysqli_error($con));
Which showed me the error which was Duplicate entry '0' for key 'PRIMARY' and the problem was that I did not set AUTO_INCREMENT on the Primary key.
I found this code once...
$sql_select = "SELECT * FROM users";
$rs_stuff = select($sql_select);
while ($res = mysql_fetch_assoc($rs_stuff)) {
echo ($res("Name")."<br />");
}
It works well, it returns all names found in "Name" col, the problem is I want it to make to return all data in that table, like if I just typed "SELECT * FROM users" on mysql, I don't understand much of PHP, I tried to do this:
echo("<br />\n".$res);
But when trying to run this on the page, I just got a empty blank with "Array" written on it...
Is it possible to do this without putting the col names in the php?
(Sorry about my English, it is not my main language.)
This happens because $res is a Array
use:
print_r($res);
or if you want a better view of it:
echo '<pre>';
print_r($res);
echo '</pre>';
OR
you can use:
echo ($res["Name"]."<br />");
also, on this second option, watch out for multidimensional arrays. Your $res might be one. In which case it will be:
echo ($res[0]["Name"]."<br />");
if you have only one result. I suggest you go with the first choice and see how your $res looks like before echoing strings ;)
Either way, please find a good PHP tutorial as it is CLEAR that you lack basic knowledge of how to use and manipulate PHP code.
Hope it helps! :D
$sql_select = "SELECT * FROM users";
$rs_stuff = select($sql_select);
echo '<table>';//create the table
while ($res = mysql_fetch_assoc($rs_stuff)) {
echo '<tr><td>'.$res['name'].'</td></tr>';
}
If you learning learn mysqli_ or PDO their is no point in learning mysql as they are depriciated.
Try this
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
print_r($row)
}
} else {
echo "0 results";
}
$conn->close();
?>
please put all your rows in an array and then print.
$sql_select = "SELECT * FROM users";
$rs_stuff = select($sql_select);
$arr = array();
while ($res = mysql_fetch_assoc($rs_stuff)) {
$arr[] = $res["Name"];
}
echo '<pre>';
print_r($arr);
echo '<pre>';
Try with this :
foreach($res as $key => $value) {
print $res[$key] . ' => ' . $value;
}
hope that helps :)
It hink this will help:
$sql_select = "SELECT * FROM users";
$rs_stuff = mysql_query($sql_select);
while ($res = mysql_fetch_assoc($rs_stuff)) {
foreach($res as $key => $value) {
echo $key.': '.$value."<br />\n";
}
echo "<br />\n";
}
Loop trough the array of values in the columns and echo out the cells value in the column.
I think this will look like this:
Name: John<br />
Usernmae: johndoe<br />
Age: 36<br />
<br />
Name: Christian<br />
Username: admin<br />
Age: 46<br />
<br />
Don't use echo to print out an array. When you use echo PHP wants to convert an array to a string. If you only want to get the arrays values use print_r. Or use this function:
function convertArraytoString($array) {
foreach($array as $key => $value) {
$return .= $key.': '.$value."<br />\n";
}
return $return;
}
Than you can convert to the array via echo convertArraytoString($res);
I am getting the id from another page but i am not being able to pass it to the sql query. If i define any value to $id instead of 0 then the query works but otherwise it fails.
Secondly, i would like to display the values of the array in respective input fields. I tried using
<?php
echo $result_array['institutename'][0];
?>
in the body part but it didnt work out.
My rest code is as follows:
(I know the mysql functions are deprecated but i would move on to mysqli as soon as i have solved this problem)
<?php
include 'connect.php';
$id=0;
$result_array=array();
if(isset($_REQUEST['id'])){
$id=(int)$_REQUEST['id'];
//$uid=$id;
if(!empty($id)){
$sql = "SELECT * FROM institute WHERE id =$id";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)){
$result_array[]=$row;
}
}
}
if ($_SERVER['REQUEST_METHOD'] == 'POST' && $_POST['form_institutedetails'] == 'saveinstitutedetails')
{
$mysql_table='institute';
$institutename = $_POST['institutename'];
$established = $_POST['established'];
$regno = $_POST['reg_no'];
$branch = $_POST['branch'];
$initials = $_POST['initials'];
$address=$_POST['address'];
$pin=$_POST['pin'];
$contact1=$_POST['contact1'];
$contact2=$_POST['contact2'];
$contact3=$_POST['contact3'];
$fax1=$_POST['fax1'];
$fax2=$_POST['fax2'];
$email=$_POST['email'];
$website=$_POST['website'];
if(isset($_POST['head_office'])){
$head_office=$_POST['head_office'];
}
else{
$head_office="Branch";
}
if (!preg_match("/^.+#.+\..+$/", $email))
{
$error_message = 'Email is not a valid email address. Please check and try again.';
}
if (empty($error_message))
{
$newinstitutename = mysql_real_escape_string($institutename);
$newestablished = mysql_real_escape_string($established);
$newregno = mysql_real_escape_string($regno);
$newbranch = mysql_real_escape_string($branch);
$newaddress = mysql_real_escape_string($address);
$newpin = mysql_real_escape_string($pin);
$newemail = mysql_real_escape_string($email);
$newwebsite = mysql_real_escape_string($website);
$ho = mysql_real_escape_string($head_office);
include 'connect.php';
$sql = "UPDATE `".$mysql_table."` SET `institutename`='$newinstitutename', `established`='$newestablished', `regno`='$newregno', `branch`='$newbranch', `initials`='$initials', `address`='$newaddress', `pin`='$newpin', `contact1`='$contact1', `contact2`='$contact2', `contact3`='$contact3', `fax1`='$fax1', `fax2`='$fax2', `email`='$newemail', `website`='$newwebsite', `head_office`='$ho' WHERE `id`=$id";
$result = mysql_query($sql, $db);
mysql_close($db);
$error_message='Updated Successfully!.';
}
}
?>
When you are unsure about the structure of an array, you can always do a print_r during development.
print_r($result_array);
In this case, it is an index array of associative arrays.
To access the first record's institutename (and probably the only record since it looks like you used an unique key in your query), you can use
echo $result_array[0]['institutename'];
<?php
include 'config.php'; //connect to db
if(isset($_REQUEST["pwd"]) && isset($_REQUEST["name"])) {
$password = $_REQUEST['pwd']; //pass from previous page
$name = $_REQUEST['name']; //pass from previous page
$checkUserPass = mysql_query("SELECT * FROM validPersonnel WHERE Passkey = '$password' and Name = '$name'", $conn); //check if the user exist
if(mysql_num_rows($checkUserPass) == 1) {
$personnelId = mysql_query("SELECT PersonnelID FROM validPersonnel WHERE Passkey = '$password' and Name = '$name'", $conn); //query user id
while($row = mysql_fetch_assoc($personnelId)) {
echo $row['PersonnelD']; // print user id
}
mysql_close($conn);
//echo "<br/><br/>";
//echo "<script>alert('Logged In.')</script>";
//header("Refresh: 1; url=profile/profile.php?id="'.$id.');
//header('Refresh: 1; url=test.php?id=$personnelId');
} else {
echo "<br/><br/>";
echo "<script>alert('Wrong Password.')</script>";
header('Refresh: 1; url=personnelselect.php');
}
}
?>
i cannot echo the $row['PersonnelD'] the page shows blank. i cannot understand where did i go wrong. this page quesion have been solved
Looks like you have mistake in code:
echo $row['PersonnelD'];
shouldn't it be following?
echo $row['PersonnelID'];
check the mysql_fetch_assoc() function may be its parameter is empty so it can't enter the while loop
Try to debug and check the values came in the variables using var_dump() function. Ex: var_dump($row); in while loop.
In both your querys, you have
"SELECT * FROM validPersonnel WHERE Passkey = '$password' and Name = '$name'"
It should be:
"SELECT * FROM validPersonnel WHERE Passkey = '".$password."' and Name = '".$name."';"
PHP doesn't recognize the $var unless you close the quotes. The period adds the $var to the string.
All this section is supposed to do is collect an int from active and use it in the if statement to continue with the code. Can somebody please tell me why this is not working?
$act_qry = "Select active FROM user_m WHERE username = '$username' and password = '$Menrypted_password'";
$result_act = mysqli_query ( $connMS, $act_qry );
$value_act = mysqli_fetch_object($result_act);
if($value_act == 1)
{
//Do php stuff.
}
I am having this table in my database:-http://prntscr.com/9tnalx
Check this code:-
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
//connect to database
$link = mysqli_connect('localhost','root','','stack');
$act_qry = "Select product_id FROM bom WHERE bom_description = 'Table Tops'";
$result_act = mysqli_query ( $link, $act_qry ) or die(mysqli_error($link));
$value_act = mysqli_fetch_object($result_act);
if($value_act->product_id == 1)
{
echo $value_act->product_id;
}
// or you can do this
$value_act = mysqli_fetch_assoc($result_act);
if($value_act['product_id'] == 1)
{
echo $value_act->product_id;
}
mysqli_close($link);
?>
Output on my browser:- http://prntscr.com/9tnazj
Note:- I hope you can understand the code by checking my screenshot of table.Thanks