Simple code not working [closed] - php

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Hello guys I want to show the database on my website using this code which is given below but it's giving me annoying error again and again. I have tried everything but nothing is working it give me same error notice
Here is the error Notice
Notice: Undefined index: name in C:\xampp\htdocs\test3\index.php on line 15
Here is the PHP Code
<?php
$connect = mysql_connect("localhost","root","123");
if(!$connect) {
die("Failed to Connect: " . mysql_error());
}
if (!mysql_select_db ("login")){
die("Failed to Select DB: ". mysql_error());
}
$results = mysql_query ("Select * from users ");
while($row = mysql_fetch_array($results)){
echo $row['name'];
}
?>
I have also tried to replace mysql_fetch_array($results) with this mysqli_fetch_assoc($result) and it's also not working please run this code yourself and then give me that code. Thanks

you can use var_dump() to check the result
while($row = mysql_fetch_array($results)){
var_dump($row);
}
check the output, whether field name exists

Your database "login", table "users" doesn't have a column "name". That could be because of a typo with CaSe sEnsitivitY or other just missing.

<?php
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="test"; // Database name
$tbl_name="members"; // Table name
// Connect to server and select databse.
mysql_connect("localhost", "root", "abcd")or die("cannot connect");
mysql_select_db("testDB")or die("cannot select DB");
$sql="SELECT * FROM login WHERE userid='$myusername' and password='$mypassword'";
$result=mysql_query($sql);
//you can then mysql_fetch_array or mysql_fetch_ob
...
?>
this will surely help you

You can also simply do it this way to avoid confusion on the if's
mysql_connect("localhost","root","123") or die("Failed to Connect");
mysql_select_db ("login") or die ("cannot connect to db");
$results = mysql_query ("Select * from users ");
while($row = mysql_fetch_assoc($results))
{
echo $row['name'];
}
Since the error refers to the name, you might want to check your users table if the column name exists.

Related

