How to save variable as a string in database? - php

I am trying to save a string with number and math operator into database. I want to save the face value of string, but php or mysql is calculating the string and then saving it to the database.
For example:
$stringValue = "24/2";
$query = "UPDATE winter";
$query .= " SET value =".$stringValue;
$query .= " WHERE name = 'xyz'";
$result = mysqli_query($connection, $query);
After running the code, I want the value saved in database to be "24/2", but it is being saved as 12.

As #Uueerdo said you need to add ' sign before and after string in SQL.
$stringValue = "24/2";
$query = "UPDATE winter";
$query .= " SET value ='".$stringValue."'";
$query .= " WHERE name = 'xyz'";
$result = mysqli_query($connection, $query);
Also you probably should use prepared statements (not much longer, but more safer).
$stringValue = "24/2";
$name = "xyz";
$query = "UPDATE winter";
$query .= " SET value=?";
$query .= " WHERE name=?";
$stmt = $connection->prepare( $query );
$stmt->bind_param( 'ss', $stringValue, $name );
$stmt->execute();
$res = $stmt->get_result();

Related

MySQL alternative to Read/Modify/Write a field

In several PHP codes I have to just increment a field value from a MySQL DB.
Tipically, I use this snippet:
$sql = "SELECT IDpage, numPages FROM Pages WHERE IDpage=".$page;
$result = mysqli_query( $conn,$sql)
$row = mysqli_fetch_array($result);
$num = $row['numPages'] + 1;
$sql = "UPDATE Pages SET numPages=".$num." WHERE IDpage=".$page;;
$result = mysqli_query( $conn,$sql)
Is there any more elegant and concise method?
You don't need to fetch the data first, just do the update.
$sql = "UPDATE Pages SET numPages = numPages + 1 WHERE IDpage = ".$page;
$result = mysqli_query($conn, $sql);
Also, your snippet is missing a few semicolons.

How to run multiple query on single save button?

When I click on the save button only all_university table updates but the all_colleges table has not been updated. How can I update two tables on one save button?
<?php
if(isset($_POST['save'])) {
$chk = implode(",", $_POST['company_name']);
$sql = "update all_university set placement = '$chk' where university_name = '".$_POST['university_name']."'";
$sql = "update all_colleges set placement = '$chk' where college_name = '".$_POST['college_name']."'";
$value = mysqli_multi_query($link,$sql);
if($value == true){
$msg .="<h5 style='color:green'>Successfull</h5>";
} else {
$msg .="<h5 style='color:red'>Error!</h5>";
}
}
?>
It doesn't matter how many queries you have. Just run them all one by one.
Besides, you should be using prepared statements.
<?php
if(isset($_POST['save'])) {
$chk = implode(",", $_POST['company_name']);
$sql = "update all_university set placement = ? where university_name = ?";
$stmt = $link->prepare($sql);
$stmt->bind_param("ss", $chk, $_POST['university_name']);
$stmt->execute();
$sql = "update all_colleges set placement = ? where college_name = ?";
$stmt = $link->prepare($sql);
$stmt->bind_param("ss", $chk, $_POST['college_name']);
$stmt->execute();
$msg .="<h5 style='color:green'>Successfull</h5>";
}
DO NOT use mysqli_multi_query(). It will do you no good and won't work the way you think.
If you want to use the multi-query function, you have to concatenate the two query strings:
$sql = "update all_university set placement = '$chk' where university_name = '".$_POST['university_name']."';";
$sql .= "update all_colleges set placement = '$chk' where college_name = '".$_POST['college_name']."'";
And then execute mysqli_multi_query.
Or, as Rory already mentioned, just query twice using the normal mysqli_query function.
But you should really look into prepared statements as you are vulnerable to SQL injection!
Separate both query with semicolon (;)
$sql = "update all_university set placement = '$chk' where university_name = '".$_POST['university_name']."';";
$sql = "update all_colleges set placement = '$chk' where college_name = '".$_POST['college_name']."'";
Then, Append Both Query.
$sql = "update all_university set placement = '$chk' where university_name = '".$_POST['university_name']."'";
$sql .= "update all_colleges set placement = '$chk' where college_name = '".$_POST['college_name']."'";
Execute it.
$value = mysqli_multi_query($link,$sql);
The mysqli_multi_query() function performs one or more queries against
the database. The queries are separated with a semicolon.

print this query out put in json format to use in php webservices

