I am using this same code `
php $postId = 41;
<!-- hidden items and variables. Elements that will not be revealed !-->
<span id="gameLength"><?php
// MySQL connect configuration
$dbname="my_db";
$host="localhost";
$user="guessthe";
$dbh=mysql_connect ($host,$user,"correctPassword?") or die ('I cannot connect to the database because: ' . mysql_error(). '');
mysql_select_db ("$dbname") or die('I cannot select the database because: ' . mysql_error());
$sql="SELECT * FROM games WHERE postId = $postId";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
$gameId = $rows['id'];
$game100s = $rows['game100s'];
$gamesPlayedAllTime = $rows['gamesPlayed'];
$gamesPointsAllTime = $rows['gameScore'];
$gameLength = $rows['gameLength']; // get number of questions
$gameScore = $rows['gameScore'];
$gameType = $rows['gameType'];
$gametitle = $rows['gameSubTitle'];
echo $gameLength;
There is a value in the gameLength row! I can't get this code to pull any of the rows! Any idea what i'm doing wrong?
You're using MySQL, which is depcirated - and will be phased out. You should use MySQLi or PDO instead. Also, your $postId is defined outside a PHP-tag? Might just be a copy/paste mistake? Anyway, you can try the code below, which is in MySQLi:
<?php
$postId = 41;
?>
<!-- hidden items and variables. Elements that will not be revealed !-->
<span id="gameLength"><?php
// MySQL connect configuration
$dbname = "my_db";
$host = "localhost";
$user = "guessthe";
// Connecting to the database
$mysqli = new mysqli($host, $user, "correctPassword?", $dbname);
if ($mysqli->connect_errno) {
// If we are here, the connection failed
echo "Failed to connect to MySQL: (".$mysqli->connect_errno.") ".$mysqli->connect_error;
}
$sql ="SELECT * FROM games WHERE postId = $postId";
if ($result = $mysqli->query($sql)) {
// If the query was sucsessfull, we can get the rows
while ($row = $result->fetch_assoc()) {
$gameId = $row['id'];
$game100s = $row['game100s'];
$gamesPlayedAllTime = $row['gamesPlayed'];
$gamesPointsAllTime = $row['gameScore'];
$gameLength = $row['gameLength']; // get number of questions
$gameScore = $row['gameScore'];
$gameType = $row['gameType'];
$gametitle = $row['gameSubTitle'];
}
} else {
// If the query failed, do something here
}
echo $gameLength;
?>
I see some people commenting that you need to put the $postId variable inside quotes in the query, but when using double-quotes (") variables will be posted, so it's not really needed. Also note that things are case-sensitive, so if your results doesn't show, check for spelling-mistakes.
There are many errors in your code
Try this...
<?php
$postId = 41;
?>
<!-- hidden items and variables. Elements that will not be revealed !-->
<span id="gameLength">
<?php
// MySQL connect configuration
$host = "localhost";
$dbname = "my_db";
$user = "username";
$password = "password";
$dbh = mysql_connect ($host,$user,$password) or die ('I cannot connect to the database because: ' . mysql_error() . '');
mysql_select_db($dbname, $dbh) or die('I cannot select the database because: ' . mysql_error());
$sql = "SELECT * FROM games WHERE postId='$postId'";
$result = mysql_query($sql);
while($rows = mysql_fetch_array($result)){
$gameId = $rows['id'];
$game100s = $rows['game100s'];
$gamesPlayedAllTime = $rows['gamesPlayed'];
$gamesPointsAllTime = $rows['gameScore'];
$gameLength = $rows['gameLength']; // get number of questions
$gameScore = $rows['gameScore'];
$gameType = $rows['gameType'];
$gametitle = $rows['gameSubTitle'];
echo $gameLength;
}
?>
You need to fix this is your code and that should fix the error.
$sql="SELECT * FROM games WHERE postId ='".$postId."' ";
If you want all the records you can use a while loop. Here is some pseudo code.
while($row = mysql_fect_assoc($query)){
echo $row["THE THING YOU WANT"];
...
}
Related
I need to use multiple queries and send them out as well formed xml for as3 purposes.
When I use only one query everything works fine.
Problem starts when multi-query operates.
Right now when //XML header is hidden I get a structure printed on screen and it looks good.
But when header goes enabled, nothing works!
Please take a look at my code:
<?php
$dbHost = "localhost";
$dbUser = "root";
$dbPass = "";
$dbName = "test";
$dbTable = "pizzaroma";
$mysqli = mysqli_connect($dbHost, $dbUser, $dbPass, $dbName);
if ($mysqli->connect_errno)
echo "la conection ha fallado: ".$mysqli->connect_errno;
$query = "SELECT * FROM ".$dbTable." WHERE cat='pizza' AND act='1' ORDER BY ID ASC; ";
$query .= "SELECT * FROM ".$dbTable." WHERE cat='pasta' AND act='1' ORDER BY ID ASC; ";
if ($mysqli->multi_query($query)) {
// header("Content-type: text/xml");
echo "<?xml version='1.0' encoding='UTF-8'?>";
echo "<pics>";
do {
echo "<theme name='temporaly'>";
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_assoc()) {
echo "<pic name='".$row['NAME']."' desc='".$row['DESCES']."' price='".$row['PRICE']."'/>";
echo "</pic>";
}
$result->free();
}
echo "</theme>";
if ($mysqli->more_results()) {
}
}
while ($mysqli->next_result());
echo "</pics>";
}
$mysqli->close();
?>
earlier i were using "echo",.. now instead ive put "printf" there,.. but only some lines, i am not sure if that was the reason.. but now works. it was throwing me the
"Strict Standards: mysqli_next_result(): There is no next result set. Please, call mysqli_more_results()/mysqli::more_results() to check whether to call this function/method" so looking for help i have found this line there :
do{} while(mysqli_more_results($db) && mysqli_next_result($db));
that solved the problem for xml error.
<?php
$dbHost = "localhost";
$dbUser = "root";
$dbPass = "";
$dbName = "test";
$dbTable = "pizzaroma";
$mysqli = mysqli_connect($dbHost, $dbUser, $dbPass, $dbName);
if ($mysqli->connect_errno)
echo "la conection ha fallado: ".$mysqli->connect_errno;
$query = "SELECT * FROM ".$dbTable." WHERE cat='pizza' AND act='1' ORDER BY ID ASC; ";
$query .= "SELECT * FROM ".$dbTable." WHERE cat='pasta' AND act='1' ORDER BY ID ASC; ";
$query .= "SELECT * FROM ".$dbTable." WHERE cat='carne' AND act='1' ORDER BY ID ASC; ";
if ($mysqli->multi_query($query)) {
header("Content-type: text/xml");
printf( "<?xml version='1.0' encoding='UTF-8'?>");
printf( "<pics>");
do {
printf( "<theme name='temporaly'>");
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_assoc()) {
echo "<pic name='".$row['NAME']."'/>";
}
$result->free();
}
echo "</theme>";
}
while (mysqli_more_results($mysqli) && mysqli_next_result($mysqli));
echo "</pics>";
}
$mysqli->close();
?>
later on i´ve had to serialize the xml output it was easy :D
>> $i=1; and ... do {printf( "<theme name='".$i++."'>");
but now ,.. how do I associate output serialIDs to elements from array that contains category names. something like...
if name="1" then name="firtsArrayChild"
any idea?
but i think that is another song for another question out there! thanks
I want to make a auto complete text box for select employee name from DB. But it makes query error which is
Warning: mysql_fetch_array() expects parameter 1 to be resource, string given in
Following is my code.
<?php
include 'func/db_connect.php';
if(!empty($_POST["keyword"])) {
$query ="SELECT * FROM employee WHERE name like '" . $_POST["keyword"] . "%' ORDER BY name LIMIT 0,6";
$result=mysql_fetch_array($query);
if(!empty($result)) {
?>
<ul id="name-list">
<?php
foreach($result as $name) {
?>
<li onClick="selectName('<?php echo $name["name"]; ?>');"><?php echo $name["name"]; ?></li>
<?php } ?>
</ul>
<?php } } ?>
What is the wrong with this code, can anyone help me !
Try this
$result=mysql_query($query);
while($data = mysql_fetch_assoc($result))
{
$row[] = $data;
}
And change !empty($result) to count($row) > 1
You need to actually perform the query before being able to fetch the results:
$result = mysql_query("SELECT id, name FROM mytable");
$rows = mysql_fetch_array($result);
Check out the PHP docs for more in-depth examples:
http://php.net/manual/de/function.mysql-fetch-array.php
On a sidenote: using mysql_* function has been deprecated for a while, have a look into mysqli!
Try with this , you need to use mysql_query() function and you pass string directly to mysql_fetch_array()
$query = mysql_query("SELECT * FROM employee WHERE name like '" . $_POST["keyword"] . "%' ORDER BY name LIMIT 0,6");
$result = mysql_fetch_array($query);
Note : mysql_* functions deprecated and removed in PHP 7.x. Use MySQLi or PDO_MySQL extension
you have execute the query first
Deprecated features in PHP 5.5.x
The original MySQL extension is now deprecated, and will generate E_DEPRECATED errors when connecting to a database. Instead, use the MYSQLi or PDO_MySQL extensions.
<?php
// include 'func/db_connect.php';
global $conn;
$servername = "localhost"; //host name
$username = "username"; //username
$password = "password"; //password
$mysql_database = "dbname"; //database name
//mysqli prepared statement
$conn = mysqli_connect($servername, $username, $password) or die("Connection failed: " . mysqli_connect_error());
mysqli_select_db($conn,$mysql_database) or die("Opps some thing went wrong");
if(!empty($_POST["keyword"])) {
$name_val = '%'.$_POST["keyword"].'%';
$stmt = $conn->prepare("SELECT * FROM employee WHERE name like ? ORDER BY name LIMIT 0,6");
$stmt->bind_param('s',$name_val);
$qry_res=$stmt->execute();
if($row_count>0) {
?>
<ul id="name-list">
<?php
while($row = $qry_res->fetch_assoc())
{
?>
<li onClick="selectName('<?php echo $row["name"]; ?>');"><?php echo $row["name"]; ?></li>
<?php } ?>
</ul>
$stmt->close();
You can try this:
$cn=mysql_connect("localhost","root","");
if(!$cn)
{
echo "Unable to connect";
die();
}
$query = "Select * from table";
$result= mysql_query($query,$cn);
$n = mysql_num_rows($result);
if($n>0)
{
while($rw=mysql_fetch_array($result))
{
$owenername=$rw["owenername"];?>
<p>Owner Name:<?php echo $owenername;?> </p>
<?php}
}
else
{
?>data not found
<?PHP
}
?>
I am using eclipse editor. I am programming within vtiger 5.4. in my file config.inc.php the variable $default_charset is setted as
$default_charset = 'UTF-8';
I'm trying to make a sql query in mysql using the next variable
$sql = "select cod_dpto from vtiger_ubi where dpto='" . $dpto . "'";
When I print the variable $dpto I get "SAÑA", but the execution of the query mysql
$adb->query ( $sql );
doesn't work. But when I modify my query as:
$sql = "select cod_dpto from vtiger_ubi where dpto='SAÑA'";
the instruction
$adb->query ( $sql );
returns the values that I need.
Could you help me please, how can I convert my variable $dpto such that the sql query works well.
EDIT
I trying to make the query with the below code, without vtiger, and I get 0 results for thw two cases with variable and writing 'SAÑA'
$servername = "localhost";
$username = "root";
$password = "peru2006";
$dbname = "consuladoperurio_com_br_2";
$port = "3306";
// Create connection
$conn = new mysqli ( $servername, $username, $password, $dbname, $port );
// Check connection
if ($conn->connect_error) {
die ( "Connection failed: " . $conn->connect_error );
}
$sql = "select cod_dpto from vtiger_ubigeo where dpto='$dpto'";
echo $sql;
$result = $conn->query ( $sql );
if ($result->num_rows > 0) {
// output data of each row
while ( $row = $result->fetch_assoc () ) {
echo "id: " . $row ["cod_dpto"] "<br>";
}
} else {
echo "0 results";
}
$conn->close ();
Your Select statement looks like this:
$sql = "select cod_dpto from vtiger_ubi where dpto='".SAÑA."';
you'll probably want it to look like:
$sql = "select cod_dpto from vtiger_ubi where dpto='$dpto'";
Notice no concat operator, and the variable is only wrapped in single quotes.
When i run the following code it will return 100 users record from a table but when i increase the value of LIMIT from 100 to a greater number like 5000 then it will not return anything.i have total 6000 records in table. So how can i access different number of records like 2000, 3000 or even all 6000 records? kindly Guide what's wrong!
<?php
$db = mysql_connect("localhost","root","");
if (!$db) {
die('Could not connect to db: ' . mysql_error());}
mysql_select_db("distributedsms",$db);
$result = mysql_query("select * from users LIMIT 100", $db);
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['user no'] = $row['sno'];
$row_array['mnc'] = $row['mnc'];
$row_array['mcc'] = $row['mcc'];
$row_array['lac'] = $row['lac'];
$row_array['cell id'] = $row['cell id'];
$row_array['lat'] = $row['lat'];
$row_array['lng'] = $row['lng'];
$row_array['address'] = $row['address'];//push the values in the array
array_push($json_response,$row_array);
$users = $json_response;}
$fp = fopen('users_data.json', 'w+');
fwrite($fp, json_encode($json_response));
fclose($fp);
echo json_encode($json_response);
?>
First, enable error reporting in your INI or Script:
<?php error_reporting(E_ALL);
ini_set('display_errors', 1);
This will help you if there is any error/warning in case of low memory allocation or similar.
To fetch all records, you shouldn't use LIMIT, remove LIMIT from your SQL.
i.e. select * from users
You should not use mysql_connect as it is deprecated. Use mysqli_connect instead. Also, I don't think you need to iterate so much, just choose what you want in your select statement.
UPDATE: another factor on why this might be happening can also be the returned information from the database, if you have apostrophes ' in your strings and you try to use json_encode, it will break, you would need to addslashes first.
Try the following, change your LIMIT as you wish, and let me know if you still have those errors:
<?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 sno,mnc,mcc,lac,cell_id,lat,lng,address FROM users LIMIT 100";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$response = array();
while ($row = $result->fetch_assoc()) {
foreach($row as $k => $str){
$row[$k] = addslashes($str);
}
array_push($response, $row);
}
echo json_encode($response);
} else {
echo "0 results";
}
$conn->close();
?>
I have a database in which I have a main form that list all personnel using this code
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("datatest", $con);
$result = mysql_query("SELECT * FROM Personnel");
echo "<TABLE BORDER=2>";
echo"<TR><TD><B>Name</B><TD><B>Number</B><TD><B>View</B><TD></TR>";
while ($myrow = mysql_fetch_array($result))
{
echo "<TR><TD>".$myrow["Surname"]." ".$myrow["First Names"]."<TD>".$myrow["Number"];
echo "<TD>View";
}
echo "</TABLE>";
?>
</HTML>
As you can note I have a link to view details of the person but when I click on the VIEW link I get the following error
Parse error: syntax error, unexpected 'EmployeeID' (T_STRING) in C:\Program Files\EasyPHP-12.1\www\my portable files\dss4\childdetails.php on line 6
The childdetails.php has the following code
<HTML>
<?php
$db = mysql_connect("localhost", "root", "");
mysql_select_db("datatest",$db);
$result = mysql_query("SELECT * FROM children;
WHERE "EmployeeID="["$EmployeeID"],$db);
$myrow = mysql_fetch_array($result);
echo "Child Name: ".$myrow["ChildName"];
echo "<br>Mother: ".$myrow["Mother"];
echo "<br>Date of Birth: ".$myrow["DateOfBirth"];
?>
</HTML>
Since the first form to list the personnel works I believe the problem is in childdetails.php on line 6 as returned by the server but I simply don’t know how to fix it.
Note: a person can have more than one child as well as having more than one wife
Help please
I would say more like.
$result = mysql_query("SELECT * FROM children WHERE EmployeeID='$EmployeeID'");
// as far $EmployeeID is actualy set before running a query
//but as comment says don't use mysql better something like this
<?php
$mysqli = new mysqli('localhost', 'root', 'my_password', 'my_db');
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT * FROM children WHERE EmployeeID=?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $EmployeeID);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($Employee);
/* fetch value */
$stmt->fetch();
printf($Employee);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
To begin with, your query is wrong, you're telling the sql that your script is over and that it should start executing something new. I'll show you how to do it properly here below.
Also, don't use mysql specific syntax, It's outdated and can get you into real trouble later on, especially if you decide to use sqlite or postgresql.
Also, learn to use prepared statements to avoid sql injection, you want the variables to be used as strings into a prepared query, not as a possible executing script for your sql.
Use a PDO connection, you can init one like this:
// Usage: $db = connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword);
// Pre: $dbHost is the database hostname,
// $dbName is the name of the database itself,
// $dbUsername is the username to access the database,
// $dbPassword is the password for the user of the database.
// Post: $db is an PDO connection to the database, based on the input parameters.
function connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword)
{
try
{
return new PDO("mysql:host=$dbHost;dbname=$dbName;charset=UTF-8", $dbUsername, $dbPassword);
}
catch(PDOException $PDOexception)
{
exit("<p>An error ocurred: Can't connect to database. </p><p>More preciesly: ". $PDOexception->getMessage(). "</p>");
}
}
And then init the variables:
$host = 'localhost';
$user = 'root';
$dataBaseName = 'databaseName';
$pass = '';
Now you can access your database via
$db = connectToDatabase($host , $databaseName, $user, $pass); // You can make it be a global variable if you want to access it from somewhere else.
Now you should construct a query that can be used as a prepared query, that is, it accepts prepared statements so that you prepare the query and then you execute an array of variables that are to be put executed into the query, and will avoid sql injection in the meantime:
$query = "SELECT * FROM children WHERE EmployeeID = :employeeID;"; // Construct the query, making it accept a prepared variable.
$statement = $db->prepare($query); // Prepare the query.
$statement->execute(array(':employeeID' => $EmployeeID)); // Here you insert the variable, by executing it 'into' the prepared query.
$statement->setFetchMode(PDO::FETCH_ASSOC); // Set the fetch mode.
while ($row = $statement->fetch())
{
$ChildName = $row['ChildName'];
$Mother = $row['Mother'];
$DateOfBirth = $row['DateOfBirth'];
echo "Child Name: $ChildName";
echo "<br />Mother: $Mother";
echo "<br />Date of Birth: $DateOfBirth";
}
You should use a similar approach to receive $EmployeeID but this should help you a lot.
By the way: remember to close your break tags with a whitespace ' ' and a forwardslash like I showed you.
You
Need
change your query something like this
<HTML>
<?php
$db = mysql_connect("localhost", "root", "");
mysql_select_db("datatest",$db);
$result = mysql_query("SELECT * FROM children WHERE EmployeeID=" . $EmployeeID, $db);
$myrow = mysql_fetch_array($result);
echo "Child Name: ".$myrow["ChildName"];
echo "<br>Mother: ".$myrow["Mother"];
echo "<br>Date of Birth: ".$myrow["DateOfBirth"];
?>
</HTML>