I am trying to get result from as table in mySQL in the following code.
It does not work. I am newbie in PHP.
Maybe someone can help whatws wrong in my code? I think that my SQL sentence is not written well. Is it?
<?php
header("Content-type: text/html; charset=utf8");
// header('Content-Type:text/html;charset=utf-8');
//1. create connection
$connection=mysql_connect("localhost","user","pass");
if(!$connection){
die("database connection failed:" . mysql_error());
}
//2. select database
$db = mysql_select_db("database",$connection);
if(!db) {
die("database connection failed:" . mysql_error());
}
//if i want to work with hebrew databases
mysql_query("SET NAMES 'utf8'",$connection); // reading heberer from phpadmin database - only for hebrew sites
$MessageNo = $_POST['MsgNo']
//$MessageN0=(int)$MessageNo
$query = mysql_query("SELECT * FROM MessageContent WHERE MsgNo='$MessageNo'");;;
$messages = array();
while ($row = mysql_fetch_array($query)) {
$messages[] = array('MsgContId' => $row['MsgContId'], 'MsgNo' => $row['MsgNo'],'MsgContent' => $row['MsgContent'], 'AddedBy' => $row['AddedBy'],'AddedAt'=>$row['AddedAt']);
}
// echo json_encode(array('users' => $users));
echo json_encode($messages);
mysql_close($connection);
?>
I can see on this line you have formatting errors:
$query = mysql_query("SELECT * FROM MessageContent WHERE MsgNo='$MessageNo'");;;
Remove the extra two semi-colons:
$query = mysql_query("SELECT * FROM MessageContent WHERE MsgNo='$MessageNo'");
Also this:
$MessageNo = $_POST['MsgNo']
Needs a semi-colon:
$MessageNo = $_POST['MsgNo'];
Additionally you're using deprecated functions. I would suggest you look into MySQLi functions or PDO.
Consult: mysqli with prepared statements, or PDO with prepared statements.
EDIT: Also in your second query, you're not using the connection string:
$query = mysql_query("SELECT * FROM MessageContent WHERE MsgNo='$MessageNo'",$connection);
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
Also add or die(mysql_error()) to mysql_query().
Sidenote:
Your present code is open to SQL injection.
Related
I'm using PHP to try and select a single row from a table in my MySQL database. I've run the query manually inside phpMyAdmin4 and it returned the expected results. However, when I run the EXACT same query in PHP, it's returning nothing.
$query = "SELECT * FROM characters WHERE username=".$username." and charactername=".$characterName."";
if($result = $mysqli->query($query))
{
while($row = $result->fetch_row())
{
echo $row[0];
}
$result->close();
}
else
echo "No results for username ".$username." for character ".$characterName.".";
And when I test this in browser I get the "No results..." echoed back. Am I doing something wrong?
This isn't a duplicate question because I'm not asking when to use certain quotes and backticks. I'm asking for help on why my query isn't working. Quotes just happened to be incorrect, but even when corrected the problem isn't solved. Below is the edited code as well as the rest of it. I have removed my server information for obvious reasons.
<?PHP
$username = $_GET['username'];
$characterName = $_GET['characterName'];
$mysqli = new mysqli("REDACTED","REDACTED","REDACTED");
if(mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * FROM `characters` WHERE `username`='".$username."' and `charactername`='".$characterName."'";
if($result = $mysqli->query($query))
{
while($row = $result->fetch_row())
{
echo $row[0];
}
$result->close();
}
else
echo "No results for username ".$username." for character ".$characterName.".";
$mysqli->close();
?>
It's failing: $mysqli = new mysqli("REDACTED","REDACTED","REDACTED"); because you didn't choose a database.
Connecting to a database using the MySQLi API requires 4 parameters:
http://php.net/manual/en/function.mysqli-connect.php
If your password isn't required, you still need an (empty) parameter for it.
I.e.: $mysqli = new mysqli("host","user", "", "db");
Plus, as noted.
Your present code is open to SQL injection. Use mysqli_* with prepared statements, or PDO with prepared statements.
Footnotes:
As stated in the original post. Strings require to be quoted in values.
You need to add quotes to the strings in your query:
$query = "SELECT *
FROM characters
WHERE username='".$username."' and charactername='".$characterName."'";
I rarely do programming. I only know enough to be dangerous as they say and I simply assemble bits of code to get what I want. My code below seems to die at the $sql query statement. It never returns any data. It should show the 13 records that are present, but it says there is none to return. I'm guessing this is some kind of syntax error?
<?php
$host = 'myipaddress';
$user = 'myuser';
$pass = 'mypass';
$db = 'mydatabase';
$conn = mysql_connect($host, $user, $pass, $db) or die("Can not connect." . mysql_error());
// Create connection
//$conn = mysqli_connect($host, $user, $pass, $db);
// Check connection
if (!$conn) {
die("Connection failed: ");
}
$sql = "SELECT * FROM pages WHERE pid > '5'";
$result = mysql_query($conn, $sql);
if (mysql_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["pid"]. " - Name: " . $row["title"]. "<br>";
}
} else {
echo "0 results";
}
mysql_close($conn);
?>
Your using the mysql_ API right up until you try to fetch rows here, where you're using mysqli_. That will not work.
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["pid"]. " - Name: " . $row["title"]. "<br>";
}
Your script is at risk for SQL Injection Attacks. Please stop using mysql_* functions. These extensions have been removed in PHP 7. Learn about prepared statements for PDO and MySQLi and consider using PDO, it's really pretty easy.
EDIT: Your connection (Good Eyes Ralph!) string will not work because mysql_connect() doesn't accept the database as part of the connection. You must use the additional function mysql_select_db() to choose your database.
In addition, it is not necessary to specify the connection link in mysql_query() but if you do it should be the second argument:
$result = mysql_query($sql, $conn);
There is quite a bit wrong with your code.
mysql_connect($host, $user, $pass, $db)
mysql_connect() uses 3 parameters, the 4th doesn't do what you think it does.
http://php.net/manual/en/function.mysql-connect.php
You need to use mysql_select_db() http://php.net/manual/en/function.mysql-select-db.php
Then,
$result = mysql_query($conn, $sql);
The connection comes second in mysql_.
http://php.net/manual/en/function.mysql-query.php
Then you're mixing a MySQLi function mysqli_fetch_assoc which doesn't intermix with the mysql_ library.
Read: Can I mix MySQL APIs in PHP?
So, just use the full MySQLi library
http://php.net/manual/en/book.mysqli.php
or PDO:
http://php.net/manual/en/book.pdo.php
Along with a prepared statement:
https://en.wikipedia.org/wiki/Prepared_statement
Check for the real errors, should your query fail:
http://php.net/manual/en/function.mysql-error.php
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
As you can see, I did not provide you with a full rewrite, as I feel that in "Teaching a person how to fish...", will feed them for life, rather than "Throwing them a fish...", and only feed them for a day (wink).
You need to use mysql_fetch_assoc() in place of mysqli_fetch_assoc(), because your previous functions are based on mysql_*, not mysqli_*
if (mysql_num_rows($result) > 0) {
// output data of each row
while($row = mysql_fetch_assoc($result)) {
echo "id: " . $row["pid"]. " - Name: " . $row["title"]. "<br>";
}
} else {
echo "0 results";
}
I just created ajax function which sends data to php and php to database. Inserting to dotp_task_log table, works fine. But further, when I need to add data to dotp_tasks after adding to dotp_task_log, it isn't adding, and I cant find why... I get the Gerror, Here is my php file which adds data to database.
<?php
$currentUser = isset($_POST['currentUser']) ? $_POST['currentUser'] : '';
$currentTasken = isset($_POST['currentTasken']) ? $_POST['currentTasken'] : '';
$currentPercent = isset($_POST['currentPercent']) ? $_POST['currentPercent'] : '';
$con = mysql_connect("localhost", "root", "") or die(mysql_error());
if(!$con)
die('Could not connectzzz: ' . mysql_error());
mysql_select_db("foxi" , $con) or die ("could not load the database" . mysql_error());
$check = mysql_query("SELECT * FROM dotp_task_log");
$numrows = mysql_num_rows($check);
if($numrows >= 1)
{
//$pass = md5($pass);
$ins = mysql_query("INSERT INTO dotp_task_log (task_log_creator, task_log_Task) VALUES ('$currentUser' , '$currentTasken')" ) ;
if($ins)
{
$check = mysql_query("SELECT * FROM dotp_tasks");
$numrows = mysql_num_rows($check);
if($numrows > 1)
{
//$pass = md5($pass);
$inss = mysql_query("INSERT INTO dotp_tasks (task_percent_complete) VALUES ('$currentPercent') WHERE task_id='$currentTasken'" ) ;
if($inss)
{
die("Succesfully added Percent!");
}
else
{
die("GERROR");
}
}
else
{
die("Log already exists!");
}
}
else
{
die("ERROR");
}
}
else
{
die("Log already exists!");
}
?>
As I stated in comments:
INSERT... doesn't have a WHERE clause. Error checking would have signaled the syntax error. INSERT ON DUPLICATE KEY does. You may have wanted to use UPDATE instead
$inss = mysql_query("UPDATE dotp_tasks
SET task_percent_complete = '$currentPercent'
WHERE task_id='$currentTasken'" );
References:
https://dev.mysql.com/doc/refman/5.0/en/update.html
http://dev.mysql.com/doc/refman/5.6/en/insert-on-duplicate.html
Plus, do use error checking when testing:
http://php.net/manual/en/function.mysql-error.php
instead of echoing custom messages.
Add or die(mysql_error()) to mysql_query().
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
Footnotes:
Make sure your HTML form does hold a POST method and that all inputs bear the name attributes and no typos. Using error reporting, will signal that.
Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements, they're much safer.
Fred -ii- nailed it in his comment - you're using improper syntax in that query.
It looks like you want an update query, for example:
update dotp_tasks
set task_percent_complete = '$currentPercent'
where task_id = '$currentTasken'
Additionally - it's always best to avoid creating queries by formatting strings manually - you'll want to look into prepared statements to improve this code further.
We have the following code in the HTML of one of our webpages. We are trying to display all of the Wifi speeds and GPS locations in our database using the MySQL call and while loop shown in the below PHP code. However, it doesn't return anything to the page. We put echo statements in various parts of the PHP (ex. before the while loop, before the database stuff) and it doesn't even print those statements to the webpage.
<body>
<h2>WiFi Speeds in the System</h2>
<p>Speeds Recorded in the System</p>
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$dbc = mysql_connect($hostname, $username, $password)
or die('Connection Error: ' . mysql_error());
mysql_select_db('createinsertdb', $dbc) or die('DB Selection Error' .mysql_error());
$data = "(SELECT Wifi_speed AND GPS_location FROM Instance)";
$results = mysql_query($data, $dbc);
while ($row = mysql_fetch_array($results)) {
echo $row['Wifi_speed'];
echo $row['GPS_location'];
}
?>
</body>
This line is incorrect, being the AND:
$data = "(SELECT Wifi_speed AND GPS_location FROM Instance)";
^^^
Change that to and using a comma as column selectors:
$data = "(SELECT Wifi_speed, GPS_location FROM Instance)";
However, you should remove the brackets from the query:
$data = "SELECT Wifi_speed, GPS_location FROM Instance";
Read up on SELECT: https://dev.mysql.com/doc/refman/5.0/en/select.html
Using:
$results = mysql_query($data, $dbc) or die(mysql_error());
would have signaled the syntax error. Yet you should use it during testing to see if there are in fact errors in your query.
Sidenote:
AND is used for a WHERE clause in a SELECT.
I.e.:
SELECT col FROM table WHERE col_x = 'something' AND col_y = 'something_else'
Or for UPDATE, i.e.:
UPDATE table SET col_x='$var1'
WHERE col_y='$var2'
AND col_z='$var3'
Footnotes:
Consider moving to mysqli with prepared statements, or PDO with prepared statements, as mysql_ functions are deprecated and will be removed from future PHP releases.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
"Thank you for the suggest but we tried that and it didn't change anything. – sichen"
You may find that you may not be able to use those functions after all. If that is the case, then you will need to switch over to either mysqli_ or PDO.
References:
MySQLi: http://php.net/manual/en/book.mysqli.php
PDO: http://php.net/manual/en/ref.pdo-mysql.php
hi mate i see some problem with your DB connection & query
here is example check this out
in SELECT is incorrect, being the AND .using a comma as column selectors:
and make condition for after set query & check data validation that is proper method
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "createinsertdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error); }
$sql = "SELECT `Wifi_speed `, `GPS_location `, FROM `Instance`";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row['Wifi_speed'];
echo $row['GPS_location'];
}
} else {
echo "0 results";
}
$conn->close();
?>
Hi I know this is a little general but its something I cant seem to work out by reading online.
Im trying to connnect to a database using php / mysqli using a wamp server and a database which is local host on php admin.
No matter what I try i keep getting the error Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given when i try to output the contents of the database.
the code im using is:
if (isset($_POST["submit"]))
{
$con = mysqli_connect("localhost");
if ($con == true)
{
echo "Database connection established";
}
else
{
die("Unable to connect to database");
}
$result = mysqli_query($con,"SELECT *");
while($row = mysqli_fetch_array($result))
{
echo $row['login'];
}
}
I will be good if you have a look at the standard mysqli_connect here
I will dont seem to see where you have selected any data base before attempting to dump it contents.
<?php
//set up basic connection :
$con = mysqli_connect("host","user","passw","db") or die("Error " . mysqli_error($con));
?>
Following this basic standard will also help you know where prob is.
you have to select from table . or mysqli dont know what table are you selecting from.
change this
$result = mysqli_query($con,"SELECT *");
to
$result = mysqli_query($con,"SELECT * FROM table_name ");
table_name is the name of your table
and your connection is tottally wrong.
use this
$con = mysqli_connect("hostname","username","password","database_name");
you have to learn here how to connect and use mysqli