PHP get data from DB not working [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 6 years ago.
Can you figure out my code? All the code does is: No database selected It won't get the data from the db. The server os is Ubuntu or OS X. I been pulling my hair out for hours.
<?php
mysqli_connect("localhost", "root", "");
mysql_select_db("hit-counter");
$sql_get_count = mysql_query("SELECT id FROM hit_info ORDER BY id DESC LIMIT 1");
if($sql_get_count === FALSE) {
die(mysql_error());
}
while($row = mysql_fetch_assoc($sql_get_count)) {
print_r($row);
}
?>
I try this, it does the same
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("hit-counter");
$sql_get_count = mysql_query("SELECT id FROM hit_info ORDER BY id DESC LIMIT 1");
if($sql_get_count === FALSE) {
die(mysql_error());
}
while($row = mysql_fetch_assoc($sql_get_count)) {
print_r($row);
}
?>
you have an error in your code. You use mysqli_ function to connect the server but you use a deprecated function mysql_ to select the database.
Try this code:
mysqli_connect("localhost", "root", "");
mysqli_select_db("hit-counter");
Another option when using mysqli_ is to select the database you want during connecting to the server:
$link = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");
You didn't mention database name:try this
<?php
$con = mysqli_connect("127.0.0.1","root","654321","testV2") or die("Some error occurred during connection " . mysqli_error($con));
// Write query
$strSQL = "SELECT id FROM did ORDER BY id DESC LIMIT 1";
// Execute the query.
$query = mysqli_query($con, $strSQL);
while($result = mysqli_fetch_array($query))
{
echo $result["id"]."
";
}
// Close the connection
mysqli_close($con);
?>
You cannot interchange the mysql and mysqli functions, please modify your mysql_select_db to mysqli_select_db.
I will not go over the errors everyone else has pointed out. But, I will mention one that no one has. I think the - character in your database name will also cause problems. You should enclose the database name in back ticks. The back tick is this ` character, most likely the far left key above the TAB key. If you had error reporting turned on, or looked at your php error log, you would have seen the error.

Ban System not working [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm developing a banning sytem for my web site and all the values are correct and I get no errors on the page, but the data does not go into the table. Here's the code for database connectivity.
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="PyroStudio"; // Database name
$tbl_name="banned"; // 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");
Here is the actual banning system itself
if ($_POST['post'])
{
//get data
$bannuser = $_POST['bannuser'];
$TypeBan = $_POST['TypeBan'];
$Reviewed = $_POST['Reviewed'];
$ModNote = $_POST['ModNote'];
$Reason = $_POST['Reason'];
$OffenItem = $_POST['OffenItem'];
$BanLengthMssg = $_POST['BanLengthMssg'];
$ReleaseMssg = $_POST['ReleaseMssg'];
$AppealMssg = $_POST['AppealMssg'];
//Connect To The Database
$connect = mysql_connect("localhost","root","");
mysql_select_db("PyroStudio");
$namecheck = mysql_query("SELECT bannuser FROM $tbl_name WHERE bannuser='$bannuser'");
$count = mysql_num_rows($namecheck);
if($count!=0)
{
die("This User Is Already Banned! <a href='home.php'>[Home]</a>");
}
//check for existance
if ($bannuser)
{
if(strlen($bannuser)>25||strlen($bannuser)<6)
{
echo "<b>Length Of Username Is Must Be Between 6 and 25 Characters Long!</b>";
}
else
{
$queryreg = mysql_query("
INSERT INTO $tbl_name VALUES ('$bannuser','$TypeBan','$Reviewed','$ModNote','$Reason','$OffenItem','$BanLengthMssg','$ReleaseMssg','$AppealMssg')
");
die ("<b>The Moderation Report Has Been Submitted! The User Is Now Banned!</b> <b><a href='home.php'>[Home]</a></b>");
}
}
}
?>
I've used this system before and now I dont know why it doesn't want to work. If you can help, that would be great.
mysql_query("SELECT bannuser FROM $tbl_name WHERE bannuser='$bannuser'");
Just don't. This is a giant gaping security hole. Also, your code may be failing because of unescaped $_POST data getting into SQL statement and breaking it. Or because you had missed something with INSERT query, since you hadn't even specified a column list. If you're interested in what is the issue, check MySQL server logs for those or the result of mysql_error() function.
Anyway, consider the following approach:
$db = new PDO("mysql:host=localhost;dbname=PyroStudio", "root", "");
$bannuser = $_POST["bannuser"];
if (strlen($bannuser) > 25 || strlen($bannuser) < 6) {
die("Invalid username.");
}
$count = $db->prepare("SELECT COUNT(*) FROM bannuser WHERE bannuser = ?")
->execute(array($bannuser))
->fetchColumn();
if ($count > 0) {
die("Already banned.");
}
$stmt = $db->prepare("INSERT INTO bannuser (bannuser, typeban, …) VALUES (:bannuser, :typeban, …)");
$stmt->bindParam("bannuser", $bannuser);
$stmt->bindParam("typeban", $_POST["typeban"]);
…
$stmt->execute();
This is not a complete code (in particular, I'm too lazy to type every inserted parameter out there) but just a rough sketch I've did from memory to get you started.

PHP API That fetches and displays a row form sql database [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have been trying to code an API that when a button is pressed on a program is fetches and displays a random row from a mysql database in this format - Text:Text - My code so far doesn't seem to work? Have a look:
<?php
// Create connection
$con=mysqli_connect("example.com","user","pass","database");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysql_query("SELECT * FROM `data_submit` ORDER BY RAND() LIMIT 0,4;");
$row = mysql_fetch_array($result);
echo $row['name'];
mysqli_close($con);
?>
Please help!!! It's really annoying.
Thanks
You're mixing mysql_* and mysqli_* extensions. You can't use them interchangeably, you must use one or the other (since mysql_* is deprecated, as per my comment above, you should consider using MySQLi). You also must loop over the result, since you're returning an array:
<?php
// Create connection
$con=mysqli_connect("example.com","user","pass","database");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con, "SELECT * FROM `data_submit` ORDER BY RAND() LIMIT 0,4;");
while ($row = mysqli_fetch_array($result)) {
echo $row['name'];
}
mysqli_close($con);
?>
You start with a mysqli_connect but switch to the mysql_query (the non-improved version). You should stick to the mysqli-library: mysqli_query and mysqli_fetch_array
Sidenote your current query will be very slow on larger tables, here is a faster one.
SELECT *
FROM table
WHERE id >= ( SELECT FLOOR( MAX(id) * RAND()) FROM table )
ORDER BY id LIMIT 4

record won't delete from database

I am trying to delete a record using php from a database. This is supposed to happen when I click a button, no error is displayed and the query appears on the screen but the record remains on the database
phpmyadmin gives me the following code to use: DELETE FROM 'the shop'.'customer' WHERE 'customer'.'CustomerID' = 8
<?php
$host="localhost"; // Host name
$tbl_name="customer"; // Table name
$db_user="root";
$db_pass="";
$connect = mysql_connect("$host", "$db_user", "$db_pass");
$db_name="the_shop"; // Database name
mysql_select_db("$db_name");
if (!$connect)
{
die("MySQL could not connect!");
}
if(isset($_GET['submit2'])){
$db_username = $_GET['username'];
$sql4 = "DELETE FROM 'the_shop'.'customer' WHERE 'customer'.'CustomerID' = 8"
or die('error deleting record');
mysql_query($sql4);
echo $sql4;
}
?>
I know this will only delete the record that has a CustomerID that = 8
my intention is that once this works I will replace CustomerID with Username and the '8' with the relevant variable that will be given a value via a form
any help is appreciated
You are using quotes instead of back tick
$sql4 = "DELETE FROM `the_shop`.`customer` WHERE `customer`.`CustomerID` = 8";
Moreover you don't need back ticks(In this case as you are not using any Reserved keywords here) as well as you are using die() at wrong place
Use this,It is working.
<?php
$host="localhost"; // Host name
$tbl_name="customer"; // Table name
$db_user="root";
$db_pass="";
$connect = mysql_connect("$host", "$db_user", "$db_pass");
$db_name="the_shop"; // Database name
mysql_select_db("$db_name",$connect);
if (!$connect)
{
die("MySQL could not connect!");
}
if(isset($_GET['submit2'])){
$db_username = $_GET['username'];
$sql4 = "DELETE FROM `the_shop`.`customer` WHERE `customer`.`CustomerID` = 8";
mysql_query($sql4,$connect) or die('error deleting record');
echo $sql4;
}
?>
Your statement is not correct. You use quoted instead of back ticks. But you can make your statement easier.
$sql4 = "DELETE FROM customer WHERE CustomerID = 8";
$sql4 = "DELETE FROM `the_shop`.`customer` WHERE `customer`.`CustomerID` = 8"
mysql_query($sql4);or die('error deleting record');
echo $sql4;
You don't need to specify which database to query in your query.
This will suffice:
DELETE FROM customer WHERE CustomerID = 8
The Mysql extension is deprecated. This means that it is no longer supported by PHP and should not be used. Try mysqli or pdo instead.
You can just use this. There is no need for you to specify the database.
delete from customer where CustomerID = 8

Php,MySql Sending Query To Database

http://jsfiddle.net/Fd9wx/
I made this to help solve my problem
so I have some php code and html code that should send sql Query's to the database upon the html table I have created like to set up new databases but then I fill out my form and click run it does not want to work for me. I did some google research and got nothing back now before you say "use PDO and This is no longer supported" PDO is hard for me to use because I dont understand some of it I will use it later on but not now, also I did make this script here from hand so dont say "contact script dev" if some one could point me in right direction to solving my problem or just way to make my sql errors show in my script? like the line what to remove and all
here is main part of my script
$tablename=$_POST['tablename'];
$value=$_POST['value'];
$type=$_POST['type'];
$length=$_POST['length'];
$collation=$_POST['collation'];
$attributes=$_POST['attributes'];
$null=$_POST['null'];
$extra=$_POST['extra'];
// Insert data into mysql
$sql="CREATE TABLE `a7972613_db`.`$tablename` (
`field1` $type( $length ) $null $extra
) ENGINE = MYISAM";
$result=mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
}
else {
echo "Please Go Back And Check Your Errors!";
}
thats my main part
The problem with your code is you have not selected the database.
$host = "xxxxx";
$database = "xxxxx";
$user = "xxxx";
$password = "xxxxx";
// Connect to server and select database.
mysql_connect("$host", "$user", "$password")or die("cannot connect");
Use below code for selecting database
// Connect to server and select database.
$conn = mysql_connect("$host", "$user", "$password")or die("cannot connect");
mysql_select_db($database,$conn);
and another problem is when your query fails, you have hardcoded the error,but use below code for checking where is the problem in your query
$result=mysql_query($sql) or die(mysql_error());
Change your query to
$result = mysql_query($sql) or die("Error with $sql: " . mysql_error());
with mysql_error(), you will see what your problem is.
You can dump your $sql string in order to see, whether it is correct
echo $sql;

Categories