I'm new to both PHP & mySQL, but I suspect some apostrophe related bug here (maybe).
For some reason the first query always seems to return null because the
echo "result: $result\n";
never prints any data. At the first call that is expected, but at the second call the player has been added to the db. My database works in the sense that I can see that rows with correct ids are added to the database (via phpMyAdmin).
Can you help me spot the error?
<?php
require_once('Db.php');
$db = new Db();
// Quote and escape form submitted values
$id = $db->quote($_POST['id']);
$score = $db->quote($_POST['score']);
$result = $db->query("SELECT `id` FROM `xxxxxx`.`Player` WHERE `id` = `$id`");
echo "result: $result\n"; // Never prints any data
if($result->num_rows == 0) {
// Row not found. Create it!
$result = $db->query("INSERT INTO `xxxxxx`.`Player` (`id`,`score`) VALUES (" . $id . "," . 0 . ")");
}
?>
First, drop those backticks from id in WHERE clause, otherwise it will take the field name from id column instead of 'id'.
Then you need to fetch data from $result:
$result = $db->query("SELECT id FROM `xxxxxx`.`Player` WHERE id = '$id'");
$row = $result->fetch_array();
echo $row['id'];
Or if there are more rows than one:
while($row = $result->fetch_array())
{
echo $row['id'];
}
You are using backticks in your query for $id. Remove them and try again.
Your query should be
$result = $db->query("SELECT `id` FROM `xxxxxx`.`Player` WHERE `id` = $id");
OR
$result = $db->query("SELECT `id` FROM `xxxxxx`.`Player` WHERE `id` = ".$id."");
Related
I need to update the initial values of a mysql column, a tokens column, at the beginning, those values are all null, then, they need to be updated, with a tokens generating function, how am doing it, it just doesn´t updates any values, see:
$query = "SELECT `id` FROM `acuses_recibo` WHERE `id_envio`=101 AND `token` IS NULL";
$result = mysqli_query($conn, $query);
here I select the id´s of those null tokens for an specific id_envio, then
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){//as long as there are token null values
foreach($row as $id=>$row['id']){
$indice = $row['id'];
$v=getToken(32);
echo $v.PHP_EOL;
echo "id es: ".$row['id'].PHP_EOL;
$queryDos = "UPDATE `acuses_recibo` SET `token`={$v} WHERE `id`={$indice} ";
mysqli_query($conn, $queryDos);
}
where getToken(32) calculates a token of length 32, this way no token is updated, the only way they get updated is if I set tokenin $queryDos to a fixed value, how could I remedy this in such a way that every token value gets updated? thanx i.a.
This is how I solved it, I separated the problem in two parts, the first just selects all the id´s for a specific id_envio as follows
$query = "SELECT `id` FROM `acuses_recibo` WHERE `id_envio`=101 AND `token` IS NULL";
$result = mysqli_query($conn, $query);
// an arrays is created and used to store the id´s selected
$members = array();
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$members[] = array('id'=> $row['id']);
}
// the connection is then closed, something I found on mysql not being explicitly multiconnection
mysqli_close($conn);
// then a new connection is setup
$connDos = mysqli_connect($servername, $username, $password, $database);
Now, the token values are updated as follows, please note that $indice has to be cast to int type because the array fetched returns strings
foreach($members as $m){
$indice = $m["id"];
$indice = intval($indice);
$voken=getToken(32);
$queryDos = " UPDATE `acuses_recibo` SET `token`='{$voken}' WHERE `id`='{$indice}' ";
if (mysqli_query($connDos, $queryDos)) {
echo "Record updated successfully".PHP_EOL;
} else {
echo "Error updating record: " . mysqli_error($connDos).PHP_EOL;
}
}
then, the second connection is closed
mysqli_close($connDos);
and this is how I could update the token values to their calculated values. I hope it helps somebody.
I am trying to insert to another table the results of a select statement from another table. The select statement works but the insert statement does not work. Please help me.
$query="SELECT * FROM subject WHERE sub_code = '$enrol' ";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$csubject=$row['sub_name'];
$cday=$row['sub_day'];
$ctime=$row['sub_time'];
echo "<strong>". $csubject . "</strong>";
}
$query = mysql_query("INSERT INTO client (client_csub_code,client_csub_name,client_csub_day,client_csub_time) VALUES ('$enrol','$csubject','$cday','$ctime')");
header("Location:homeclient.php");
?>
You asked for how to do these two as one query.
This is how:
$query = mysql_query("INSERT INTO `client` ( `client_csub_code`, `client_csub_name`, `client_csub_day`, `client_csub_time` ) SELECT `sub_code`, `sub_name`, `sub_day`, `sub_time` FROM `subject` WHERE `code` = '$enrol'");
// I would also add error checking
if ( mysql_errno() )
echo mysql_error();
$query="SELECT * FROM subject WHERE sub_code = '$enrol' ";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$csubject=$row['sub_name'];
$cday=$row['sub_day'];
$ctime=$row['sub_time'];
echo "<strong>". $csubject . "</strong>";
$query = mysql_query("INSERT INTO client (client_csub_code,client_csub_name,client_csub_day,client_csub_time) VALUES ('$enrol','$csubject','$cday','$ctime')");
}
header("Location:homeclient.php");
?>
Try changing to this. Currently your query is outside of your while, it will only run once and the values of $csubject etc are always going to be the last values of your fetched results.
I am trying to write PHP code to update a value once it exist, and if it doesn't then insert it. Part of this function works which is the insert part however the update doesn't seem to work my code is below:
<?php
$id = $_GET['Track'];
$user = $_GET['User'];
$rating = $_GET['Rating'];
include("connect.php");
$query = "UPDATE `rating` SET `rating` = '$rating' WHERE track_id = '$id' AND user_id = '$user' AND rating_set=NOW()";
$sth = $dbc->query($query);
$rows = $sth->rowCount();
if ($rows == 0) {
$query = "INSERT INTO rating values ('$id','$rating','$user',NOW())";
$results = $dbc->query($query);
$rows = $results->rowCount();
}
/* output in necessary format */
header('Content-type: application/json; charset=utf-8');
echo $_GET['onJSONPLoad'];
echo "(" . json_encode($rows) . ")";
$dbc = null;
?>
Your update query can't work.
You are only updating data where rating_set is exactly NOW(). That will most likely not fit on any data record. You probably only want to use the date part.
you are using NOW() in update query, which gives current time. Which will never be same!!! try removing '....AND rating_set=NOW()' from your update query.
$id = $_SESSION['user_id'];
$query1 = mysql_query("SELECT `user_name` FROM `users` WHERE `id` LIKE '$id'");
echo $query1;
if (mysql_num_rows($query1) == 0)
die ("User not found");
else {
$username = mysql_result($query1);
echo $username ;
}
Could someone tell me why i'd keep getting resource ID's and then 'array' echoed out?! I've tried fetch assoc and MySQL fetch and still nothing unfortunately :( I've read through the manual and still no joy!
Are you trying to display the value in the "user_name" column? If so, you need a loop that looks like this:
while($row = mysql_fetch_array($query1)) {
$username = $row['user_name'];
echo "user_name = " . $username;
}
Place it inside your "else" block, replacing what's currently inside it. The way you did it, your $username variable is getting the Result Set object, not the data inside it.
You can use mysql_result, but you have to specify the row number as a second parameter
mysql_result($query1, 0);
http://www.php.net/manual/en/function.mysql-result.php
Or you can do...
$id = $_SESSION['user_id'];
$query1 = mysql_query("SELECT `user_name` FROM `users` WHERE `id` LIKE '$id'");
if (mysql_num_rows($query1)==0){
die ("User not found");
}
while($row = mysql_fetch_array($query1)){
echo $row['user_name'];
}
By the way you do not have to use LIKE, rather = would be good.
I am using a page where a variable $submissionid is being posted to it. I would like to use this variable and pull the field subcheck from a MySQL table called submission. I would like the value of the field subcheck to simply be a new variable $subcheck. I'm not sure how to do this. I have a query below, but how to I convert the result of the query below into a variable called $subcheck? (For any given submissionid, there will only be one $subcheck.)
Thanks in advance,
John
$querysub = mysql_query("SELECT subcheck FROM submission WHERE submissionid = '$submissionid' ");
mysql_query($querysub) or die(mysql_error());
You can try:
$querysub = mysql_query("SELECT subcheck FROM submission WHERE submissionid = ".
mysql_real_escape_string($submissionid));
$result = mysql_query($querysub);
if (!$result) {
die 'Could not run query: ' . mysql_error();
}
$subcheck = mysql_result($result, 0);
This is more of a 'php' question, than it is for mysql.
Look up the 'extract' keyword for PHP Link. Effectively 'extract' takes the contents of an associative array and creates php variables (symbol table entries) using the names of keys. Each php variable will then contain the associated value.
You should be able to just:
$result = mysql_query("SELECT * FROM table");
$row = mysql_fetch_array( $result, MYSQL_ASSOC );
extract( $row ); // Create php variables, named after each column in the table.
$row["field"] == $field; // Will be a true statement after 'extract()'
Enjoy, you now have the ability to have your code dynamic adjust to a DB schema that could be changed.
-- J Jorgenson --
This should work:
$querysub = mysql_query("SELECT subcheck FROM submission WHERE submissionid = '" . $submissionid ."' ");
$result = mysql_query($querysub) or die(mysql_error());
$row = mysql_fetch_assoc( $result );
if ($row ) {
$subcheck = $row['subcheck'];
} else {
echo "Subcheck not found";
}
Be careful with the escape characters around $submissionid in your query string. In your sample, they are probably letting the name of the variable go into the string you send to the mysql server.