i have written this query in php file to get data from database ,it is working fine and getting required data .
but how to print the retrieved data in json fromat for using web services
$query = "SELECT * ";
$query .= "FROM subjects ";
$query .= "WHERE visible = 1 ";
$query .= "ORDER BY position ASC";
$result = mysqli_query($connection, $query);
$subject = mysqli_fetch_assoc($result);
print_r($subject);
what code has to be done please help me.
Have you tried json_encode? Like:
$query = "SELECT * ";
$query .= "FROM subjects ";
$query .= "WHERE visible = 1 ";
$query .= "ORDER BY position ASC";
$result = mysqli_query($connection, $query);
$subject = mysqli_fetch_assoc($result);
echo json_encode($subject);
For more information you can check: PHP Manual
try this :
$query = "SELECT * ";
$query .= "FROM subjects ";
$query .= "WHERE visible = 1 ";
$query .= "ORDER BY position ASC";
$result = mysqli_query($connection, $query);
$subject = mysqli_fetch_assoc($result);
header('Content-Type: application/json');
echo json_encode($subject);

MySQL query went wrong

can you say me where are i am making mistakes in this simple query
$q = "UPDATE users SET ".$aItemSlot." = '$seton' WHERE username='$us'";
$r = #mysqli_query($dbc, $q);
$q = "UPDATE items SET item_position='3' WHERE it_id='$seton'";
$r = #mysqli_query($dbc, $q);
error-
1064 - You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near ''$aItemSlot' = '$seton' WHERE username='$us'' at line 1
Here is my source
$q = "SELECT * FROM users WHERE username='$us'";
$r = #mysqli_query($dbc, $r);
$row = mysqli_fetch_array($r);
$aHelmet_Slot = $row['helmet_slot'];
$aShield_Slot = $row['shield_slot'];
$aWeapon_Slot = $row['weapon_slot'];
$aGloves_Slot = $row['g1loves_slot'];
$aShoes_Slot = $row['shoes_slot'];
$aArmor_Slot = $row['armor_slot'];
$aEar_Slot = $row['ear_slot'];
$aBelt_Slot = $row['belt_slot'];
$aRing1_Slot = $row['ring1_slot'];
$aRing2_Slot = $row['ring2_slot'];
$aRing3_Slot = $row['ring3_slot'];
$aRing4_Slot = $row['ring4_slot'];
$aCharLevel = $row['char_lvl'];
if ($aItemSlot == 'ring_slot'){
if($aCharLevel >= $aItem_Level){
$NotEmpty = false;
if ($aRing1_Slot == 0){
$q = "UPDATE users SET ring1_slot='$seton' WHERE username='$us'";
$r = #mysqli_query($dbc, $q);
$NotEmpty = true;
}
if (($aRing2_Slot == 0) && (!$NotEmpty)){
$q = "UPDATE users SET ring2_slot='$seton' WHERE username='$us'";
$r = #mysqli_query($dbc, $q);
$NotEmpty = true;
}
if (($aRing3_Slot == 0) && (!$NotEmpty)){
$q = "UPDATE users SET ring3_slot='$seton' WHERE username='$us'";
$r = #mysqli_query($dbc, $q);
$NotEmpty = true;
}
if(($aRing4_Slot == 0) && (!$NotEmpty)){
$q = "UPDATE users SET ring4_slot='$seton' WHERE username='$us'";
$r = #mysqli_query($dbc, $q);
$NotEmpty = true;
}
if(!$NotEmpty){
$q = "UPDATE items SET item_position='2' WHERE it_id='$aRing1_Slot'";
$r = #mysqli_query($dbc, $q);
$q = "UPDATE users SET ring1_slot='$seton' WHERE username='$us'";
$r = #mysqli_query($dbc, $q);
$NotEmpty = true;
}
$q = "UPDATE items SET item_position='3' WHERE it_id='$seton'";
$r = #mysqli_query($dbc, $q);
}
}
else
{
if ($aCharLevel >= $aItem_Level){
$link_slot_var = "a" .$aItemSlot;
$aSlotItemID = $$link_slot_var;
if($aSlotItemID <> 0){
$q = "UPDATE items SET item_position='2' WHERE it_id='$aSlotItemID'";
$r = #mysqli_query($dbc, $q);
}
$q = "UPDATE users SET '$aItemSlot' = '.$seton.' WHERE username='$us'; // it fails there
$r = #mysqli_query($dbc, $q);
$q = "UPDATE items SET item_position='3' WHERE it_id='$seton'";
$r = #mysqli_query($dbc, $q);
}
}
There Should not be a $ symbol before the mysql database field name it should be something like this
UPDATE users SET aItemSlot = '".$seton."' WHERE username='".$us."'
Modify your query in the above format and try to execute
Why do you use a table name as variable?
{$aItemSlot}
In general it should be like this:
$mysqli->query("Update users
set aItemSlot = '$seton'
where username = $us
") ;
Also, try to use prepared statements.
UPDATE
Make update of the row which related to this table:
UPDATE [LOW_PRIORITY] [IGNORE] table_reference
SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
[WHERE where_condition]
[ORDER BY ...]
[LIMIT row_count]
UPDATE statement updates columns of existing rows in the named table
with new values. The SET clause indicates which columns to modify and
the values they should be given. Each value can be given as an
expression, or the keyword DEFAULT to set a column explicitly to its
default value. The WHERE clause, if given, specifies the conditions
that identify which rows to update. With no WHERE clause, all rows are
updated. If the ORDER BY clause is specified, the rows are updated in
the order that is specified. The LIMIT clause places a limit on the
number of rows that can be updated.
You can also perform UPDATE operations covering multiple tables.
UPDATE items,month SET items.price=month.price
WHERE items.id=month.id;
UPDATE2
You need to check/update each row.
$stmt = $mysqli->prepare("UPDATE table SET col1 = ?, col2 = ?, col3 = ? WHERE id = ? ")
$stmt->bind_param('sssi', $var1, $var2, $var3, $id);
This shows what you need to do.
You missed assignment operator :
UPDATE users SET " . $aItemSlot . " = '" . $seton . "' WHERE username='$us'";
Your query should be like this:
"UPDATE users SET " . $aItemSlot . "='$seton' WHERE username='$us'";
^ assignment operator
This is a valid syntax.. how ever you have to be sure that those params are VALID before making the query...
$sql = "UPDATE users SET {$aItemSlot} = '{$seton}' WHERE username = '{$us}'";
Try this, this will surely work
$q = "UPDATE users SET ".$aItemSlot." = " . $seton . " WHERE username= " . $us;
You will need to make some slight adjustments.
PHP/SQL
$q = "UPDATE users SET aItemSlot = '".$seton."' WHERE username='".$us."'";
// Or if $aItemSlot actually is a variable
$q = "UPDATE users SET '".$aItemSlot."'='".$seton."' WHERE username='".$us."'";
Bottom note: because $aItemSlot starts with an 'a' I am wondering if this is an array. In that case your script will fail saying that the array to string conversion has failed. If this is the case, check what value $aItemSlot holds using var_dump().

convert | separated values into new table using PHP

Edit: I forgot to add the explode part that I'm having the issues with. I need the query result exploded.
I have been messing with this for a while and have a workable procedure in mysql, however I want to accomplish this as part of a larger script. I have a table filled with IDs and several columns of data with "|" separated values. How can I use or edit the below PHP to query and insert normalized results into a new table?
If I run this with an actual string: "40|180|408|360|40|166|80|59"; It will insert values (not the ID, which I also need) but when I try to pass in query results, I get "Array to string conversion" errors. Any guidance would be appreciated.
$query = "Select id, imageSize from T1";
$result = mysqli_query($conn, $query);
$myArray = explode('|', $result);
foreach($myArray as $value) {
$sql = "INSERT INTO testExplode VALUES ($value)";
$result = mysqli_query($conn, $sql);
}
If you want to insert all of your results then:
$query = "Select id, imageSize from T1";
$myArray = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($myArray)) {
$sql = "INSERT INTO testExplode VALUES (" . mysqli_real_escape_string($conn, $row['imageSize']) . ")";
mysqli_query($conn, $sql);
}
//If just only one:
$query = "Select id, imageSize from T1";
$myArray = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($myArray);
$sql = "INSERT INTO testExplode VALUES (" . mysqli_real_escape_string($conn, $row['imageSize']) . ")";
mysqli_query($conn, $sql);
NOTE:
Avoid sql injecions by escaping your variables in your querys.
EDIT:
Based on the OP comment.
$query = "Select id, imageSize from T1";
$myArray = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($myArray)) {
$values = explode('|', $row['imageSize']);
foreach ($values as $value) {
$sql = "INSERT INTO testExplode VALUES (" . mysqli_real_escape_string($conn, $value) . ")";
mysqli_query($conn, $sql);
}
}

Categories